0% found this document useful (0 votes)
14 views

Programming For Problem Solving Using C and C RBU

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Programming For Problem Solving Using C and C RBU

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Programming for problem solving using

C/C++ Lab Manual

B.Tech(AIML & CTIS ),


Ist Semester, RBU NextGen
June 20, 2023
Contents
1 C Basics, Operators, Loops 5

1.1 Even or Odd Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

1.2 Simple Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

1.3 Quadratic Equation Solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

1.4 Factorial Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

1.5 Fibonacci Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

1.6 Prime Number Check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

1.7 Sum of Digits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

1.8 Patterns with Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

1.9 Count Vowels and Consonants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

1.10 Find the Greatest Common Divisor (GCD) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

1.11 Multiplication Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

1.12 Count Digits in a Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

1.13 Sum of First N Natural Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

2 Arrays & Functions 22

2.1 Reverse an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

2.2 Find and Display Largest and Smallest Elements in an Array . . . . . . . . . . . . . . . . . . . . . . . . 25

2.3 Add Two 2x2 Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

2.4 Find the Transpose of a 3x3 Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

2.5 Calculate the Length of a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

2.6 Concatenate Two Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

3 Structures and Unions 31

3.1 Define and Use a Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

3.2 Nested Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

3.3 Array of Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

3.4 Functions and Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

3.5 Unions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

3.6 Bit-fields and Enumerated Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

4 Pointers & File Handling 40

4.1 Pointer Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

4.2 Pointer Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

4.3 Dynamic Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

4.4 Pointer to a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

4.5 Pointer to Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46


4.6 Writing to a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

4.7 Reading from a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

4.8 Appending to a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

4.9 Copying File Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

4.10 File Operations with Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

5 Strings 51

5.1 Declare and Display a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

5.2 String Declaration and Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

5.3 String Initialization with Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

5.4 String Initialization with Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

5.5 Using strcpy() and strlen() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

5.6 Using strcmp() and strcat() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

5.7 Check Null-Termination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

5.8 Null-Terminated String Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

5.9 Char Array and Pointer Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

5.10 Pointer Arithmetic with Char Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

5.11 Pointers and Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

5.12 Substring Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

5.13 Count Substring Occurrences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

5.14 Tokenization Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

5.15 Tokenization with Different Delimiters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

5.16 String to Integer Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

5.17 String to Integer with Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69


This unit covers
• C Basics, Operators, Loops Exercises

• C Arrays & Functions Exercises

• Exercises on Structures and Unions

• Exercises on Pointers & File Handling

• Exercises on Strings
1 C Basics, Operators, Loops
C is a general-purpose, procedural programming language widely used for system and application software. It provides a

strong foundation for understanding more complex programming concepts and languages.

1 # include < stdio .h >


2

3 int main () {
4 // code
5 return 0;
6 }

• #include <stdio.h>: Preprocessor directive to include the Standard Input Output library.

• int main(): Main function where execution starts.

• return 0;: Ends the program and returns control to the operating system.

Operators
Operators are symbols used to perform operations on variables and values. C supports several types of operators:

Arithmetic Operators

Perform basic arithmetic operations.

• + (Addition)

• - (Subtraction)

• * (Multiplication)

• / (Division)

• % (Modulus)

Syntax:

1 int a = 10;
2 int b = 5;
3 int sum = a + b ; // sum is 15

Relational Operators

Compare two values.

• == (Equal to)

• != (Not equal to)

• > (Greater than)

• < (Less than)

• >= (Greater than or equal to)

• <= (Less than or equal to)

Syntax:
1 int a = 10;
2 int b = 5;
3 int result = ( a > b ) ; // result is 1 ( true )

Logical Operators

Combine conditional statements.

• (Logical AND)

• || (Logical OR)

• ! (Logical NOT)

Syntax:

1 int a = 10;
2 int b = 5;
3 int result = ( a > b ) && ( b > 0) ; // result is 1 ( true )

Assignment Operators

Assign values to variables.

• = (Simple assignment)

• += (Add and assign)

• -= (Subtract and assign)

• *= (Multiply and assign)

• /= (Divide and assign)

• %= (Modulus and assign)

Syntax:

1 int a = 10;
2 a += 5; // a is now 15

Increment and Decrement Operators

Increase or decrease value by 1.

• ++ (Increment)

• – (Decrement)

Syntax:

1 int a = 10;
2 a ++; // a is now 11

Control statements
Control statements in C allow you to alter the flow of execution in your program. They enable conditional execution

and looping, which are fundamental to programming logic.


If Statement
Executes a block of code if a specified condition is true.

Syntax:

1 if ( condition ) {
2 // code to execute if condition is true
3 }

Example:

1 int a = 10;
2 if ( a > 5) {
3 printf ( " a is greater than 5\ n " ) ;
4 }

If-Else Statement
Executes one block of code if the condition is true and another block if the condition is false.

Syntax:

1 if ( condition ) {
2 // code to execute if condition is true
3 } else {
4 // code to execute if condition is false
5 }

Example:

1 int a = 10;
2 if ( a > 5) {
3 printf ( " a is greater than 5\ n " ) ;
4 } else {
5 printf ( " a is not greater than 5\ n " ) ;
6 }

If-Else If-Else Statement


Used to check multiple conditions.

Syntax:

1 if ( condition1 ) {
2 // code to execute if condition1 is true
3 } else if ( condition2 ) {
4 // code to execute if condition2 is true
5 } else {
6 // code to execute if none of the conditions are true
7 }

Example:

1 int a = 10;
2 if ( a > 15) {
3 printf ( " a is greater than 15\ n " ) ;
4 } else if ( a > 5) {
5 printf ( " a is greater than 5 but less than or equal to 15\ n " ) ;
6 } else {
7 printf ( " a is 5 or less \ n " ) ;
8 }

Switch Statement
Allows multi-way branching based on the value of an expression. Each case represents a branch.

Syntax:

1 switch ( expression ) {
2 case value1 :
3 // code to execute if expression equals value1
4 break ;
5 case value2 :
6 // code to execute if expression equals value2
7 break ;
8 // more cases
9 default :
10 // code to execute if no case matches
11 }

Example:

1 int day = 3;
2 switch ( day ) {
3 case 1:
4 printf ( " Monday \ n " ) ;
5 break ;
6 case 2:
7 printf ( " Tuesday \ n " ) ;
8 break ;
9 case 3:
10 printf ( " Wednesday \ n " ) ;
11 break ;
12 default :
13 printf ( " Invalid day \ n " ) ;
14 }

Break Statement
Exits from the innermost loop or switch statement.

Syntax:

1 break ;

Example:

1 for ( int i = 0; i < 10; i ++) {


2 if ( i == 5) {
3 break ; // Exit the loop when i equals 5
4 }
5 printf ( " % d \ n " , i ) ;
6 }

Continue Statement
Skips the rest of the code inside the loop for the current iteration and proceeds with the next iteration.

Syntax:

1 continue ;

Example:

1 for ( int i = 0; i < 10; i ++) {


2 if ( i % 2 == 0) {
3 continue ; // Skip even numbers
4 }
5 printf ( " % d \ n " , i ) ;
6 }

Goto Statement
Transfers control to a labeled statement. Its use is generally discouraged because it can lead to code that is difficult to

understand and maintain.

Syntax:

1 goto label ;
2

3 label :
4 // code to execute

Example:

1 int i = 0;
2 start :
3 if ( i < 5) {
4 printf ( " % d \ n " , i ) ;
5 i ++;
6 goto start ; // Jump back to the label
7 }

Loops
Loops are used to execute a block of code multiple times.

For Loop

Used when the number of iterations is known.

Syntax:
1 for ( initia lization ; condition ; increment / decrement ) {
2 // code
3 }

Example:

1 for ( int i = 0; i < 5; i ++) {


2 printf ("% d \ n " , i ) ;
3 }

While Loop

Used when the number of iterations is not known, and execution continues as long as the condition is true.

Syntax:

1 while ( condition ) {
2 // code
3 }

Example:

1 int i = 0;
2 while ( i < 5) {
3 printf ("% d \ n " , i ) ;
4 i ++;
5 }

Do-While Loop

Similar to the while loop, but it guarantees at least one execution of the loop body.

Syntax:

1 do {
2 // code
3 } while ( condition ) ;

Example:

1 int i = 0;
2 do {
3 printf ("% d \ n " , i ) ;
4 i ++;
5 } while ( i < 5) ;

1.1 Even or Odd Number


Objective: Write a C program that reads an integer and determines whether it is even or odd using the modulus operator.

Instructions:

1. Prompt the user to enter an integer.

2. Use the modulus operator to determine if the number is even or odd.

3. Display the result.


Sample Input:

1 Enter an integer : 7

Sample Output:

1 The number 7 is odd .

Program:

1 # include < stdio .h >


2

3 int main () {
4 int num ;
5

6 // Prompt user to enter an integer


7 printf ( " Enter an integer : " ) ;
8 scanf ( " % d " , & num ) ;
9

10 // Check if the number is even or odd


11 if ( num % 2 == 0) {
12 printf ( " The number % d is even .\ n " , num ) ;
13 } else {
14 printf ( " The number % d is odd .\ n " , num ) ;
15 }
16

17 return 0;
18 }

1.2 Simple Calculator


Objective: Write a C program to create a simple calculator that performs addition, subtraction, multiplication, and

division based on user choice. Use a switch-case statement to handle the operations.

Instructions:

1. Prompt the user to enter two numbers and an operation choice.

2. Use a switch-case statement to perform the selected operation.

3. Display the result.

Sample Input:

1 Enter first number : 10


2 Enter second number : 5
3 Enter operation (+ , -, * , /) : *

Sample Output:

1 10 * 5 = 50

Program:

1 # include < stdio .h >


2

3 int main () {
4 float num1 , num2 ;
5 char operator ;
6

7 // Prompt user to enter numbers and operator


8 printf ( " Enter first number : " ) ;
9 scanf ( " % f " , & num1 ) ;
10 printf ( " Enter second number : " ) ;
11 scanf ( " % f " , & num2 ) ;
12 printf ( " Enter operation (+ , -, * , /) : " ) ;
13 scanf ( " % c " , & operator ) ;
14

15 // Perform the operation based on user choice


16 switch ( operator ) {
17 case ’+ ’:
18 printf ( " %.2 f + %.2 f = %.2 f \ n " , num1 , num2 , num1 + num2 ) ;
19 break ;
20 case ’ - ’:
21 printf ( " %.2 f - %.2 f = %.2 f \ n " , num1 , num2 , num1 - num2 ) ;
22 break ;
23 case ’* ’:
24 printf ( " %.2 f * %.2 f = %.2 f \ n " , num1 , num2 , num1 * num2 ) ;
25 break ;
26 case ’/ ’:
27 if ( num2 != 0) {
28 printf ( " %.2 f / %.2 f = %.2 f \ n " , num1 , num2 , num1 / num2 ) ;
29 } else {
30 printf ( " Error : Division by zero \ n " ) ;
31 }
32 break ;
33 default :
34 printf ( " Error : Invalid operator \ n " ) ;
35 break ;
36 }
37

38 return 0;
39 }

