Docsity

C programming notes with exercises, Lecture notes of Programming Languages

Toggle sidebar
bg1
Theory
1. Explain the difference between a compiler and an interpreter in the context of C
programming.
Solution: Differences between a compiler and an interpreter in the context of C programming
are as follows:
Compiler
Interpreter
Translates the entire source code at once
Translates the source code line by line
Generates intermediate object code/executable
Executes code directly without generating an
intermediate file
Detects errors after the entire code is compiled
Stops at the first encountered error and halts
execution
Needs more memory during compilation
Requires less memory during execution
Generates machine-specific code
Requires an interpreter on each platform
Entire C source code must be compiled before
execution
Can directly execute C interactively line by
line
Binary executable produced is
platform/architecture specific
Interpreter can run on any platform with
interpreter installed
Used for creating executables to distribute
software
Used for interactive evaluation and debugging
Example: GCC (GNU Compiler Collection),
Clang
Example: Python, Ruby, JavaScript
interpreters
2. Describe the concept of data types and their significance in C programming.
Solution: Data types are fundamental to writing code in the C programming language. They
allow a C program to interpret stored data appropriately by defining the storage format,
permissible values and operations that can be performed on the data. Carefully selecting suitable
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28

Partial preview of the text

Download C programming notes with exercises and more Lecture notes Programming Languages in PDF only on Docsity!

Theory

1. Explain the difference between a compiler and an interpreter in the context of C programming. Solution: Differences between a compiler and an interpreter in the context of C programming are as follows: Compiler Interpreter Translates the entire source code at once Translates the source code line by line Generates intermediate object code/executable Executes code directly without generating an intermediate file Detects errors after the entire code is compiled Stops at the first encountered error and halts execution Needs more memory during compilation Requires less memory during execution Generates machine-specific code Requires an interpreter on each platform Entire C source code must be compiled before execution Can directly execute C interactively line by line Binary executable produced is platform/architecture specific Interpreter can run on any platform with interpreter installed Used for creating executables to distribute software Used for interactive evaluation and debugging Example: GCC (GNU Compiler Collection), Clang Example: Python, Ruby, JavaScript interpreters 2. Describe the concept of data types and their significance in C programming. Solution: Data types are fundamental to writing code in the C programming language. They allow a C program to interpret stored data appropriately by defining the storage format, permissible values and operations that can be performed on the data. Carefully selecting suitable

data types for the data being represented allows the compiler to allocate storage efficiently and helps identify problems early.

  1. Basic Data Types Integers and floating-point types comprise the basic data types offered by C to represent numeric values. Char types are used to store textual data. A. Int The int data type in C is used for representing integer numbers. Integers consist of whole numbers that may contain a positive or negative sign but do not have a decimal component. Int variables occupy either 2 bytes or 4 bytes of storage. Significance: - Permit mathematical operations like addition and subtraction to be carried out with efficiency on binary whole numbers. - Enable versatile numeric calculations not requiring fractions through an expansive value range subject to storage size. - Support efficient allocation of appropriate storage size. A short int occupies less space with a smaller range compared to a long int with a wider range. B. Float The float data type represents floating point numbers in C, numbers with fractional parts expressed with a decimal point. Float types occupy 4 bytes of storage space. Significance: - Enable mathematical computations on numbers with fractions essential for scientific and statistical programming. - Approximate real number values to about 6 decimal places of precision by default. - Define acceptable operations based on mathematical rules for fractional numbers. C. Double Double is a floating point data type in C similar to float but allowing greater precision and range of values by allocating more storage of 8 bytes. Significance: - Permit very large and very small real numbers with approximately 15 decimal digits of precision. - Suited for complex scientific calculations requiring a wider dynamic range. - Enable definitions of constants and calculations using standard scientific notation.
  • Help organize disparate data relevant to a real-world entity like employee details.
  • Elements can have different data types as per storage needs.
  • Enable component access using meaningful names for self-documenting code.
  • User-defined types aid extending the type system. The rich variety of inbuilt data types including the basic types for numeric, textual data and derived aggregate types along with storage abilities enable numerically intensive scientific computing, manipulation of diverse real-world data effectively. Careful selection of appropriate data types gives great expressive power and performance efficiency to C programs. 3. Differentiate between primary and secondary memory in the context of C programming. Solution: Differences between primary and secondary memory in the context of C programming are as follows: Primary Memory Secondary Memory RAM (Random Access Memory) Hard Disk Drive (HDD), Solid State Drive (SSD) etc. Volatile - Loses data when power is turned off Non-volatile - Retains data even when power is turned off Smaller capacity compared to secondary memory Larger capacity compared to primary memory Stores data currently being processed by the CPU Used for long-term storage of data and programs More expensive per unit of storage Generally less expensive per unit of storage Faster access times Slower access times compared to primary memory Directly accessible by the CPU Indirectly accessible, requires data transfer to primary memory for CPU access 4. Explain the concept of pointers and how they are used in C programming.