1.3 Quadratic Equation Solver


Objective: Write a C program to solve a quadratic equation of the form

ax 2 + bx + c = 0

using the quadratic formula. Handle cases for real and complex roots.

Instructions:

1. Prompt the user to enter the coefficients a, b, and c.

2. Calculate the discriminant and determine the nature of the roots.

3. Display the roots, handling both real and complex cases.


Sample Input:

1 Enter coefficient a : 1
2 Enter coefficient b : -3
3 Enter coefficient c : 2

Sample Output:

1 The roots are : 2.00 and 1.00

Program:

1 # include < stdio .h >


2 # include < math .h >
3

4 int main () {
5 float a , b , c , discriminant , root1 , root2 , realPart , imaginaryPart ;
6

7 // Prompt user to enter coefficients


8 printf ( " Enter coefficient a : " ) ;
9 scanf ( " % f " , & a ) ;
10 printf ( " Enter coefficient b : " ) ;
11 scanf ( " % f " , & b ) ;
12 printf ( " Enter coefficient c : " ) ;
13 scanf ( " % f " , & c ) ;
14

15 // Calculate the discriminant


16 discriminant = b * b - 4 * a * c ;
17

18 // Calculate roots based on the discriminant


19 if ( discriminant > 0) {
20 root1 = ( - b + sqrt ( discriminant ) ) / (2 * a ) ;
21 root2 = ( - b - sqrt ( discriminant ) ) / (2 * a ) ;
22 printf ( " The roots are : %.2 f and %.2 f \ n " , root1 , root2 ) ;
23 } else if ( discriminant == 0) {
24 root1 = root2 = -b / (2 * a ) ;
25 printf ( " The root is : %.2 f \ n " , root1 ) ;
26 } else {
27 realPart = -b / (2 * a ) ;
28 imaginaryPart = sqrt ( - discriminant ) / (2 * a ) ;
29 printf ( " The roots are : %.2 f + %.2 fi and %.2 f - %.2 fi \ n " , realPart , imaginaryPart , realPart ,
imaginaryPart ) ;
30 }
31

32 return 0;
33 }

1.4 Factorial Calculation


Objective: Write a C program to calculate the factorial of a number using both iterative and recursive methods.

Instructions:
1. Prompt the user to enter a number.

2. Implement both iterative and recursive methods to calculate the factorial.

3. Display the results.

Sample Input:

1 Enter a number : 5

Sample Output:

1 Iterative Factorial : 120


2 Recursive Factorial : 120

Program:

1 # include < stdio .h >


2

3 // Function to calculate factorial iteratively


4 long long f a c t o r i a l I t e r a t i v e ( int n ) {
5 long long result = 1;
6 for ( int i = 1; i <= n ; i ++) {
7 result *= i ;
8 }
9 return result ;
10 }
11

12 // Function to calculate factorial recursively


13 long long f a c t o r i a l R e c u r s i v e ( int n ) {
14 if ( n == 0 || n == 1) {
15 return 1;
16 } else {
17 return n * f a c t o r i a l R e c u r s i v e ( n - 1) ;
18 }
19 }
20

21 int main () {
22 int num ;
23

24 // Prompt user to enter a number


25 printf ( " Enter a number : " ) ;
26 scanf ( " % d " , & num ) ;
27

28 // Calculate factorial using iterative method


29 printf ( " Iterative Factorial : % lld \ n " , f a c t o r i a l I t e r a t i v e ( num ) ) ;
30

31 // Calculate factorial using recursive method


32 printf ( " Recursive Factorial : % lld \ n " , f a c t o r i a l R e c u r s i v e ( num ) ) ;
33

34 return 0;
35 }
1.5 Fibonacci Series
Objective: Write a C program to generate the Fibonacci series up to n terms using a for loop.

Instructions:

1. Prompt the user to enter the number of terms.

2. Use a for loop to generate and display the Fibonacci series.

Sample Input:

1 Enter the number of terms : 7

Sample Output:

1 Fibonacci Series : 0 1 1 2 3 5 8

Program:

1 # include < stdio .h >


2

3 int main () {
4 int terms , first = 0 , second = 1 , next ;
5

6 // Prompt user to enter number of terms


7 printf ( " Enter the number of terms : " ) ;
8 scanf ( " % d " , & terms ) ;
9

10 printf ( " Fibonacci Series : " ) ;


11

12 for ( int i = 1; i <= terms ; i ++) {


13 if ( i == 1) {
14 printf ( " % d " , first ) ;
15 continue ;
16 }
17 if ( i == 2) {
18 printf ( " % d " , second ) ;
19 continue ;
20 }
21 next = first + second ;
22 first = second ;
23 second = next ;
24 printf ( " % d " , next ) ;
25 }
26

27 printf ( " \ n " ) ;


28

29 return 0;
30 }

1.6 Prime Number Check


Objective: Write a C program to check whether a given number is prime or not using a for loop and if conditions.
Instructions:

1. Prompt the user to enter a number.

2. Use a for loop to check if the number is divisible by any number other than 1 and itself.

3. Display whether the number is prime.

Sample Input:

1 Enter a number : 29

Sample Output:

1 The number 29 is prime .

Program:

1 # include < stdio .h >


2

3 int main () {
4 int num , isPrime = 1;
5

6 // Prompt user to enter a number


7 printf ( " Enter a number : " ) ;
8 scanf ( " % d " , & num ) ;
9

10 // Check if the number is prime


11 if ( num <= 1) {
12 isPrime = 0;
13 } else {
14 for ( int i = 2; i <= num / 2; i ++) {
15 if ( num % i == 0) {
16 isPrime = 0;
17 break ;
18 }
19 }
20 }
21

22 // Display the result


23 if ( isPrime ) {
24 printf ( " The number % d is prime .\ n " , num ) ;
25 } else {
26 printf ( " The number % d is not prime .\ n " , num ) ;
27 }
28

29 return 0;
30 }

1.7 Sum of Digits


Objective: Write a C program to find the sum of the digits of a number using a while loop.

Instructions:

1. Prompt the user to enter a number.


2. Use a while loop to sum the digits of the number.

3. Display the result.

Sample Input:

1 Enter a number : 1234

Sample Output:

1 The sum of the digits is 10.

Program:

1 # include < stdio .h >


2

3 int main () {
4 int num , sum = 0;
5

6 // Prompt user to enter a number


7 printf ( " Enter a number : " ) ;
8 scanf ( " % d " , & num ) ;
9

10 // Calculate the sum of digits


11 while ( num != 0) {
12 sum += num % 10;
13 num /= 10;
14 }
15

16 // Display the result


17 printf ( " The sum of the digits is % d .\ n " , sum ) ;
18

19 return 0;
20 }

1.8 Patterns with Loops


Objective: Write a C program to print a pattern of stars like the following:

1 *
2 **
3 ***
4 ****
5 *****

Instructions:

1. Use nested loops to generate the pattern.

2. Display the pattern on the console.

Sample Output:

1 *
2 **
3 ***
4 ****
5 *****

Program:

1 # include < stdio .h >


2

3 int main () {
4 int i , j , rows = 5;
5

6 // Loop to print the pattern


7 for ( i = 1; i <= rows ; i ++) {
8 for ( j = 1; j <= i ; j ++) {
9 printf ( " * " ) ;
10 }
11 printf ( " \ n " ) ;
12 }
13

14 return 0;
15 }

1.9 Count Vowels and Consonants


Objective: Write a C program to count the number of vowels and consonants in a given string. Use a for loop to iterate

through each character in the string.

Instructions:

1. Prompt the user to enter a string.

2. Use a for loop to iterate through the string and count vowels and consonants.

3. Display the counts.

Sample Input:

1 Enter a string : Hello World

Sample Output:

1 Vowels : 3
2 Consonants : 7

Program:

1 # include < stdio .h >


2 # include < ctype .h >
3

4 int main () {
5 char str [100];
6 int i , vowels = 0 , consonants = 0;
7

8 // Prompt user to enter a string


9 printf ( " Enter a string : " ) ;
10 gets ( str ) ; // Note : gets () is unsafe , use fgets () in production code
11

12 // Iterate through the string


13 for ( i = 0; str [ i ] != ’ \0 ’; i ++) {
14 char ch = tolower ( str [ i ]) ;
15 if ( ch >= ’a ’ && ch <= ’z ’) {
16 if ( ch == ’a ’ || ch == ’e ’ || ch == ’i ’ || ch == ’o ’ || ch == ’u ’) {
17 vowels ++;
18 } else {
19 consonants ++;
20 }
21 }
22 }
23

24 // Display the counts


25 printf ( " Vowels : % d \ n " , vowels ) ;
26 printf ( " Consonants : % d \ n " , consonants ) ;
27

28 return 0;
29 }

1.10 Find the Greatest Common Divisor (GCD)


Objective: Write a C program to find the GCD of two numbers using the Euclidean algorithm.

Instructions:

1. Prompt the user to enter two numbers.

2. Use the Euclidean algorithm to calculate the GCD.

3. Display the GCD.

Sample Input:

1 Enter two numbers : 48 18

Sample Output:

1 The GCD of 48 and 18 is 6

Program:

1 # include < stdio .h >


2

3 int gcd ( int a , int b ) {


4 if ( b == 0)
5 return a ;
6 return gcd (b , a % b ) ;
7 }
8

9 int main () {
10 int num1 , num2 ;
11

12 // Prompt user to enter two numbers


13 printf ( " Enter two numbers : " ) ;
14 scanf ( " % d % d " , & num1 , & num2 ) ;
15

16 // Calculate GCD using Euclidean algorithm


17 printf ( " The GCD of % d and % d is % d \ n " , num1 , num2 , gcd ( num1 , num2 ) ) ;
18

19 return 0;
20 }

1.11 Multiplication Table


Objective: Write a C program to generate and print the multiplication table for a number up to 10 using a for loop.

Instructions:

1. Prompt the user to enter a number.

2. Use a for loop to generate and display the multiplication table up to 10.

Sample Input:

1 Enter a number : 7

Sample Output:

1 Mult iplicati on table for 7:


2 7 x 1 = 7
3 7 x 2 = 14
4 7 x 3 = 21
5 7 x 4 = 28
6 7 x 5 = 35
7 7 x 6 = 42
8 7 x 7 = 49
9 7 x 8 = 56
10 7 x 9 = 63
11 7 x 10 = 70

Program:

1 # include < stdio .h >


2

3 int main () {
4 int num ;
5

6 // Prompt user to enter a number


7 printf ( " Enter a number : " ) ;
8 scanf ( " % d " , & num ) ;
9

10 // Print multipl ication table


11 printf ( " Multipl ication table for % d :\ n " , num ) ;
12 for ( int i = 1; i <= 10; i ++) {
13 printf ( " % d x % d = % d \ n " , num , i , num * i ) ;
14 }
15

16 return 0;
17 }

1.12 Count Digits in a Number


Objective: Write a C program to count the number of digits in a given integer using a while loop.

Instructions:

1. Prompt the user to enter an integer.

2. Use a while loop to count the digits.

3. Display the count.

Sample Input:

1 Enter a number : 12345

Sample Output:

1 The number 12345 has 5 digits .

Program:

1 # include < stdio .h >


2

3 int main () {
4 int num , count = 0;
5

6 // Prompt user to enter a number


7 printf ( " Enter a number : " ) ;
8 scanf ( " % d " , & num ) ;
9

10 // Count the number of digits


11 while ( num != 0) {
12 num /= 10;
13 count ++;
14 }
15

16 // Display the count


17 printf ( " The number has % d digits .\ n " , count ) ;
18

19 return 0;
20 }

1.13 Sum of First N Natural Numbers


Objective: Write a C program to calculate the sum of the first N natural numbers using a for loop.

Instructions:

1. Prompt the user to enter the value of N.

2. Use a for loop to calculate the sum of the first N natural numbers.

3. Display the result.

Sample Input:
1 Enter the value of N : 5

Sample Output:

1 The sum of the first 5 natural numbers is 15.

Program:

1 # include < stdio .h >


2

3 int main () {
4 int n , sum = 0;
5

6 // Prompt user to enter the value of N


7 printf ( " Enter the value of N : " ) ;
8 scanf ( " % d " , & n ) ;
9

10 // Calculate the sum of the first N natural numbers


11 for ( int i = 1; i <= n ; i ++) {
12 sum += i ;
13 }
14

15 // Display the result


16 printf ( " The sum of the first % d natural numbers is % d .\ n " , n , sum ) ;
17

18 return 0;
19 }

2 Arrays & Functions


Arrays in C are a collection of elements of the same type, stored in contiguous memory locations. They allow you to

store multiple values in a single variable.

Syntax.

1 type arrayName [ arraySize ];

Example

1 int numbers [5]; // Declares an array of 5 integers

Initializing Arrays

1 int numbers [5] = {1 , 2 , 3 , 4 , 5}; // Declares and initializes an array

Accessing Array Elements

1 int value = numbers [2]; // Accesses the third element of the array ( index starts at 0)
Multidimensional Arrays
Arrays with more than one dimension, such as

Syntax.

1 type arrayName [ rows ][ columns ];

Example

1 int matrix [3][4]; // Declares a 2 D array with 3 rows and 4 columns

C Functions
Functions in C are blocks of code that perform a specific task and can be reused throughout the program. They help in

organizing code and improving readability.

Syntax.

1 returnType functionName ( parameters ) {


2 // code to execute
3 return value ; // if returnType is not void
4 }

Example

1 # include < stdio .h >


2

3 // Function declaration
4 int add ( int a , int b ) ;
5

6 int main () {
7 int result = add (10 , 5) ; // Function call
8 printf ( " Result : % d \ n " , result ) ;
9 return 0;
10 }
11

12 // Function definition
13 int add ( int a , int b ) {
14 return a + b ;
15 }

Function Declaration
Declares the function before its use in main() or other functions.

Syntax.

1 returnType functionName ( parameters ) ;


Function Definition
Provides the actual body of the function.

Syntax.

1 returnType functionName ( parameters ) {


2 // function body
3 }

Function Call
Invokes the function and optionally passes arguments.

Syntax.

1 functionName ( arguments ) ;

Example

1 int result = add (10 , 5) ; // Calls the function and stores the result

Default Arguments
C does not support default arguments. All arguments must be explicitly provided in function calls.

2.1 Reverse an Array


Objective: Write a C program to reverse the elements of a 1-D array and display the reversed array.

Instructions:

1. Prompt the user to enter the size of the array and the elements.

2. Reverse the array using a loop.

3. Display the reversed array.

Sample Input:

1 Enter the size of the array : 5


2 Enter 5 elements : 1 2 3 4 5

Sample Output:

1 Reversed array : 5 4 3 2 1

Program:

1 # include < stdio .h >


2

3 int main () {
4 int arr [100] , size ;
5

6 // Prompt user to enter the size of the array


7 printf ( " Enter the size of the array : " ) ;
8 scanf ( " % d " , & size ) ;
9

10 // Prompt user to enter the elements of the array


11 printf ( " Enter % d elements : " , size ) ;
12 for ( int i = 0; i < size ; i ++) {
13 scanf ( " % d " , & arr [ i ]) ;
14 }
15

16 // Reverse the array


17 for ( int i = 0; i < size / 2; i ++) {
18 int temp = arr [ i ];
19 arr [ i ] = arr [ size - 1 - i ];
20 arr [ size - 1 - i ] = temp ;
21 }
22

23 // Display the reversed array


24 printf ( " Reversed array : " ) ;
25 for ( int i = 0; i < size ; i ++) {
26 printf ( " % d " , arr [ i ]) ;
27 }
28 printf ( " \ n " ) ;
29

30 return 0;
31 }

2.2 Find and Display Largest and Smallest Elements in an Array


Objective: Write a C program to find and display the largest and smallest elements in a 1-D array.

Instructions:

1. Prompt the user to enter the size of the array and the elements.

2. Find the largest and smallest elements using a loop.

3. Display the largest and smallest elements.

Sample Input:

1 Enter the size of the array : 6


2 Enter 6 elements : 7 2 9 4 1 5

Sample Output:

1 Largest element : 9
2 Smallest element : 1

Program:

1 # include < stdio .h >


2

3 int main () {
4 int arr [100] , size ;
5 int largest , smallest ;
6

7 // Prompt user to enter the size of the array


8 printf ( " Enter the size of the array : " ) ;
9 scanf ( " % d " , & size ) ;
10

11 // Prompt user to enter the elements of the array


12 printf ( " Enter % d elements : " , size ) ;
13 for ( int i = 0; i < size ; i ++) {
14 scanf ( " % d " , & arr [ i ]) ;
15 }
16

17 // Initialize largest and smallest


18 largest = smallest = arr [0];
19

20 // Find the largest and smallest elements


21 for ( int i = 1; i < size ; i ++) {
22 if ( arr [ i ] > largest ) {
23 largest = arr [ i ];
24 }
25 if ( arr [ i ] < smallest ) {
26 smallest = arr [ i ];
27 }
28 }
29

30 // Display the largest and smallest elements


31 printf ( " Largest element : % d \ n " , largest ) ;
32 printf ( " Smallest element : % d \ n " , smallest ) ;
33

34 return 0;
35 }

2.3 Add Two 2x2 Matrices


Objective: Write a C program to add two 2x2 matrices and display the result.

Instructions:

1. Prompt the user to enter the elements of two 2x2 matrices.

2. Add the matrices element-wise.

3. Display the resulting matrix.

Sample Input:

1 Enter elements of matrix A :


2 1 2
3 3 4
4 Enter elements of matrix B :
5 5 6
6 7 8

Sample Output:

1 Sum of the matrices :


2 6 8
3 10 12

Program:

1 # include < stdio .h >


2

3 int main () {
4 int A [2][2] , B [2][2] , Sum [2][2];
5

6 // Prompt user to enter elements of matrix A


7 printf ( " Enter elements of matrix A :\ n " ) ;
8 for ( int i = 0; i < 2; i ++) {
9 for ( int j = 0; j < 2; j ++) {
10 scanf ( " % d " , & A [ i ][ j ]) ;
11 }
12 }
13

14 // Prompt user to enter elements of matrix B


15 printf ( " Enter elements of matrix B :\ n " ) ;
16 for ( int i = 0; i < 2; i ++) {
17 for ( int j = 0; j < 2; j ++) {
18 scanf ( " % d " , & B [ i ][ j ]) ;
19 }
20 }
21

22 // Add the matrices


23 for ( int i = 0; i < 2; i ++) {
24 for ( int j = 0; j < 2; j ++) {
25 Sum [ i ][ j ] = A [ i ][ j ] + B [ i ][ j ];
26 }
27 }
28

29 // Display the result


30 printf ( " Sum of the matrices :\ n " ) ;
31 for ( int i = 0; i < 2; i ++) {
32 for ( int j = 0; j < 2; j ++) {
33 printf ( " % d " , Sum [ i ][ j ]) ;
34 }
35 printf ( " \ n " ) ;
36 }
37

38 return 0;
39 }

2.4 Find the Transpose of a 3x3 Matrix


Objective: Write a C program to find and display the transpose of a 3x3 matrix.

Instructions:

1. Prompt the user to enter the elements of a 3x3 matrix.


2. Compute the transpose of the matrix.

3. Display the transposed matrix.

Sample Input:

1 Enter elements of the matrix :


2 1 2 3
3 4 5 6
4 7 8 9

Sample Output:

1 Transpose of the matrix :


2 1 4 7
3 2 5 8
4 3 6 9

Program:

1 # include < stdio .h >


2

3 int main () {
4 int matrix [3][3] , transpose [3][3];
5

6 // Prompt user to enter elements of the matrix


7 printf ( " Enter elements of the matrix :\ n " ) ;
8 for ( int i = 0; i < 3; i ++) {
9 for ( int j = 0; j < 3; j ++) {
10 scanf ( " % d " , & matrix [ i ][ j ]) ;
11 }
12 }
13

14 // Compute the transpose of the matrix


15 for ( int i = 0; i < 3; i ++) {
16 for ( int j = 0; j < 3; j ++) {
17 transpose [ j ][ i ] = matrix [ i ][ j ];
18 }
19 }
20

21 // Display the transposed matrix


22 printf ( " Transpose of the matrix :\ n " ) ;
23 for ( int i = 0; i < 3; i ++) {
24 for ( int j = 0; j < 3; j ++) {
25 printf ( " % d " , transpose [ i ][ j ]) ;
26 }
27 printf ( " \ n " ) ;
28 }
29

30 return 0;
31 }
2.5 Calculate the Length of a String
Objective: Write a C program to calculate the length of a string without using the strlen() function.