Solution: A pointer in C programming is a special variable that stores the address of another variable or data object. Therefore, pointers are used to store the memory address of another value rather than storing the actual data value itself. Characteristics of Pointers:

  • Pointers require declaration including the * operator to differentiate from other variables
  • They can only be assigned addresses of variables of the same datatype
  • Pointers can be used to access and manipulate the value stored in the referenced memory address Usage of Pointers in C:
  • Accessing and manipulating variables directly: They allow creating a reference variable that directly accesses an existing variable for retrieving and modifying its value.
  • Dynamic memory allocation: Pointers along with memory allocation functions like malloc() and free() can help dynamically allocate memory at runtime, which is then accessed via pointers.
  • Parameter passing: Pointers allow passing arguments to functions by reference instead of by value to avoid copying data. This allows direct modification of arguments in the function.
  • Referencing arrays elements: Since arrays are essentially stored at contiguous memory locations, array elements can be accessed by pointer arithmetic which allows sequential access to elements.
  • Building complex data structures: Pointers enable creation of linked lists, trees, graphs etc by storing addresses of dynamically allocated nodes and moving from one data object to another via the pointer references.
  • Function pointers: Pointers to functions, enabling functions to be passed as arguments to other functions. 5. Explain the concept of file handling and its applications in C programming. Solution: File handling refers to the ability of a programming language to access files stored on disk so programs can read and write to files for permanent storage and retrieval of data. C programming provides file handling capabilities through its standard library. File Handling Concepts in C:
  • C provides a FILE pointer to access files through the stdio.h header file
  • fopen() function is used to open a file and associate a FILE pointer
  • There are different file access modes like r, w, a, r+, w+ etc.
  • fprintf() and fscanf() allows writing formatted input/output
  • fclose function closes an open file freeing its buffer

Basic

1. Write a C program to enter two numbers and perform all arithmetic operations. Solution: #include <stdio.h> int main() { double num1, num2; printf("Enter the first number: "); scanf("%lf", &num1); printf("Enter the second number: "); scanf("%lf", &num2); printf("\nArithmetic Operations:\n"); printf("Sum: %.2f\n", num1 + num2); printf("Difference: %.2f\n", num1 - num2); printf("Product: %.2f\n", num1 * num2); if (num2 != 0) { printf("Quotient: %.2f\n", num1 / num2); } else { printf("Cannot divide by zero.\n"); } if (num2 != 0) { printf("Remainder: %.2f\n", fmod(num1, num2)); } else { printf("Cannot calculate remainder when the second number is zero.\n"); } return 0; }

Output: Enter the first number: 76. Enter the second number: 45. Arithmetic Operations: Sum: 122. Difference: 31. Product: 3512. Quotient: 1. Remainder: 31.

2. Write a C program to enter radius of a circle and find its diameter, circumference and area. Solution: #include <stdio.h> #include <math.h> int main() { double radius, diameter, circumference, area; printf("Enter the radius of the circle: "); scanf("%lf", &radius); diameter = 2 * radius; circumference = 2 * M_PI * radius; area = M_PI * pow(radius, 2); printf("\nResults:\n"); printf("Diameter: %.2f\n", diameter); printf("Circumference: %.2f\n", circumference); printf("Area: %.2f\n", area);

printf("\n%d days is equal to:\n", days); printf("Years: %d\n", years); printf("Weeks: %d\n", weeks); printf("Days: %d\n", remaining_days); return 0; }

5. C program to find area of an equilateral triangle. Solution: #include <stdio.h> #include <math.h> int main() { float side, area; printf("Enter the side length of the equilateral triangle: "); scanf("%f", &side); Area = (sqrt(3) / 4) * side * side area = (sqrt(3) / 4) * side * side; printf("\nThe area of the equilateral triangle with side %.2f units is %.2f square units.\n", side, area); return 0; } 6. C program to calculate total average and percentage of five subjects. Solution: #include <stdio.h> int main() { float subject1, subject2, subject3, subject4, subject5; float total_marks, average, percentage; printf("Enter marks of Subject 1: "); scanf("%f", &subject1); printf("Enter marks of Subject 2: "); scanf("%f", &subject2); printf("Enter marks of Subject 3: "); scanf("%f", &subject3); printf("Enter marks of Subject 4: "); scanf("%f", &subject4);

printf("Enter marks of Subject 5: "); scanf("%f", &subject5); total_marks = subject1 + subject2 + subject3 + subject4 + subject5; average = total_marks / 5; percentage = (total_marks / (5 * 100)) * 100; printf("\nTotal Marks: %.2f\n", total_marks); printf("Average Marks: %.2f\n", average); printf("Percentage: %.2f%%\n", percentage); return 0; }