Instructions:

1. Prompt the user to enter a string.

2. Calculate the length of the string by iterating through it until the null terminator is reached.

3. Display the length of the string.

Sample Input:

1 Enter a string : Hello World

Sample Output:

1 Length of the string : 11

Program:

1 # include < stdio .h >


2

3 int main () {
4 char str [100];
5 int length = 0;
6

7 // Prompt user to enter a string


8 printf ( " Enter a string : " ) ;
9 fgets ( str , sizeof ( str ) , stdin ) ;
10

11 // Calculate the length of the string


12 while ( str [ length ] != ’ \0 ’) {
13 length ++;
14 }
15

16 // Adjust length for the newline character added by fgets


17 if ( str [ length - 1] == ’\ n ’) {
18 length - -;
19 }
20

21 // Display the length of the string


22 printf ( " Length of the string : % d \ n " , length ) ;
23

24 return 0;
25 }

2.6 Concatenate Two Strings


Objective: Write a C program to concatenate two strings without using the strcat() function.

Instructions:

1. Prompt the user to enter two strings.

2. Concatenate the second string to the end of the first string manually.
3. Display the concatenated string.

Sample Input:

1 Enter the first string : Hello


2 Enter the second string : World

Sample Output:

1 Concatenated string : HelloWorld

Program:

1 # include < stdio .h >


2

3 int main () {
4 char str1 [100] , str2 [100];
5 int i , j ;
6

7 // Prompt user to enter the first string


8 printf ( " Enter the first string : " ) ;
9 fgets ( str1 , sizeof ( str1 ) , stdin ) ;
10

11 // Remove newline character if present


12 if ( str1 [ strlen ( str1 ) - 1] == ’\ n ’) {
13 str1 [ strlen ( str1 ) - 1] = ’ \0 ’;
14 }
15

16 // Prompt user to enter the second string


17 printf ( " Enter the second string : " ) ;
18 fgets ( str2 , sizeof ( str2 ) , stdin ) ;
19

20 // Remove newline character if present


21 if ( str2 [ strlen ( str2 ) - 1] == ’\ n ’) {
22 str2 [ strlen ( str2 ) - 1] = ’ \0 ’;
23 }
24

25 // Find the length of the first string


26 for ( i = 0; str1 [ i ] != ’ \0 ’; i ++) ;
27

28 // Append the second string to the first string


29 for ( j = 0; str2 [ j ] != ’ \0 ’; j ++) {
30 str1 [ i + j ] = str2 [ j ];
31 }
32 str1 [ i + j ] = ’ \0 ’; // Null - terminate the concatenated string
33

34 // Display the concatenated string


35 printf ( " Concatenated string : % s \ n " , str1 ) ;
36

37 return 0;
38 }
3 Structures and Unions
In C, structures are user-defined data types that group related variables of different types under a single name. Each

variable within a structure is called a member.

Syntax

1 struct StructureName {
2 type member1 ;
3 type member2 ;
4 // more members
5 };

Example

1 # include < stdio .h >


2

3 // Structure definition
4 struct Person {
5 char name [50];
6 int age ;
7 float height ;
8 };
9

10 int main () {
11 // Creating and initializing a structure variable
12 struct Person person1 = { " Alice " , 30 , 5.5};
13

14 // Accessing structure members


15 printf ( " Name : % s \ n " , person1 . name ) ;
16 printf ( " Age : % d \ n " , person1 . age ) ;
17 printf ( " Height : %.1 f \ n " , person1 . height ) ;
18

19 return 0;
20 }

Accessing Structure Members Use the dot operator (.) to access members of a structure variable.

Example

1 person1 . age = 31; // Accessing and modifying the ’ age ’ member

Unions
Unions in C are similar to structures but allow only one member to be accessed at a time. They are useful when you

need to store different data types in the same memory location but not simultaneously.

Syntax

1 union UnionName {
2 type member1 ;
3 type member2 ;
4 // more members
5 };

Example

1 # include < stdio .h >


2

3 // Union definition
4 union Data {
5 int integer ;
6 float floating ;
7 char character ;
8 };
9

10 int main () {
11 // Creating and initializing a union variable
12 union Data data ;
13

14 // Assigning and accessing union members


15 data . integer = 10;
16 printf ( " Integer : % d \ n " , data . integer ) ;
17

18 data . floating = 5.75; // This overwrites the previous value


19 printf ( " Float : %.2 f \ n " , data . floating ) ;
20

21 data . character = ’A ’; // This overwrites the previous value


22 printf ( " Character : % c \ n " , data . character ) ;
23

24 return 0;
25 }

Accessing Union Members Use the dot operator (.) to access members of a union variable.

Example

1 data . floating = 5.75; // Accessing and modifying the ’ floating ’ member

Key Differences

• Structures: All members occupy different parts of memory. The size of a structure is the sum of the sizes of its

members (plus padding).

• Unions: All members share the same memory location. The size of a union is the size of its largest member.

3.1 Define and Use a Structure


Objective: Write a C program to define a structure Student with members name, age, and marks. Create an instance

of this structure, assign values to its members, and display these values.

Instructions:

1. Define the Student structure.

2. Create an instance of the structure.

3. Assign values to its members.


4. Display the values.

Sample Input:

1 Name : John Doe


2 Age : 20
3 Marks : 85.5

Sample Output:

1 Student Details :
2 Name : John Doe
3 Age : 20
4 Marks : 85.5

Program:

1 # include < stdio .h >


2

3 // Define the structure Student


4 struct Student {
5 char name [50];
6 int age ;
7 float marks ;
8 };
9

10 int main () {
11 // Create an instance of Student
12 struct Student student ;
13

14 // Assign values to members


15 printf ( " Enter name : " ) ;
16 fgets ( student . name , sizeof ( student . name ) , stdin ) ;
17 printf ( " Enter age : " ) ;
18 scanf ( " % d " , & student . age ) ;
19 printf ( " Enter marks : " ) ;
20 scanf ( " % f " , & student . marks ) ;
21

22 // Display the values


23 printf ( " \ nStudent Details :\ n " ) ;
24 printf ( " Name : % s " , student . name ) ;
25 printf ( " Age : % d \ n " , student . age ) ;
26 printf ( " Marks : %.2 f \ n " , student . marks ) ;
27

28 return 0;
29 }

3.2 Nested Structures


Objective: Write a C program to define a structure Employee with members name, age, and a nested structure Address

that includes street, city, and zip. Create an instance of Employee, assign values to all members, and display the

complete information.
Instructions:

1. Define the Address structure nested within the Employee structure.

2. Create an instance of Employee.

3. Assign values to all members.

4. Display the complete information.

Sample Input:

1 Employee Name : Alice Smith


2 Age : 30
3 Street : 123 Elm Street
4 City : Springfield
5 Zip : 12345

Sample Output:

1 Employee Details :
2 Name : Alice Smith
3 Age : 30
4 Address :
5 Street : 123 Elm Street
6 City : Springfield
7 Zip : 12345

Program:

1 # include < stdio .h >


2

3 // Define the nested structure Address


4 struct Address {
5 char street [100];
6 char city [50];
7 int zip ;
8 };
9

10 // Define the structure Employee


11 struct Employee {
12 char name [50];
13 int age ;
14 struct Address address ;
15 };
16

17 int main () {
18 // Create an instance of Employee
19 struct Employee employee ;
20

21 // Assign values to members


22 printf ( " Enter employee name : " ) ;
23 fgets ( employee . name , sizeof ( employee . name ) , stdin ) ;
24 printf ( " Enter age : " ) ;
25 scanf ( " % d " , & employee . age ) ;
26 getchar () ; // Clear the newline character left by scanf
27

28 printf ( " Enter street : " ) ;


29 fgets ( employee . address . street , sizeof ( employee . address . street ) , stdin ) ;
30 printf ( " Enter city : " ) ;
31 fgets ( employee . address . city , sizeof ( employee . address . city ) , stdin ) ;
32 printf ( " Enter zip code : " ) ;
33 scanf ( " % d " , & employee . address . zip ) ;
34

35 // Display the complete information


36 printf ( " \ nEmployee Details :\ n " ) ;
37 printf ( " Name : % s " , employee . name ) ;
38 printf ( " Age : % d \ n " , employee . age ) ;
39 printf ( " Address :\ n " ) ;
40 printf ( " Street : % s " , employee . address . street ) ;
41 printf ( " City : % s " , employee . address . city ) ;
42 printf ( " Zip : % d \ n " , employee . address . zip ) ;
43

44 return 0;
45 }

3.3 Array of Structures


Objective: Write a C program to define a structure Book with members title, author, and price. Create an array of

Book structures, initialize it with data, and display the details of all books.

Instructions:

1. Define the Book structure.

2. Create an array of Book structures.

3. Initialize the array with data.

4. Display the details of all books.

Sample Output:

1 Book 1:
2 Title : The Great Gatsby
3 Author : F . Scott Fitzgerald
4 Price : 10.99
5

6 Book 2:
7 Title : 1984
8 Author : George Orwell
9 Price : 8.99
10

11 Book 3:
12 Title : To Kill a Mockingbird
13 Author : Harper Lee
14 Price : 12.49
Program:

1 # include < stdio .h >


2

3 // Define the structure Book


4 struct Book {
5 char title [50];
6 char author [50];
7 float price ;
8 };
9

10 int main () {
11 // Create an array of Book structures
12 struct Book books [3] = {
13 { " The Great Gatsby " , " F . Scott Fitzgerald " , 10.99} ,
14 { " 1984 " , " George Orwell " , 8.99} ,
15 { " To Kill a Mockingbird " , " Harper Lee " , 12.49}
16 };
17

18 // Display the details of all books


19 for ( int i = 0; i < 3; i ++) {
20 printf ( " Book % d :\ n " , i + 1) ;
21 printf ( " Title : % s " , books [ i ]. title ) ;
22 printf ( " Author : % s " , books [ i ]. author ) ;
23 printf ( " Price : %.2 f \ n \ n " , books [ i ]. price ) ;
24 }
25

26 return 0;
27 }

3.4 Functions and Structures


Objective: Write a C program to define a structure Rectangle with members length and width. Write a function that

takes a Rectangle structure as an argument and returns its area. Use this function to calculate and display the area of a

rectangle.

Instructions:

1. Define the Rectangle structure.

2. Write a function to calculate the area of a rectangle.

3. Call the function from the main function and display the result.

Sample Input:

1 Length : 5
2 Width : 4

Sample Output:

1 Area of the rectangle : 20

Program:
1 # include < stdio .h >
2

3 // Define the structure Rectangle


4 struct Rectangle {
5 float length ;
6 float width ;
7 };
8

9 // Function to calculate the area of a rectangle


10 float calculateArea ( struct Rectangle rect ) {
11 return rect . length * rect . width ;
12 }
13

14 int main () {
15 struct Rectangle rect ;
16

17 // Prompt user to enter dimensions


18 printf ( " Enter length : " ) ;
19 scanf ( " % f " , & rect . length ) ;
20 printf ( " Enter width : " ) ;
21 scanf ( " % f " , & rect . width ) ;
22

23 // Calculate and display the area


24 float area = calculateArea ( rect ) ;
25 printf ( " Area of the rectangle : %.2 f \ n " , area ) ;
26

27 return 0;
28 }

3.5 Unions
Objective: Write a C program to define a union Data with members integer, float, and char. Create an instance of

this union, assign values to each member, and display the values to show how the union’s memory is shared.

Instructions:

1. Define the Data union.

2. Create an instance of the union.

3. Assign values to each member and display them.

4. Observe how changing one member affects the others due to shared memory.

Sample Input:

1 Integer value : 10
2 Float value : 3.14
3 Character value : A

Sample Output:

1 Integer value : 10
2 Float value : 3.14
3 Character value : A

Note: Only the last assigned value will be correctly displayed.

Program:
1 # include < stdio .h >
2

3 // Define the union Data


4 union Data {
5 int integer ;
6 float floating ;
7 char character ;
8 };
9

10 int main () {
11 union Data data ;
12

13 // Assign and display integer value


14 data . integer = 10;
15 printf ( " Integer value : % d \ n " , data . integer ) ;
16

17 // Assign and display float value


18 data . floating = 3.14;
19 printf ( " Float value : %.2 f \ n " , data . floating ) ;
20

21 // Assign and display character value


22 data . character = ’A ’;
23 printf ( " Character value : % c \ n " , data . character ) ;
24

25 return 0;
26 }

3.6 Bit-fields and Enumerated Data Types


Objective: Write a C program to define a structure Flags that includes bit-fields for bit1, bit2, and bit3, each

occupying 1 bit. Define an enumerated type Day for days of the week. Create an instance of Flags, assign values to the

bit-fields, and display them. Use the Day enumeration to display the name of a specific day of the week.

Instructions:

1. Define the Flags structure with bit-fields.

2. Define the Day enumeration.

3. Create an instance of Flags, assign values to the bit-fields, and display them.

4. Create a variable of type Day and display the name of a specific day.

Sample Input:
1 Bit1 : 1
2 Bit2 : 0
3 Bit3 : 1
4 Day : Wednesday
Sample Output:

1 Flags :
2 Bit1 : 1
3 Bit2 : 0
4 Bit3 : 1
5

6 Day : Wednesday

Program:

1 # include < stdio .h >


2

3 // Define the structure Flags with bit - fields


4 struct Flags {
5 unsigned int bit1 : 1;
6 unsigned int bit2 : 1;
7 unsigned int bit3 : 1;
8 };
9

10 // Define the enumerated type Day


11 enum Day { Sunday , Monday , Tuesday , Wednesday , Thursday , Friday , Saturday };
12

13 int main () {
14 struct Flags flags ;
15 enum Day today ;
16

17 // Assign values to bit - fields


18 flags . bit1 = 1;
19 flags . bit2 = 0;
20 flags . bit3 = 1;
21

22 // Display bit - fields


23 printf ( " Flags :\ n " ) ;
24 printf ( " Bit1 : % d \ n " , flags . bit1 ) ;
25 printf ( " Bit2 : % d \ n " , flags . bit2 ) ;
26 printf ( " Bit3 : % d \ n " , flags . bit3 ) ;
27

28 // Assign and display a day of the week


29 today = Wednesday ;
30 printf ( " \ nDay : " ) ;
31 switch ( today ) {
32 case Sunday : printf ( " Sunday \ n " ) ; break ;
33 case Monday : printf ( " Monday \ n " ) ; break ;
34 case Tuesday : printf ( " Tuesday \ n " ) ; break ;
35 case Wednesday : printf ( " Wednesday \ n " ) ; break ;
36 case Thursday : printf ( " Thursday \ n " ) ; break ;
37 case Friday : printf ( " Friday \ n " ) ; break ;
38 case Saturday : printf ( " Saturday \ n " ) ; break ;
39 }
40
41 return 0;
42 }

4 Pointers & File Handling


Pointers
In C, pointers are variables that store the address of another variable. They allow for efficient manipulation of arrays

and dynamic memory management.

Syntax

1 type * pointerName ;

Example

1 # include < stdio .h >


2

3 int main () {
4 int value = 10;
5 int * ptr ; // Pointer declaration
6

7 ptr = & value ; // Pointer assignment ( stores address of ’ value ’)


8

9 printf ( " Value : % d \ n " , value ) ;


10 printf ( " Address of value : % p \ n " , ( void *) ptr ) ;
11 printf ( " Value through pointer : % d \ n " , * ptr ) ; // Dereferencing pointer to get the value
12

13 return 0;
14 }

Key Operations

• Declaration: int *ptr; (pointer to an integer)

• Assignment: ptr = &value; (assign address of value to ptr)

• Dereferencing: *ptr (accesses the value at the address stored in ptr)

Dynamic Memory Allocation

• malloc(size): Allocates size bytes of memory.

• free(pointer): Frees memory allocated by malloc.

Example

1 # include < stdio .h >


2 # include < stdlib .h >
3

4 int main () {
5 int * ptr ;
6 ptr = ( int *) malloc ( sizeof ( int ) ) ; // Allocate memory for one integer
7
8 if ( ptr == NULL ) {
9 printf ( " Memory allocation failed \ n " ) ;
10 return 1;
11 }
12

13 * ptr = 20; // Assign value to allocated memory


14 printf ( " Dynamically allocated value : % d \ n " , * ptr ) ;
15

16 free ( ptr ) ; // Free allocated memory


17

18 return 0;
19 }

File Handling
C provides functions to read from and write to files. Files are managed using file pointers.

Basic File Operations

• Opening a File: Use fopen().

• Reading/Writing: Use fgetc(), fputc(), fscanf(), fprintf().

• Closing a File: Use fclose().

Syntax

1 FILE * filePointer ;
2 filePointer = fopen ( " filename " , " mode " ) ;

Modes

• "r": Read

• "w": Write

• "a": Append

• "r+": Read and write

• "w+": Write and read

• "a+": Append and read

Example

1 # include < stdio .h >


2

3 int main () {
4 FILE * file ;
5

6 // Opening a file in write mode


7 file = fopen ( " example . txt " , " w " ) ;
8 if ( file == NULL ) {
9 printf ( " Error opening file \ n " ) ;
10 return 1;
11 }
12
13 fprintf ( file , " Hello , World !\ n " ) ; // Write to the file
14

15 fclose ( file ) ; // Close the file


16

17 // Opening the same file in read mode


18 file = fopen ( " example . txt " , " r " ) ;
19 if ( file == NULL ) {
20 printf ( " Error opening file \ n " ) ;
21 return 1;
22 }
23

24 char buffer [100];


25 while ( fgets ( buffer , sizeof ( buffer ) , file ) ) {
26 printf ( " % s " , buffer ) ; // Read and print from the file
27 }
28

29 fclose ( file ) ; // Close the file


30

31 return 0;
32 }

Key Functions

• fopen(filename, mode): Opens a file.

• fclose(filePointer): Closes a file.

• fgets(buffer, size, filePointer): Reads a line from the file.

• fprintf(filePointer, format, args...): Writes formatted data to a file.

• fscanf(filePointer, format, args...): Reads formatted data from a file.

Pointers and file handling are fundamental for managing memory and data storage in C, offering flexibility and control

over program execution.

4.1 Pointer Basics


Objective: Write a C program to demonstrate pointer basics by defining an integer variable, creating a pointer to that

variable, and displaying the value of the variable using the pointer.

Instructions:

1. Define an integer variable.

2. Create a pointer to the integer variable.

3. Display the value of the integer variable using the pointer.

Sample Input:

1 Value of integer variable : 25

Sample Output:

1 Value of integer variable : 25


2 Value using pointer : 25
Program:

1 # include < stdio .h >


2

3 int main () {
4 int num = 25; // Define an integer variable
5 int * ptr = & num ; // Create a pointer to the integer variable
6

7 // Display the value using the pointer


8 printf ( " Value of integer variable : % d \ n " , num ) ;
9 printf ( " Value using pointer : % d \ n " , * ptr ) ;
10

11 return 0;
12 }

4.2 Pointer Arithmetic


Objective: Write a C program to demonstrate pointer arithmetic by creating an array of integers, using pointers to

traverse the array, and displaying the elements of the array using pointer arithmetic.

Instructions:

1. Define an array of integers.

2. Use pointers to traverse the array.

3. Display the elements of the array using pointer arithmetic.

Sample Input:

1 Array elements : 10 , 20 , 30 , 40 , 50

Sample Output:

1 Array elements are :


2 10
3 20
4 30
5 40
6 50

Program:

1 # include < stdio .h >


2

3 int main () {
4 int arr [] = {10 , 20 , 30 , 40 , 50}; // Define an array of integers
5 int * ptr = arr ; // Create a pointer to the array
6

7 // Display the elements using pointer arithmetic


8 printf ( " Array elements are :\ n " ) ;
9 for ( int i = 0; i < 5; i ++) {
10 printf ( " % d \ n " , *( ptr + i ) ) ;
11 }
12
13 return 0;
14 }

4.3 Dynamic Memory Allocation


Objective: Write a C program to allocate memory dynamically for an array of integers using malloc(), initialize the

array, and display its elements. Free the allocated memory using free().

Instructions:

1. Allocate memory dynamically for an array of integers.

2. Initialize the array and display its elements.

3. Free the allocated memory.

Sample Input:

1 Number of elements : 5
2 Array elements : 1 , 2 , 3 , 4 , 5

Sample Output:

1 Array elements are :


2 1
3 2
4 3
5 4
6 5

Program:

1 # include < stdio .h >


2 # include < stdlib .h >
3

4 int main () {
5 int * arr ;
6 int size = 5;
7

8 // Allocate memory dynamically


9 arr = ( int *) malloc ( size * sizeof ( int ) ) ;
10 if ( arr == NULL ) {
11 printf ( " Memory allocation failed \ n " ) ;
12 return 1;
13 }
14

15 // Initialize the array


16 for ( int i = 0; i < size ; i ++) {
17 arr [ i ] = i + 1;
18 }
19

20 // Display the array elements


21 printf ( " Array elements are :\ n " ) ;
22 for ( int i = 0; i < size ; i ++) {
23 printf ( " % d \ n " , arr [ i ]) ;
24 }
25

26 // Free the allocated memory


27 free ( arr ) ;
28

29 return 0;
30 }

4.4 Pointer to a Function


Objective: Write a C program to define a function that takes two integers and returns their sum. Define a pointer to

this function and use the pointer to call the function and display the result.

Instructions:

1. Define a function that returns the sum of two integers.

2. Define a pointer to this function.

3. Use the function pointer to call the function and display the result.

Sample Input:

1 Integers : 5 , 10

Sample Output:

1 Sum of 5 and 10 is : 15

Program:

1 # include < stdio .h >


2

3 // Function to return the sum of two integers


4 int sum ( int a , int b ) {
5 return a + b ;
6 }
7

8 int main () {
9 int (* funcPtr ) ( int , int ) = sum ; // Define a pointer to the function
10 int result ;
11

12 // Call the function using the pointer


13 result = funcPtr (5 , 10) ;
14

15 // Display the result


16 printf ( " Sum of 5 and 10 is : % d \ n " , result ) ;
17

18 return 0;
19 }
4.5 Pointer to Pointer
Objective: Write a C program to demonstrate pointer to pointer by creating an integer variable, defining a pointer to

that variable, and defining another pointer that points to the first pointer. Display the value of the integer using the pointer

to pointer.

Instructions:

1. Define an integer variable.

2. Define a pointer to the integer variable.

3. Define another pointer that points to the first pointer.

4. Display the value of the integer using the pointer to pointer.

Sample Input:

1 Integer value : 42

Sample Output:

1 Value of integer variable : 42


2 Value using pointer to pointer : 42

Program:

1 # include < stdio .h >


2

3 int main () {
4 int num = 42; // Define an integer variable
5 int * ptr1 = & num ; // Define a pointer to the integer variable
6 int ** ptr2 = & ptr1 ; // Define a pointer to the pointer
7

8 // Display the value using the pointer to pointer


9 printf ( " Value of integer variable : % d \ n " , num ) ;
10 printf ( " Value using pointer to pointer : % d \ n " , ** ptr2 ) ;
11

12 return 0;
13 }

4.6 Writing to a File


Objective: Write a C program to create a file named output.txt, write a string to the file, and close the file. Verify

that the file has been created and contains the correct content.

Instructions:

1. Open a file named output.txt for writing.

2. Write a string to the file.

3. Close the file.

4. Verify that the file contains the correct content.

Sample Input:

1 String to write : Hello , World !


Sample Output:

1 File ’ output . txt ’ created and string written successfully .

Program:

1 # include < stdio .h >


2

3 int main () {
4 FILE * file = fopen ( " output . txt " , " w " ) ; // Open the file for writing
5

6 if ( file == NULL ) {
7 printf ( " Error opening file !\ n " ) ;
8 return 1;
9 }
10

11 fprintf ( file , " Hello , World !\ n " ) ; // Write a string to the file
12 fclose ( file ) ; // Close the file
13

14 printf ( " File ’ output . txt ’ created and string written successfully .\ n " ) ;
15

16 return 0;
17 }

4.7 Reading from a File


Objective: Write a C program to open a file named input.txt, read the contents of the file, and display the contents

on the console. Ensure the file is properly closed after reading.

Instructions:

1. Open a file named input.txt for reading.

2. Read the contents of the file.

3. Display the contents on the console.

4. Close the file.

Sample Input:

1 Contents of input . txt : Welcome to File Handling in C .

Sample Output:

1 Contents of ’ input . txt ’:


2 Welcome to File Handling in C .

Program:

1 # include < stdio .h >


2

3 int main () {
4 FILE * file = fopen ( " input . txt " , " r " ) ; // Open the file for reading
5 char buffer [256]; // Buffer to hold file contents
6

7 if ( file == NULL ) {
8 printf ( " Error opening file !\ n " ) ;
9 return 1;
10 }
11

12 // Read and display the contents of the file


13 while ( fgets ( buffer , sizeof ( buffer ) , file ) != NULL ) {
14 printf ( " % s " , buffer ) ;
15 }
16

17 fclose ( file ) ; // Close the file


18

19 return 0;
20 }

4.8 Appending to a File


Objective: Write a C program to open an existing file named log.txt in append mode, add a new line of text to the

end of the file, and close the file.

Instructions:

1. Open a file named log.txt in append mode.

2. Add a new line of text to the end of the file.

3. Close the file.

Sample Input:

1 Text to append : New log entry .

Sample Output:

1 New line appended to ’ log . txt ’ successfully .

Program:

1 # include < stdio .h >


2

3 int main () {
4 FILE * file = fopen ( " log . txt " , " a " ) ; // Open the file in append mode
5

6 if ( file == NULL ) {
7 printf ( " Error opening file !\ n " ) ;
8 return 1;
9 }
10

11 fprintf ( file , " New log entry .\ n " ) ; // Append a new line of text
12 fclose ( file ) ; // Close the file
13

14 printf ( " New line appended to ’ log . txt ’ successfully .\ n " ) ;


15

16 return 0;
17 }
4.9 Copying File Contents
Objective: Write a C program to copy the contents of a file named source.txt to a new file named destination.txt.

Display a message indicating the completion of the file copy operation.

Instructions:

1. Open the source file source.txt for reading.

2. Open the destination file destination.txt for writing.

3. Copy the contents from the source file to the destination file.

4. Close both files.

5. Display a message indicating the completion of the copy operation.

Sample Input:

1 Contents of source . txt : File copy operation example .

Sample Output:

1 Contents copied from ’ source . txt ’ to ’ destination . txt ’ successfully .

Program:

1 # include < stdio .h >


2

3 int main () {
4 FILE * source = fopen ( " source . txt " , " r " ) ; // Open the source file for reading
5 FILE * destination = fopen ( " destination . txt " , " w " ) ; // Open the destination file for writing
6 char buffer [256]; // Buffer to hold file contents
7

8 if ( source == NULL || destination == NULL ) {


9 printf ( " Error opening file !\ n " ) ;
10 return 1;
11 }
12

13 // Copy contents from source to destination


14 while ( fgets ( buffer , sizeof ( buffer ) , source ) != NULL ) {
15 fputs ( buffer , destination ) ;
16 }
17

18 fclose ( source ) ; // Close the source file


19 fclose ( destination ) ; // Close the destination file
20

21 printf ( " Contents copied from ’ source . txt ’ to ’ destination . txt ’ successfully .\ n " ) ;
22

23 return 0;
24 }
4.10 File Operations with Error Handling
Objective: Write a C program to open a file named data.bin in binary mode for writing. Write an array of integers

to the file, and then open the file again in binary mode for reading, read the integers back, and display them. Implement

error handling for file operations.

Instructions:

1. Open a file named data.bin in binary mode for writing.

2. Write an array of integers to the file.

3. Open the file again in binary mode for reading.

4. Read the integers from the file and display them.

5. Implement error handling for file operations.

Sample Input:

1 Array to write : {10 , 20 , 30 , 40 , 50}

Sample Output:

1 Data written to ’ data . bin ’ and read successfully :


2 10
3 20
4 30
5 40
6 50

Program:

1 # include < stdio .h >


2 # include < stdlib .h >
3

4 int main () {
5 FILE * file ;
6 int numbers [] = {10 , 20 , 30 , 40 , 50};
7 int readNumbers [5];
8 size_t size = sizeof ( numbers ) / sizeof ( numbers [0]) ;
9

10 // Write integers to file in binary mode


11 file = fopen ( " data . bin " , " wb " ) ;
12 if ( file == NULL ) {
13 printf ( " Error opening file for writing !\ n " ) ;
14 return 1;
15 }
16 fwrite ( numbers , sizeof ( int ) , size , file ) ;
17 fclose ( file ) ;
18

19 // Read integers from file in binary mode


20 file = fopen ( " data . bin " , " rb " ) ;
21 if ( file == NULL ) {
22 printf ( " Error opening file for reading !\ n " ) ;
23 return 1;
24 }
25 fread ( readNumbers , sizeof ( int ) , size , file ) ;
26 fclose ( file ) ;
27

28 // Display the integers


29 printf ( " Data read from ’ data . bin ’:\ n " ) ;
30 for ( size_t i = 0; i < size ; i ++) {
31 printf ( " % d \ n " , readNumbers [ i ]) ;
32 }
33

34 return 0;
35 }

5 Strings
Strings
In C, strings are arrays of characters terminated by a null character (‘\0‘). The null character signifies the end of the

string. Strings are manipulated using a variety of functions provided in the C standard library.

Syntax

1 char str [ size ];

Example

1 char str [20] = " Hello , World ! " ;

Common String Functions


strlen()

Computes the length of a string (excluding the null character).

Syntax

1 size_t strlen ( const char * str ) ;

Example

1 # include < stdio .h >


2 # include < string .h >
3

4 int main () {
5 char str [] = " Hello " ;
6 printf ( " Length : % zu \ n " , strlen ( str ) ) ; // Output : Length : 5
7 return 0;
8 }
strcpy()

Copies a string from the source to the destination.

Syntax

1 char * strcpy ( char * dest , const char * src ) ;

Example

1 # include < stdio .h >


2 # include < string .h >
3

4 int main () {
5 char src [] = " Hello " ;
6 char dest [20];
7 strcpy ( dest , src ) ;
8 printf ( " Destination : % s \ n " , dest ) ; // Output : Destination : Hello
9 return 0;
10 }

strcat()

Concatenates (appends) one string to the end of another.

Syntax

1 char * strcat ( char * dest , const char * src ) ;

Example

1 # include < stdio .h >


2 # include < string .h >
3

4 int main () {
5 char dest [20] = " Hello " ;
6 char src [] = " World " ;
7 strcat ( dest , src ) ;
8 printf ( " Concatenated : % s \ n " , dest ) ; // Output : Concatenated : Hello World
9 return 0;
10 }

strcmp()

Compares two strings lexicographically.

Syntax

1 int strcmp ( const char * str1 , const char * str2 ) ;

Example

1 # include < stdio .h >


2 # include < string .h >
3

4 int main () {
5 char str1 [] = " Hello " ;
6 char str2 [] = " Hello " ;
7 int result = strcmp ( str1 , str2 ) ;
8 if ( result == 0) {
9 printf ( " Strings are equal \ n " ) ; // Output : Strings are equal
10 } else if ( result < 0) {
11 printf ( " str1 is less than str2 \ n " ) ;
12 } else {
13 printf ( " str1 is greater than str2 \ n " ) ;
14 }
15 return 0;
16 }