Switch

1. C program to create calculator using switch case and functions. - #include <stdio.h> float add(float num1, float num2); float subtract(float num1, float num2); float multiply(float num1, float num2); float divide(float num1, float num2); int main() { int choice; float num1, num2, result; printf("Enter two numbers: "); scanf("%f %f", &num1, &num2); printf("Select operation:\n"); printf("1. Addition\n"); printf("2. Subtraction\n"); printf("3. Multiplication\n"); printf("4. Division\n"); scanf("%d", &choice); switch (choice) { case 1: result = add(num1, num2); printf("Result: %.2f\n", result); break; case 2: result = subtract(num1, num2); printf("Result: %.2f\n", result); break; case 3: result = multiply(num1, num2); printf("Result: %.2f\n", result); break; case 4: if (num2 == 0) { printf("Error! Division by zero is not allowed.\n"); } else { result = divide(num1, num2); printf("Result: %.2f\n", result);

break; default: printf("Invalid choice! Please enter a valid operation.\n"); } return 0;} float add(float num1, float num2) {return num1 + num2;} float subtract(float num1, float num2) { return num1 - num2;} float multiply(float num1, float num2) { return num1 * num2;} float divide(float num1, float num2) { return num1 / num2; }

2. C program to print number of days in a month using switch case. - #include <stdio.h> int main() { int month; printf("Enter month number (1-12): "); scanf("%d", &month); switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: printf("Number of days in month %d: 31 days\n", month); break; case 4: case 6: case 9: case 11: printf("Number of days in month %d: 30 days\n", month); break; case 2: printf("Number of days in month 2: 28 or 29 days (leap year or non-leap year)\n"); break; default: printf("Invalid month number! Please enter a number between 1 and 12.\n"); } return 0; }

printf("%d is zero.\n", number); break; default: printf("Invalid input!\n"); break; } return 0; }

5. C program to find all roots of a quadratic equation using switch case. - #include <stdio.h> #include <math.h> int main() { float a, b, c; float discriminant, root1, root2, realPart, imaginaryPart; printf("Enter coefficients a, b, and c of the quadratic equation (ax^2 + bx + c = 0): "); scanf("%f %f %f", &a, &b, &c); // Calculate discriminant discriminant = b * b - 4 * a * c; switch (discriminant > 0? 1 : (discriminant == 0? 0 : - 1)) { case 1: // Real and distinct roots root1 = (-b + sqrt(discriminant)) / (2 * a); root2 = (-b - sqrt(discriminant)) / (2 * a); printf("Roots are real and distinct.\n"); printf("Root 1 = %.2f and Root 2 = %.2f\n", root1, root2); break; case 0: // Real and equal roots root1 = root2 = - b / (2 * a); printf("Roots are real and equal.\n"); printf("Root 1 = Root 2 = %.2f\n", root1); break; case - 1: // Complex roots realPart = - b / (2 * a); imaginaryPart = sqrt(-discriminant) / (2 * a);

printf("Roots are complex and imaginary.\n"); printf("Root 1 = %.2f + %.2fi and Root 2 = %.2f - %.2fi\n", realPart, imaginaryPart, realPart, imaginaryPart); break; default: printf("Invalid coefficients! Please enter valid values.\n"); break; } return 0; }

for (col = 1; col <= stars; col++) { printf("*"); } printf("\n"); spaces++; stars - = 2; } return 0; }

3. C program to print hollow pyramid - #include <stdio.h> int main() { int rows, spaces, stars, row, col; printf("Enter the number of rows for the hollow pyramid: "); scanf("%d", &rows); spaces = rows - 1; stars = 1; for (row = 1; row <= rows; row++) { for (col = 1; col <= spaces; col++) { printf(" "); } for (col = 1; col <= stars; col++) { if (row == rows || col == 1 || col == stars) { printf("*"); } else { printf(" "); } } printf("\n"); spaces--; stars += 2; } return 0; } 4. C program to print square or rectangle star pattern

#include <stdio.h> int main() { int rows, cols, row, col; printf("Enter number of rows: "); scanf("%d", &rows); printf("Enter number of columns: "); scanf("%d", &cols); for (row = 1; row <= rows; row++) { for (col = 1; col <= cols; col++) { if (row == 1 || row == rows || col == 1 || col == cols) { printf("* "); } else { printf(" "); } } printf("\n"); } return 0; }

5. C program to print hollow square or rectangle star pattern. - #include <stdio.h> int main() { int rows, cols, row, col; printf("Enter number of rows: "); scanf("%d", &rows); printf("Enter number of columns: "); scanf("%d", &cols); for (row = 1; row <= rows; row++) { for (col = 1; col <= cols; col++) { if (row == 1 || row == rows || col == 1 || col == cols) { printf("* "); } else { printf(" "); } } printf("\n");