strchr()

Finds the first occurrence of a character in a string.

Syntax

1 char * strchr ( const char * str , int c ) ;

Example

1 # include < stdio .h >


2 # include < string .h >
3

4 int main () {
5 char str [] = " Hello " ;
6 char * ptr = strchr ( str , ’l ’) ;
7 if ( ptr != NULL ) {
8 printf ( " Character found at position : % ld \ n " , ptr - str ) ; // Output : Character found at
position : 2
9 }
10 return 0;
11 }

strstr()

Finds the first occurrence of a substring in a string.

Syntax

1 char * strstr ( const char * haystack , const char * needle ) ;

Example

1 # include < stdio .h >


2 # include < string .h >
3

4 int main () {
5 char str [] = " Hello , World ! " ;
6 char * ptr = strstr ( str , " World " ) ;
7 if ( ptr != NULL ) {
8 printf ( " Substring found at position : % ld \ n " , ptr - str ) ; // Output : Substring found at
position : 7
9 }
10 return 0;
11 }

strncat()

Concatenates a specified number of characters from the source string to the destination string.

Syntax

1 char * strncat ( char * dest , const char * src , size_t n ) ;

Example

1 # include < stdio .h >


2 # include < string .h >
3

4 int main () {
5 char dest [20] = " Hello " ;
6 char src [] = " World ! " ;
7 strncat ( dest , src , 6) ; // Append only " World "
8 printf ( " Concatenated : % s \ n " , dest ) ; // Output : Concatenated : Hello World
9 return 0;
10 }

strncpy()

Copies a specified number of characters from the source string to the destination string.

Syntax

1 char * strncpy ( char * dest , const char * src , size_t n ) ;

Example

1 # include < stdio .h >


2 # include < string .h >
3

4 int main () {
5 char src [] = " Hello , World ! " ;
6 char dest [20];
7 strncpy ( dest , src , 5) ; // Copy first 5 characters
8 dest [5] = ’ \0 ’; // Null - terminate the string
9 printf ( " Destination : % s \ n " , dest ) ; // Output : Destination : Hello
10 return 0;
11 }

These functions provide various capabilities for string manipulation and are essential for working with text data in C

programs.

5.1 Declare and Display a String


Objective: Write a C program to declare a string using character arrays, initialize it with a string literal, and display

the string on the console.


Instructions:

1. Declare a character array to hold a string.

2. Initialize the array with a string literal.

3. Display the string on the console.

Sample Input:

1 String literal : " Hello , C Programming !"

Sample Output:

1 The string is : Hello , C Programming !

Program:

1 # include < stdio .h >


2

3 int main () {
4 char str [] = " Hello , C Programming ! " ; // Declare and initialize the string
5

6 printf ( " The string is : % s \ n " , str ) ; // Display the string


7

8 return 0;
9 }

5.2 String Declaration and Length


Objective: Write a C program to declare a string using a character array, initialize it with a string literal, and compute

and display the length of the string using a loop.

Instructions:

1. Declare a character array and initialize it with a string literal.

2. Compute the length of the string using a loop.

3. Display the length of the string.

Sample Input:

1 String literal : " String Length Example "

Sample Output:

1 The length of the string is : 21

Program:

1 # include < stdio .h >


2

3 int main () {
4 char str [] = " String Length Example " ; // Declare and initialize the string
5 int length = 0;
6

7 // Compute the length of the string using a loop


8 while ( str [ length ] != ’ \0 ’) {
9 length ++;
10 }
11

12 printf ( " The length of the string is : % d \ n " , length ) ; // Display the length
13

14 return 0;
15 }

5.3 String Initialization with Arrays


Objective: Write a C program to initialize a string using a character array and display the string. Initialize the array

with both explicit and implicit null-termination.

Instructions:

1. Declare a character array and initialize it with a string literal.

2. Display the string.

3. Initialize another array explicitly with null-termination.

Sample Input:

1 String literal : " Array Initial ization "

Sample Output:

1 String with implicit null - termination : Array Initia lization


2 String with explicit null - termination : Array Initia lization

Program:

1 # include < stdio .h >


2

3 int main () {
4 char str1 [] = " Array Initia lization " ; // Implicit null - termination
5 char str2 [25] = { ’A ’ , ’r ’ , ’r ’ , ’a ’ , ’y ’ , ’ ’ , ’I ’ , ’n ’ , ’i ’ , ’t ’ , ’i ’ , ’a ’ , ’l ’ , ’i ’ , ’z ’ , ’a ’ , ’
t ’ , ’i ’ , ’o ’ , ’n ’ , ’ \0 ’ }; // Explicit null - termination
6

7 printf ( " String with implicit null - termination : % s \ n " , str1 ) ;


8 printf ( " String with explicit null - termination : % s \ n " , str2 ) ;
9

10 return 0;
11 }

5.4 String Initialization with Pointers


Objective: Write a C program to initialize a string using a pointer to a string literal, and then display the string. Show

the difference in initialization between using an array and a pointer.

Instructions:

1. Declare a pointer to a string literal.

2. Initialize the pointer with a string literal.

3. Display the string using the pointer.


4. Compare with the array initialization.

Sample Input:

1 String literal : " Pointer Ini tializat ion "

Sample Output:

1 String with array initial ization : Array Initia lization


2 String with pointer init ializati on : Pointer Initial ization

Program:

1 # include < stdio .h >


2

3 int main () {
4 char str1 [] = " Array Initia lization " ; // Array initiali zation
5 char * str2 = " Pointer Initi alizatio n " ; // Pointer ini tializat ion
6

7 printf ( " String with array in itializa tion : % s \ n " , str1 ) ;


8 printf ( " String with pointer initial ization : % s \ n " , str2 ) ;
9

10 return 0;
11 }

5.5 Using strcpy() and strlen()


Objective: Write a C program to use strcpy() to copy one string to another and strlen() to compute the length of

the string. Display both the copied string and its length.

Instructions:

1. Declare two character arrays.

2. Use strcpy() to copy a string from the source array to the destination array.

3. Use strlen() to compute the length of the copied string.

4. Display both the copied string and its length.

Sample Input:

1 Source string : " String Copy Example "

Sample Output:

1 Copied string : String Copy Example


2 Length of the copied string : 18

Program:

1 # include < stdio .h >


2 # include < string .h >
3

4 int main () {
5 char source [] = " String Copy Example " ;
6 char destination [50]; // Ensure sufficient size
7
8 // Copy source to destination
9 strcpy ( destination , source ) ;
10

11 // Compute length of the copied string


12 int length = strlen ( destination ) ;
13

14 // Display results
15 printf ( " Copied string : % s \ n " , destination ) ;
16 printf ( " Length of the copied string : % d \ n " , length ) ;
17

18 return 0;
19 }

5.6 Using strcmp() and strcat()


Objective: Write a C program to use strcmp() to compare two strings and strcat() to concatenate two strings.

Display the results of both operations.

Instructions:

1. Declare and initialize two strings.

2. Use strcmp() to compare the strings and display the result.

3. Use strcat() to concatenate the strings and display the result.

Sample Input:

1 String 1: " Hello "


2 String 2: " World "

Sample Output:

1 Comparison result : -1 ( String 1 is less than String 2)


2 Concatenated string : HelloWorld

Program:

1 # include < stdio .h >


2 # include < string .h >
3

4 int main () {
5 char str1 [50] = " Hello " ;
6 char str2 [] = " World " ;
7 char result [100]; // Ensure sufficient size
8

9 // Compare strings
10 int cmp_result = strcmp ( str1 , str2 ) ;
11 printf ( " Comparison result : % d \ n " , cmp_result ) ;
12

13 // Concatenate strings
14 strcpy ( result , str1 ) ;
15 strcat ( result , str2 ) ;
16 printf ( " Concatenated string : % s \ n " , result ) ;
17

18 return 0;
19 }

5.7 Check Null-Termination


Objective: Write a C program to demonstrate null-termination by printing each character of a string along with its

ASCII value until the null character is encountered.

Instructions:

1. Declare and initialize a string.

2. Iterate through the string and print each character along with its ASCII value.

3. Stop when the null character is encountered.

Sample Input:

1 String : " Null Termination "

Sample Output:

1 Character : N , ASCII : 78
2 Character : u , ASCII : 117
3 Character : l , ASCII : 108
4 Character : l , ASCII : 108
5 Character : , ASCII : 32
6 Character : T , ASCII : 84
7 Character : e , ASCII : 101
8 Character : r , ASCII : 114
9 Character : m , ASCII : 109
10 Character : i , ASCII : 105
11 Character : n , ASCII : 110
12 Character : a , ASCII : 97
13 Character : t , ASCII : 116
14 Character : i , ASCII : 105
15 Character : o , ASCII : 111
16 Character : n , ASCII : 110

Program:

1 # include < stdio .h >


2

3 int main () {
4 char str [] = " Null Termination " ;
5

6 // Print each character and its ASCII value


7 for ( int i = 0; str [ i ] != ’ \0 ’; i ++) {
8 printf ( " Character : %c , ASCII : % d \ n " , str [ i ] , str [ i ]) ;
9 }
10

11 return 0;
12 }
5.8 Null-Terminated String Length
Objective: Write a C program to compute the length of a string manually by iterating through the characters until the

null terminator is found.

Instructions:

1. Declare and initialize a string.

2. Iterate through the string manually to compute its length.

3. Display the length of the string.

Sample Input:

1 String : " Manual Length Calculation "

Sample Output:

1 Length of the string : 30

Program:

1 # include < stdio .h >


2

3 int main () {
4 char str [] = " Manual Length Calculation " ;
5 int length = 0;
6

7 // Compute length of the string manually


8 while ( str [ length ] != ’ \0 ’) {
9 length ++;
10 }
11

12 printf ( " Length of the string : % d \ n " , length ) ;


13

14 return 0;
15 }

5.9 Char Array and Pointer Access


Objective: Write a C program to declare a character array and a pointer to the array. Use the pointer to access and

modify elements of the array, and display the modified array.

Instructions:

1. Declare and initialize a character array.

2. Declare a pointer to the character array.

3. Use the pointer to access and modify elements of the array.

4. Display the modified array.

Sample Input:

1 Original array : " Hello , World ! "


2 Modifications : Change ’W ’ to ’M ’ and ’! ’ to ’? ’
Sample Output:

1 Modified array : Hello , Morld ?

Program:

1 # include < stdio .h >


2

3 int main () {
4 char arr [] = " Hello , World ! " ;
5 char * ptr = arr ; // Pointer to the character array
6

7 // Modify elements using pointer


8 ptr [7] = ’M ’; // Change ’W ’ to ’M ’
9 ptr [12] = ’? ’; // Change ’! ’ to ’? ’
10

11 // Display the modified array


12 printf ( " Modified array : % s \ n " , arr ) ;
13

14 return 0;
15 }

5.10 Pointer Arithmetic with Char Arrays


Objective: Write a C program to demonstrate pointer arithmetic by traversing a character array using a pointer and

displaying each character.

Instructions:

1. Declare and initialize a character array.

2. Use a pointer to traverse the array.

3. Display each character of the array.

Sample Input:

1 Character array : " Pointer Arithmetic "

Sample Output:

1 Characters in the array :


2 P
3 o
4 i
5 n
6 t
7 e
8 r
9 A
10 r
11 i
12 t
13 h
14 m
15 e
16 t
17 i
18 c

Program:

1 # include < stdio .h >


2

3 int main () {
4 char arr [] = " Pointer Arithmetic " ;
5 char * ptr = arr ; // Pointer to the character array
6

7 // Traverse and display characters using pointer arithmetic


8 while (* ptr != ’ \0 ’) {
9 printf ( " % c \ n " , * ptr ) ;
10 ptr ++;
11 }
12

13 return 0;
14 }

5.11 Pointers and Strings


Objective: Write a C program to compare two strings using a function that simulates the behavior of strcmp(). Display

whether the strings are equal, or if one is lexicographically greater than the other.

Instructions:

1. Write a function to compare two strings.

2. Use the function to compare the input strings.

3. Display the comparison result.

Sample Input:

1 String 1: " Apple "


2 String 2: " Banana "

Sample Output:

1 String 1 is less than String 2

Program:

1 # include < stdio .h >


2

3 int my_strcmp ( const char * str1 , const char * str2 ) {


4 while (* str1 && * str2 && (* str1 == * str2 ) ) {
5 str1 ++;
6 str2 ++;
7 }
8 return *( unsigned char *) str1 - *( unsigned char *) str2 ;
9 }
10

11 int main () {
12 char str1 [] = " Apple " ;
13 char str2 [] = " Banana " ;
14

15 int result = my_strcmp ( str1 , str2 ) ;


16

17 if ( result == 0) {
18 printf ( " The strings are equal \ n " ) ;
19 } else if ( result < 0) {
20 printf ( " String 1 is less than String 2\ n " ) ;
21 } else {
22 printf ( " String 1 is greater than String 2\ n " ) ;
23 }
24

25 return 0;
26 }

Case-Insensitive Comparison Objective: Write a C program to compare two strings in a case-insensitive manner by

converting both strings to lowercase before comparing them.

Instructions:

1. Convert both input strings to lowercase.

2. Use a function to compare the lowercase strings.

3. Display the result of the comparison.

Sample Input:

1 String 1: " HeLLo "


2 String 2: " hello "

Sample Output:

1 The strings are equal

Program:

1 # include < stdio .h >


2 # include < ctype .h >
3 # include < string .h >
4

5 void to_lowercase ( char * str ) {


6 while (* str ) {
7 * str = tolower (( unsigned char ) * str ) ;
8 str ++;
9 }
10 }
11

12 int my_strcmp ( const char * str1 , const char * str2 ) {


13 while (* str1 && * str2 && (* str1 == * str2 ) ) {
14 str1 ++;
15 str2 ++;
16 }
17 return *( unsigned char *) str1 - *( unsigned char *) str2 ;
18 }
19

20 int main () {
21 char str1 [] = " HeLLo " ;
22 char str2 [] = " hello " ;
23

24 // Convert both strings to lowercase


25 to_lowercase ( str1 ) ;
26 to_lowercase ( str2 ) ;
27

28 // Compare the lowercase strings


29 int result = my_strcmp ( str1 , str2 ) ;
30

31 if ( result == 0) {
32 printf ( " The strings are equal \ n " ) ;
33 } else if ( result < 0) {
34 printf ( " String 1 is less than String 2\ n " ) ;
35 } else {
36 printf ( " String 1 is greater than String 2\ n " ) ;
37 }
38

39 return 0;
40 }

5.12 Substring Search


Objective: Write a C program to find the first occurrence of a substring within a string using a function similar to

strstr(). Display the position of the first occurrence.

Instructions:

1. Define a function to find the first occurrence of a substring within a string.

2. Use the function to find the substring.

3. Display the position of the first occurrence.

Sample Input:

1 String : " Hello , World !"


2 Substring : " World "

Sample Output:

1 Position of the first occurrence : 7

Program:

1 # include < stdio .h >


2

3 // Function to find the first occurrence of a substring


4 char * my_strstr ( const char * haystack , const char * needle ) {
5 while (* haystack ) {
6 const char * h = haystack ;
7 const char * n = needle ;
8 while (* n && * h == * n ) {
9 h ++;
10 n ++;
11 }
12 if (!* n ) return ( char *) haystack ;
13 haystack ++;
14 }
15 return NULL ;
16 }
17

18 int main () {
19 char str [] = " Hello , World ! " ;
20 char sub [] = " World " ;
21

22 char * pos = my_strstr ( str , sub ) ;


23

24 if ( pos ) {
25 printf ( " Position of the first occurrence : % ld \ n " , pos - str ) ;
26 } else {
27 printf ( " Substring not found \ n " ) ;
28 }
29

30 return 0;
31 }

5.13 Count Substring Occurrences


Objective: Write a C program to count and display the number of occurrences of a substring within a given string.

Instructions:

1. Define a function to count occurrences of a substring within a string.

2. Use the function to count the occurrences.

3. Display the count.

Sample Input:

1 String : " abababab "


2 Substring : " ab "

Sample Output:

1 Number of occurrences : 4

Program:

1 # include < stdio .h >


2 # include < string .h >
3

4 int c ou nt _s u bs tr in g ( const char * str , const char * sub ) {


5 int count = 0;
6 const char * p = str ;
7 while (( p = my_strstr (p , sub ) ) != NULL ) {
8 count ++;
9 p += strlen ( sub ) ; // Move past the current occurrence
10 }
11 return count ;
12 }
13

14 char * my_strstr ( const char * haystack , const char * needle ) {


15 while (* haystack ) {
16 const char * h = haystack ;
17 const char * n = needle ;
18 while (* n && * h == * n ) {
19 h ++;
20 n ++;
21 }
22 if (!* n ) return ( char *) haystack ;
23 haystack ++;
24 }
25 return NULL ;
26 }
27

28 int main () {
29 char str [] = " abababab " ;
30 char sub [] = " ab " ;
31

32 int count = c ou n t_ su bs t ri ng ( str , sub ) ;


33

34 printf ( " Number of occurrences : % d \ n " , count ) ;


35

36 return 0;
37 }

5.14 Tokenization Example


Objective: Write a C program to tokenize a string using strtok() based on spaces. Display each token on a new line.

Instructions:

1. Define a string to be tokenized.

2. Use strtok() to tokenize the string based on spaces.

3. Display each token.

Sample Input:

1 String : " Tokenize this string "

Sample Output:

1 Token : Tokenize
2 Token : this
3 Token : string

Program:

1 # include < stdio .h >


2 # include < string .h >
3

4 int main () {
5 char str [] = " Tokenize this string " ;
6 char * token ;
7

8 // Get the first token


9 token = strtok ( str , " " ) ;
10

11 // Walk through other tokens


12 while ( token != NULL ) {
13 printf ( " Token : % s \ n " , token ) ;
14 token = strtok ( NULL , " " ) ;
15 }
16

17 return 0;
18 }

5.15 Tokenization with Different Delimiters


Objective: Write a C program to tokenize a string using strtok() with multiple delimiters (e.g., spaces, commas).

Display each token separately.

Instructions:

1. Define a string to be tokenized.

2. Use strtok() to tokenize the string based on multiple delimiters.

3. Display each token.

Sample Input:

1 String : " Apple , Orange Banana , Grape "

Sample Output:

1 Token : Apple
2 Token : Orange
3 Token : Banana
4 Token : Grape

Program:

1 # include < stdio .h >


2 # include < string .h >
3

4 int main () {
5 char str [] = " Apple , Orange Banana , Grape " ;
6 char * token ;
7

8 // Get the first token


9 token = strtok ( str , " ," ) ;
10

11 // Walk through other tokens


12 while ( token != NULL ) {
13 printf ( " Token : % s \ n " , token ) ;
14 token = strtok ( NULL , " ," ) ;
15 }
16

17 return 0;
18 }

5.16 String to Integer Conversion


Objective: Write a C program to define a function that converts a string to an integer, similar to atoi(). Test the

function with various string inputs.

Instructions:

1. Define a function to convert a string to an integer.

2. Test the function with different string inputs.

3. Display the converted integer.

Sample Input:

1 String : "12345"

Sample Output:

1 Integer : 12345

Program:

1 # include < stdio .h >


2

3 int my_atoi ( const char * str ) {


4 int result = 0;
5 while (* str >= ’0 ’ && * str <= ’9 ’) {
6 result = result * 10 + (* str - ’0 ’) ;
7 str ++;
8 }
9 return result ;
10 }
11

12 int main () {
13 char str [] = " 12345 " ;
14

15 int num = my_atoi ( str ) ;


16

17 printf ( " Integer : % d \ n " , num ) ;


18
19 return 0;
20 }

5.17 String to Integer with Error Handling


Objective: Write a C program to define a function that converts a string to an integer with basic error handling for

invalid inputs (e.g., non-numeric characters). Display appropriate error messages.

Instructions:

1. Define a function to convert a string to an integer with error handling.

2. Test the function with various string inputs.

3. Display appropriate error messages for invalid inputs.

Sample Input:

1 String : "123 abc "

Sample Output:

1 Error : Invalid input

Program:

1 # include < stdio .h >


2 # include < ctype .h >
3

4 int my_atoi ( const char * str ) {


5 int result = 0;
6 while (* str ) {
7 if (! isdigit (* str ) ) {
8 printf ( " Error : Invalid input \ n " ) ;
9 return -1; // Return error code
10 }
11 result = result * 10 + (* str - ’0 ’) ;
12 str ++;
13 }
14 return result ;
15 }
16

17 int main () {
18 char str [] = " 123 abc " ;
19

20 int num = my_atoi ( str ) ;


21

22 if ( num != -1) {
23 printf ( " Integer : % d \ n " , num ) ;
24 }
25

26 return 0;
27 }

You might also like