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

Lab Manual in C

Learn and understand the king of the day of the day of the day of my name and password ? is not like this is a holiday for today morning and numerical methods and numerical of the same as a holiday for the month ?? pm to madurai airport to

Uploaded by

wilsonabi2406
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Lab Manual in C

Learn and understand the king of the day of the day of the day of my name and password ? is not like this is a holiday for today morning and numerical methods and numerical of the same as a holiday for the month ?? pm to madurai airport to

Uploaded by

wilsonabi2406
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

CONTENTS

S.NO DATE TITLE PAGE NO MAX SIGN


MARKS
1(a) I/O Statements
1(b) Operators
1(c) Expressions
2(a) Decision Making Constructs: IF-Else
2(b) Goto Statements
2(c) Switch-Case Statements
2(d) Break-Continue Statements
3(a) Loops: For
3(b) While Loop
3(c) Do-While Loop
4(a) Arrays-One Dimensional array
4(b) Two Dimensional Array
4(c) Multidimensional Array
4(d) Traversal
5(a) Strings: String Length
5(b) String Compare
5(c) String Concatenates
5(d) String Copy
6(a) Functions: Calling
6(b) Passing Call By Value
6(c) Passing Call By Reference
6(d) Passing Arrays To Function
7 Recursion
8(a) Pointers To Functions
8(b) Pointers To Arrays
8(c) Pointers To Strings
8(d) Pointers To Pointers
9(a) Nested Structures
9(b) Pointers To Structures
9(c) Array Of Structures
9(d) Unions
10(a) Reading and writing a Files
10(b) File Pointers
10(c) File Operations
10(d) Random Access
10(e) Processor Directives
EX.NO:1(a) I/O STATEMENTS

Aim :

To write a Program to find the greater number between two numbers.

Algorithm:

Step 1: Start.

Step 2: Take two inputs (a and b) from the user.

Step 3: If a is greater than b then go to step 4 otherwise go to

step 5Step 4: Print a greater than b

Step 5: Print b greater than

aStep 6: Stop.

PROGRAM :

#include<stdio.h>

#include<conio.h>

void main()

int a,b;

printf("Enter two numbers :");

scanf("%d %d",&a,&b);

if (a>b)

printf("%d is greater",a);
printf("%d is greater",b);

getch();

Output :

Enter two numbers :4 5

5 is greater

Result :

Thus the c program output was verified successfully.


EX.NO:1(b) OPERATORS

Aim:

To write a program using operators for addition,subtraction,multiplication and division.


Algorithm:
Step 1:An operator is a symbol that operates on a variable or value. It is used for performing certain
operations like arithmetical, logical, relational, etc.
Step 2:When a programmer wants to perform some type of mathematical operation then you have to
use operators. The purpose of operators is mainly for mathematical and logical calculations.
Step 3:stop
Program:

int main()

{
int a = 10,b = 15, result;
result = a+b;
printf("Welcome to TechVidvan Tutorials...\n");
printf("Addition: a+b = %d \n",result);
result = a-b;
printf("Subtraction: a-b = %d \n",result);
result = a*b;
printf("Multiplication: a*b = %d \n",result);
result = a/b;
printf("Division: a/b = %d \n",result);
result = a%b;
printf("Modulo Division: %d \n",result);
result = ++a;
printf("Increment the value of a by 1: %d \n",result);
result = --b;
printf("Decremented the value of b by 1: %d \n",result);
return 0;
}
Output:
Welcome to TechVidvan Tutorials…
Addition: a+b = 25
Subtraction: a-b = -5
Multiplication: a*b = 150
Division: a/b = 0
Modulo Division: 10
Increment the value of a by 1: 11
Decremented the value of b by 1: 14

Result:
Thus the program output was verified successfully.
EX.NO:1(c) EXPRESSIONS

Aim:
To write a program using expressions for infix,postfix,prefix,unary and binary expressions.

Algorithm:

1. Infix Expression (operator is used between the operands)

a=x+y

2. Postfix Expression (operator is used after the operands)

xy+

3. Prefix Expression (operator is used before the operands)

+xy

4. Unary Expression (one operator and one operand)

x++

5. Binary Expression (one operator and two operands)

x+y

program:
#include <stdio.h>
int main()
{
int x = 4;
int y = 10;
if ( (x <10) && (y>5))
{
printf("Condition is true");
}
else
printf("Condition is false");
return 0;
}
Output
Condition is true

Result:

Thus the program output was verified successfully.


EX.NO:2(a) IF – ELSE STATEMENT

Aim:
To write a Program to find whether a number is odd or even.
Algorithm :

Step 1: Start.

Step 2: Take input from the user.

Step 3: Check condition. If remainder is zero go to step 4 else go to

step 5

Step 4: Print a is even and go to step 6

Step 5: Print a is odd

Step 6: Stop

Program :

#include<stdio.>
#include<conio.h>
void main()
{

int a;

printf("Enter a number :");


scanf("%d",&a);
if (a%2==0)

printf("%d is even",a);

else

printf("%d is odd",a);

getch();
}
Output:

Enter a number:5

5 is odd

Result :

Thus the c program odd number output was verified successfully.


EX.NO:2(b) GOTO STATEMENT

AIM :
Write a program to find factorial of a given number in C programming using the goto
statement.
Algorithm :

Step 1:two goto statements are used.

Step 2:The first goto statement (goto end and label end) works as a break statement and the
second goto statement (goto start and label start) works as a loop.

Step 3:To execute a group of statements repeatedly for a particular number of

times.

Step 4:To come out of several nested loops at one stroke.

Program:

#include<stdio.h>
#include<conio.h>
int main()

int num;
long fact = 1
printf("Enter a number: ");

scanf("%d",&num);

if(num<0)
goto end;
for(int i=1; i<=num; i++)
fact = fact * i;
printf("Factorial of %d is = %ld", num, fact);
end:

return 0;

}
Output:

Enter a number :5
Factorial 5 is 120

Result :

Thus the c program of factorial number output was verified successfully.


EX.NO:2(c) SWITCHCASE STATEMENT

Aim :

To write a program implement for print a number value using switch case statement

Algorithm :

Step 1:In the given program we have explain initialized a variable num with value 8.

Step 2:A switch construct is used to compare the value stored in variable num and execute the
block of statements associated with the matched case.

Step 3 :In this program, since the value stored in variable num is eight, a switch will execute the
case whose case-label is 8. After executing the case, the control will fall out of the switch and
program will be terminated with the successful result by printing the value on the output screen.

Step 4:Try changing the value of variable num and notice the change in the output.

Program :

#include<stdio.>

#include<conio.h>

int main()

int num = 3;

switch (num)

case 1:

printf("Value is

7"); break;

case 2:

printf("Value is 8");
break;

case 3:

printf("Value is 9");

break;

default:

printf("Out of range");

break;

return 0;

Output:

Value is 3

Result :

Thus the c program print given number output was verified successfully
EX.NO:2(d) BREAK –CONTINUE STATEMENT

Aim :

To write a program for own ID and create password using some message.

Algorithm :

Step 1:We considere the following program which the user to type his own ID.

Step 2:if the ID is valid it will ask him to enter his password, if the password is correct the
program will print the name of the user.

Step 3:otherwise ,the program will print Incorrect Password and if the ID does not exist , the
programwill print Incorrect ID

Program :

#include<stdio.h>

int main() {

int ID = 500;

int password = 000;

printf("Plese Enter YourID:\n");

scanf("%d", & ID);

switch (ID) {

case 500:

printf("Enter your password:\n ");

scanf("%d", & password);

switch (password)

case 000:

printf("Welcome Dear Programmer\n");

break;
default:
printf("incorrect password");

break;

break;

default:

printf("incorrect ID");

break;

Output:
Please Enter Your ID:

500

Enter your password:

000

Welcome Dear Programmer

Result :

Thus the c program student details output was verified successfully.


EX.NO:2(e) BREAK- CONTINUE STATEMENT

Aim :

To write a program using continue statement for print number 1 to 10 except 4 .


Algorithm :

Step 1:The continue statement is used to skip the remaining portion of a for/while loop.

Step 2: we continue onto the next iteration, and move to the loop condition check.

Step 3: This is quite useful for programmers to be flexible with their approach in controlloops.

Program :

// loop to print numbers 1 to 10 except 4

#include <stdio.h>

int main() {

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


{
// if i is equal to 4 , continue to next iteration without

printing 4. if (i == 4) {

continue;
}

else{

// otherwise print the value of

i. printf("%d ", i);

return 0;

}
OUTPUT :

1 2 3 5 6 7 8 9 10

Result :

Thus the program print numbers output was verified successfully.


EXP.NO:3(a) LOOPS:FOR,WHILE,DO-WHILE

Aim:
To write a program to implement in for print numbers using for looping statement.

Algorithm:
Step 1: Start
Step 2:Initialize variable K to 1, K=1
Step 3: Output K
Step 4: Increment K by 1
K=K+1
Step 5: Check if the value of K is less than or equal to 10. IF K<=10 THEN GOTO step 2 otherwise
GOTO Step 5
Step 6: Stop

Program:
// Print numbers from 1 to 10
#include <stdio.h>
int main() {
int i;
for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}
return 0;
}

Output
1 2 3 4 5 6 7 8 9 10

RESULT:
Thus the program print given numbers using looping output was verified successfully.
EXP.NO:3(b) WHILE LOOP

Aim:
To write to implement a program for print all even number between 1 to 100 using while loop
statement.

Algorithm :

Step1:declared a variable i and initialized it to 1.


Step 2:First, the condition (i < 100) is checked, if it is true.
Step 3: Control is transferred inside the body of the while loop. Inside the body of the loop,
if condition (i % 2 == 0) is checked, if it is true then the statement inside the if block is executed.
Step 4:Then the value of i is incremented using expression i++. As there are no more statements left
to execute inside the body of the while loop, this completes the first iteration.
Step 5:Again the condition (i < 100) is checked, if it is still true then once again the body of the loop
is executed.
Step 6: This process repeats as long as the value of i is less than 100. When i reaches 100, the loop
terminates and control comes out of the while loop.

Program:
#include<stdio.h>
int main()
{
int i = 1;
// keep looping while i < 100
while(i < 100)
{
// if i is even
if(i % 2 == 0)
{
printf("%d ", i);
}
i++; // increment i by 1
}
// signal to operating system everything works fine
return 0;
}

Output :
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96
98

RESULT:
Thus the program output was verified successfully.
EXP.NO:4(a) ARRAYS:1D AND 2D,MULTIDIMENSIONAL
ARRAYS,TRAVERSAL

Aim:
The following program uses for loop to take input and print elements of a 1-D array.

Algorithm:

Step1:Before using and accessing, we must declare the array variable.

Step 2:In array, indexing starts from 0 and ends at size-1. For example, if we have
arr[10] of size 10, then indexing of elements ranges from 0 to 9.

Step 3:We must include data-type and variable name while declaring one-dimensional arrays
in C.

Step 4:We can initialize them explicitly when the declaration specifies array size within
square brackets is not necessary.

Step 5:Each element of the array is stored at a contiguous memory location with a unique
index number for accessing.

PROGRAM:

#include<stdio.h>

int main()
{
int arr[5], i;

for(i = 0; i < 5; i++)


{
printf("Enter a[%d]: ", i);
scanf("%d", &arr[i]);
}

printf("\n Printing elements of the array: \n\n");

for(i = 0; i < 5; i++)


{
printf("%d ", arr[i]);
}
// signal to operating system program ran fine
return 0;
}

Output:

Enter a[0]: 11
Enter a[1]: 22
Enter a[2]: 34
Enter a[3]: 4
Enter a[4]: 34

Printing elements of the array:

11 22 34 4 34

RESULT:
Thus the program output was verified successfully.
EXP.NO:4(b) TWO DIMENSIONAL ARRAYS

Aim:
To is create a pointer for each row/column of the 2D array.

Algorithm:
Step 1:Suppose we have an array A of m rows and n columns. We can store the user input
data into our array A in the following way:
Step 2:Initially for i = 0, inner loop will traverse from j = 0 to j = n - 1.
Step 3:Thus for the 0th row, it will take n elements from the user.
Step 4:This process will be continued similarly for the second row (i = 1), third row, and so
on form rows.

Program:

#include<stdio.h>
#include<conio.h>
int void main()
{
int arr[2][3]={{3,2,1},{7,8,9}};
int *p(2);
P(0)=arr[0];
P(1)=arr[1];

for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{

Printf(“%d”,[i][j]);
}
Printf(“\n”);
}
Return 0;
}

Output:

3 2 1

789

Result:
Thus the program output was verified successfully.
EXP.NO:4(c) MULTIDIMENSIONAL ARRAYS

Aim:
Program to understand Multi-Dimensional Array in C Language:

ALGORITHM:
Step 1:type name[size1][size2]…[sizeN]; Example: int a[3][3][3];
Step 2:Declaration of Two-Dimensional Array in C Language. ...
Step 3:Initialization of Two-Dimensional Array in C Language. ...
Step 4: int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} };
Step 5: arrayName [ rowIndex ] [ columnIndex ];

Program:

#include <stdio.h>
void arr(int x[][3]); //function prototype
int main ()
{
int a[2][3] = {{1,2,3}, {4,5,6}}; //initializing array
int b[2][3] = {1, 2, 3, 4, 5};
int c[2][3] = {{1, 2}, {4}};
printf("values in array a by row:\n");
arr(a);
printf("values in array b by row:\n");
arr(b);
printf("values in array c by row:\n");
arr(c);
return 0;
} // end of main
void arr(int x[][3])
{
int i; //row counter
int j; //column counter
for (i = 0; i <= 1; ++i)
{
for (j = 0; j<= 2; ++j)
{
printf("%d", x[i][j]);
} //end of inner for
printf("\n");
} //end of outer for
}

Output:
Values in array a by row
123
456
Values in array a by row
123
450
values in array a by row
120
400

RESULT:
Thus the program output was verified successfully.
EXP.NO:4(d) TRAVERSAL ARRAYS

Aim:
To writing a program in C to perform traverse operation on an array

Algorithm:
Step 01: Start
Step 02: [Initialize counter variable. ] Set i = LB.
Step 03: Repeat for i = LB to UB.
Step 04: Apply process to arr[i].
Step 05: [End of loop. ]
Step 06: Stop

Variables used:

1. i : Loop counter or counter variable for the for loop.


2. arr : Array name.
3. LB : Lower bound. [ The index value or simply index of the first element of an array is called
its lower bound ]
4. UB : Upper bound. [ The index of the last element is called its upper bound ]

PROGRAM:
// writing a program in C to perform traverse operation on an array

#include<stdio.h>

#include<conio.h>

void main()
{
int i, size;

int arr[]={1, -9, 17, 4, -3}; //declaring and initializing array

size=sizeof(arr)/sizeof(arr[0]); //sizeof(arr) will give 20 and sizeof(arr[0]) will give 4

printf("The array elements are: ");

for(i=0;i<size;i++)

printf("\narr[%d]= %d", i, arr[i]);


}
Output:

The array elements are:


arr[0]= 1
arr[1]= -9
arr[2]= 17
arr[3]= 4
arr[4]= -3

Result:

Thus the program output was verified successfully.


EXP.NO:5 (a) STRINGS:OPERATIONS

Aim:
To write a program to implement Find out the length of the string.

Algorithm:
Step 1:strlen returns you the length of the string stored in array, however size of returns the
total allocated size assigned to the array.

Step 2:So if I consider the above example again then the following statements would return
the below values.

Step 3:strlen(str1) returned value 13.


step 4:sizeof(str1) would return value 20 as the array size is 20 (see the first statement in main
function).

Program:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));
return 0;
}

Output:

Length of string str1: 13

RESULT:

Thus the program output was verified successfully.


EXP.NO:5(b) STRING-STRCMP

Aim:

To wirte a program for compare two strings.

Algorithm:

Step 1:It compares the two strings and returns an integer value.

Step 2:If both the strings are same (equal) then this function would return 0 otherwise it may
return a negative or positive value based on the comparison.

Step 3:If string1 < string2 OR string1 is a substring of string2 then it would result in a
negative value. If string1 > string2 then it would return positive value.
step 4:If string1 == string2 then you would get 0(zero) when you use this function for
compare strings.

Example of strcmp:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}

Output:

string 1 and 2 are different

RESULT:
Thus the program output was verified successfully.
EXP.NO:5(c) STRING-STRCAT

Aim:

To write a program implement for concatenates two strings and returns the concatenated
string.

Algorithm:

Step 1:It concatenates n characters of str2 to string str1.

Step 2: A terminator char (‘\0’) will always be appended at the end of the concatenated string.

Step 3: stop

Example of strcat:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}

Output:

Output string after concatenation: HelloWorld

RESULT:

Thus the program output was verified successfully.


EXP.NO:5(d) STRING-STRCPY

Aim:

To write a program for copies the string str2 into string str1, including the end character
(terminator char ‘\0’).

Algorithm:

Step 1:char *strncpy( char *str1, char *str2, size_t n)


sterp 2:size_t is unassigned short and n is a number.
step 3: If length of str2 > n then it just copies first n characters of str2 into str1.
step 4: If length of str2 < n then it copies all the characters of str2 into str1 and appends
several terminator chars(‘\0’) to accumulate the length of str1 to make it n.

Example of strcpy:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}
Output:

String s1 is: string 2: I’m gonna copied into s1

RESULT:
Thus the program output was verified successfully.
EXP.NO:6(a) FUNCTIONS :CALL

Aim:
To write a program using to call a function using add to numbers.

Algorithm:

Step 1:A function call is an important part of the C programming language.

Step 2:It is called inside a program whenever it is required to call a function.

Step 3:It is only called by its name in the main() function of a program. We can pass the
parameters to a function calling in the main() function.

Program:

#include <stdio.h>
int add(int a, int b);
void main()
{

int sum;
int a, b;
printf(" Enter the first and second number \n");
scanf("%d %d", &a, &b);
sum = add(a, b); // call add() function
printf( "The sum of the two number is %d", sum);
}
int add(int n1, int n2) // pass n1 and n2 parameter
{
int c;
c = n1 + n2;
return c;
}

Output:

Enter the first and second number


5
6
The sum of the two number is 11

Result:

Thus the program output was verified successfully.


EXP.NO:6(b) FUNCTIONS PASSING BY VALUE

Aim:

To write a program using parameter for call by value functions.

Algorithm:

Step 1:In call by value method, the value of the actual parameters is copied into the formal
parameters.

Step 2:In other words, we can say that the value of the variable is used in the function call in
the call by value method.

Step 3:In call by value method, we can not modify the value of the actual parameter by the
formal parameter.

Step 4:In call by value, different memory is allocated for actual and formal parameters since
the value of the actual parameter is copied into the formal parameter.

Program:

#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b
in main
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do
not chane by changing the formal parameters in call by value, a = 10, b = 20
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20,
b = 10
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 2

Result:
Thus the program output was verified successfully.
EXP.NO:6(c) FUNCTIONS PASSING BY REFERENCE

Aim:
To write a program using call by reference for swapping values of two variables.

Algorithm:
Step 1:In call by reference, the address of the variable is passed into the function call as the
actual parameter.

Step 2:The value of the actual parameters can be modified by changing the formal parameters
since the address of the actual parameters is passed.

Step 3:In call by reference, the memory allocation is similar for both formal parameters and
actual parameters.

Step 4:All the operations in the function are performed on the value stored at the address of
the actual parameters, and the modified value gets stored at the same address.

Program:

Call by reference Example: Swapping the values of the two variables


#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b
in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters d
o change in call by reference, a = 10, b = 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20,
b=1
}
Output

Before swapping the values in main a = 10, b = 20


After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

Result:
Thus the program output was verified successfully.
EXP.NO:6(d) FUNCTIONS PASSING ARRAY TO FUNCTION
EXP.NO:6(c) FUNCTIONS PASSING BY REFERENCE

Aim:
To write a program implement using functions passing array elements.

Algorithm:
Step 1:In function call method, using array the value of the actual parameters is copied into
the formal parameters .

Step 2:In other words, we can say that the value of the variable is used in the function call in
the call by value method.

Step 3:In call by value method, we can not modify the value of the actual parameter by the
formal parameter.

Program:
#include<stdio.h>
int minarray(int arr[],int size){
int min=arr[0];
int i=0;
for(i=1;i<size;i++){
if(min>arr[i]){
min=arr[i];
}
}//end of for
return min;
}//end of function
int main(){
int i=0,min=0;
int numbers[]={4,5,7,3,8,9};//declaration of array
min=minarray(numbers,6);//passing array with size
printf("minimum number is %d \n",min);
return 0;
}

Output

minimum number is 3

Result:
Thus the program output was verified successfully.
EXP.NO:7 RECURSION

Aim:
To write a c program tofind factorial number using recursion.

Algorithm:

Step 1:In this program, we will read a number and then find (calculate) of factorial of that
number using recursion.
step 2: Factorial of a number is the product of that number with their all below integers.
For example (Factorial of 5) is: !5 = 5*4*3*2*1 = 120

Step 3:stop

Program:

/*C program to find factorial of a number using recursion.*/

#include <stdio.h>

//function for factorial


long int factorial(int n)
{
if(n==1) return 1;
return n*factorial(n-1);
}
int main()
{
int num;
long int fact=0;

printf("Enter an integer number: ");


scanf("%d",&num);

fact=factorial(num);
printf("Factorial of %d is = %ld",num,fact);
printf("\n");
return 0;
}

Output
Enter an integer number: 5
Factorial of 5 is = 120

Result:
Thus the program output was verified successfully.
EXP.NO:8(a) POINTERS:POINTERS TO FUNCTIONS

Aim:
To write a program swap two numbers using pointers to functions.
Algorithm:
Step 1: To pass addresses and pointers as arguments to functions with the help of examples.

Step 2:It is also possible to pass addresses as arguments to functions.

Step 3:To accept these addresses in the function definition, we can use pointers. It's because
pointers are used to store addresses. Let's take an example:

Program:
#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
int num1 = 5, num2 = 10;
// address of num1 and num2 is passed
swap( &num1, &num2);
printf("num1 = %d\n", num1);
printf("num2 = %d", num2);
return 0;
}
void swap(int* n1, int* n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
Run Code
output will be:

num1 = 10
num2 = 5

Result:
Thus the program output was verified successfully.
EXP.NO:8(b) ARRAYS OF POINTERS

Aim:
To write a program using pointers to array elements for sum of values.
Algorithm:
Step 1:Start
Step 2:Initialize variables array of [6] values.
Step 3:Initialize sum=0;
Step 4: Using for i=0 and x[i].
Step 5: Stop.

Example 1: Pointers and Arrays

#include <stdio.h>
int main() {
int i, x[6], sum = 0;
printf("Enter 6 numbers: ");
for(i = 0; i < 6; ++i) {
// Equivalent to scanf("%d", &x[i]);
scanf("%d", x+i);
// Equivalent to sum += x[i]
sum += *(x+i);
}
printf("Sum = %d", sum);
Return 0;
}

output will be:

Enter 6 numbers: 2
3
4
4
12
4
Sum = 29

Result:
Thus the program output was verified successfully.
EXP.NO:8(c) ARRAYS OF STRINGS

Aim:
To write a program using array of string pointers.
Algorithm:
Step 1: the same result by creating a character pointer that points at a string value stored at
some memory location.
Step 2:In the following example we are using character pointer variable strPtr to string value
Step 3: stop.
Program:

#include <stdio.h>

int main(void) {

// array of pointers

char *cityPtr[4] = {

"Chennai",

"Kolkata",

"Mumbai",

"New Delhi"

};

// temporary variable

int r, c;

// print cities

for (r = 0; r < 4; r++) {

c = 0;

while(*(cityPtr[r] + c) != '\0') {

printf("%c", *(cityPtr[r] + c));

c++;

} printf("\n");

}
return 0;

Output:

Chennai

Kolkata

Mumbai

New Delhi

Result:
Thus the program output was verified successfully.
EXP.NO:8(d) POINTERS TO POINTERS

Aim:

To write a program using pointers to pointers to a location in memory used to strore the
address of variables.

Algorithm:

Step1:We already know that a pointer points to a


location in memory and thus used to store the address
of variables.

Step 2:we define a pointer to pointer. The first pointer


is used to store the address of the variable.

Step 3:And the second pointer is used to store the


address of the first pointer.

Program:

#include <stdio.h>

// C program to demonstrate pointer to pointer

int main()

int var = 789;

// pointer for var

int *ptr2;

// double pointer for ptr2

int **ptr1;

// storing address of var in ptr2

ptr2 = &var;

// Storing address of ptr2 in ptr1


ptr1 = &ptr2;

// Displaying value of var using

// both single and double pointers

printf("Value of var = %d\n", var );

printf("Value of var using single pointer = %d\n",


*ptr2 );

printf("Value of var using double pointer = %d\n",


**ptr1);

return 0;

Output:
Value of var = 789
Value of var using single pointer = 789
Value of var using double pointer = 789

Result:

Thus the program output was verified successfully.


EXP.NO:9(a) NESTED STRUCTURES

Aim:
To write a program using nested structure for student details.

Algorithm:
Step 1:A nested structure in C is a structure within structure. One structure can be declared
inside another structure in the same way structure ..
Step 2:the syntax to create nested structures. structure tagname_1 { member1; member2;
member3; ... membern; structure tagname_2 { member_1; member_2; member_3; ...
member_n; }, var1 } var2;
Step 3: Nesting of structures can be extended to any level.

Program:

#include <stdio.h>

#include <string.h>

struct College

char college_name[20];

int ranking;

struct Student

int student_id;

char name[20];

int roll_no;

// Inner structure variable

} student1;

};

int main()
{

struct College c1 = {"GeeksforGeeks", 7,

{111, "Paul", 278}};

printf("College name : %s\n",

c1.college_name);

printf("Ranking : %d\n",

c1.ranking);

printf("Student id : %d\n",

c1.student1.student_id);

printf("Student name : %s\n",

c1.student1.name);

printf("Roll no : %d\n",

c1.student1.roll_no);

return 0;

Output:
College name : GeeksforGeeks
Ranking : 7
Student id : 111
Student name : Paul
Roll no : 278

Result:

Thus the program output was verified successfully.


EXP.NO:9(b) POINTER TO STRUCTURES

Aim:
To write a program using pointer to structure for student mark statement

Algorithm:
Step 1:As we can see in the above program, we have created a structure with name student, and
the student structure contains different members such as name (char), roll_no (int), state (char), age
(int).
Step 2:The student structure also defines two variables like s1 and s2, that access the structure
members using dot operator inside the main() function.
Step 3:stop

Step 4:The structure pointer points to the address of a memory block where the Structure is being
stored. Like a pointer that tells the address of another variable of any data type (int, char, float) in
memory.

Step 5:And here, we use a structure pointer which tells the address of a structure in memory by
pointing pointer variable ptr to the structure variable.

Program:
#include <stdio.h>
#include <string.h>
// create the Structure of student to store multiples items
struct student
{
char name[ 30];
int roll_no;
char state[100];
int age;
};
struct student s1, s2; // declare s1 and s2 variables of student structure
int main()
{
// records of the student s1
strcpy (s1.name, "John");
s1.roll_no = 1101;
strcpy (s1.state, "Los Angeles");
s1.age = 20;
// records of the student s2
strcpy (s2.name, " Mark Douglas");
s2.roll_no = 111;
strcpy (s2.state, "California");
s2.age = 18;
// print the details of the student s1;

printf (" Name of the student s1 is: %s\t ", s1.name);


printf (" \n Roll No. of the student s1 is: %d\t ", s1.roll_no);
printf (" \n The state of the student s1 is: %s\t ", s1.state);
printf (" \n Age of the student s1 is: %d\t ", s1.age);
// print the details of the student s2;
printf ("\n Name of the student s1 is: %s\t ", s2.name);
printf (" \n Roll No. of the student s1 is: %d\t ", s2.roll_no);
printf (" \n The state of the student s1 is: %s\t ", s2.state);
printf (" \n Age of the student s1 is: %d\t ", s2.age);
return 0;
}

Output:

Name of the student s1 is: John


Roll No. of the student s1 is: 1101
state of the student s1 is: Los Angeles
Age of the student s1 is: 20
Name of the student s1 is: Mark Douglas
Roll No. of the student s1 is: 111
The state of the student s1 is: California
Age of the student s1 is: 18

Result:
Thus the program output was verified successfully.
EXP.NO:9(c) ARRAY OF STRUCTURES

Aim:
To write a program using array of structure in collection of multiple structures.

Algorithm:

Step 1:An array of structres in C can be defined as the collection of multiple structures
variables where each variable contains information about different entities.

Step 2:The array of structures in C are used to store information about multiple entities of
different data types. The array of structures is also known as the collection of structures.

Step 3:stop

Program:
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz

Student Information List:


Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz

Result:
Thus the program output was verified successfully.
EXP.NO:9(e) UNIONS

Aim:
To write a program implement for student record details using unions.

Algorithm:

Step 1:A union-find algorithm is an algorithm that performs two useful operations on
such a data structure:

Step 2:Find: Determine which subset a particular element is in. This can be used for
determining if two elements are in the same subset.

Step 3:Union: Join two subsets into a single subset.

Program:

#include <stdio.h>
#include <string.h>

union student
{
char name[20];
char subject[20];
float percentage;
};

int main()
{
union student record1;
union student record2;

// assigning values to record1 union variable


strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;

printf("Union record1 values example\n");


printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);

// assigning values to record2 union variable


printf("Union record2 values example\n");
strcpy(record2.name, "Mani");
printf(" Name : %s \n", record2.name);

strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);

record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;
}

OUTPUT:
Union record1 values example
Name :
Subject :
Percentage : 86.500000;
Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000

Result:
Thus the program output was verified successfully.
EXP.NO:10(a) READING AND WRITING A FILES

Aim:

To reading and writing to a text file, we use the functions fprintf() and fscanf().

Alogorithm:

Step 1:They are just the file versions of printf() and scanf().
Step 2:The only difference is that fprintf() and fscanf() expects a pointer to the structure
FILE.

Example 1: Write to a text file

#include <stdio.h>
#include <stdlib.h>

int main()
{
int num;
FILE *fptr;

// use appropriate location if you are using MacOS or Linux


fptr = fopen("C:\\program.txt","w");

if(fptr == NULL)
{
printf("Error!");
exit(1);
}

printf("Enter num: ");


scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}

This program takes a number from the user and stores in the file program.txt.
After you compile and run this program, you can see a text file program.txt created in C drive of your
computer. When you open the file, you can see the integer you entered.

Example 2: Read from a text file


#include <stdio.h>
#include <stdlib.h>

int main()
{
int num;
FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);


fclose(fptr);

return 0;
}

Result: Thus the program output was verified successfully.


EXP.NO:10(b) FILE POINTERS

Aim:
To Write a c program is used to write and create the text file based on user input student id,
name and mark using file write mode.

Algorithm:

w -> used to open file for writing and new file is created always and assumed that file does not exists.
a -> used to open file for appending and initial position is at the end of the file.
r+ -> used to open file for update (both reading and writing), initial position is at the start of the file
for reading and writing.
w+ -> used to open file for update (both reading and writing) and new file is created if file does not
exists, initial position is at the start of the file for reading and writing
a+ -> used to open file for update (both reading and writing), initial position is at the end of the file
for reading and writing.

#include<stdio.h>

void main()
{
FILE *fp;
char *student_name;
int student_id, mark;
fp = fopen("student_mark_list.txt", "w");
printf("\nEnter student id: ");
scanf("%d", &student_id);

printf("\nEnter student name: ");


scanf(" %s", student_name);

printf("\nEnter student mark: ");


scanf("%d", &mark);

fprintf(fp, "%d\t%s\t%d\n", student_id, student_name, mark);


fclose(fp);
printf("\nStudent mark is written successfully!");
}

Output:

$ cc file-write.c
$ ./a.out

Enter student id: 23

Enter student name: student1

Enter student mark: 87

Student mark is written successfully!

created text file:

$ cat student_mark_list.txt
23 student1 87

Result:
Thus the program output was verified successfully.
EXP.NO:10(c) FILE OPERATIONS

Aim:
To write a c program implementing used for file operations.

C file write with different formats


It's possible to have the different format for each record in file if we want.
Lets see the above program to write file in comma separated file format instead of \t space

#include<stdio.h>

void main()
{
FILE *fp;
char *student_name;
int student_id, mark;
fp = fopen("student_mark_list.txt", "w");
printf("\nEnter student id: ");
scanf("%d", &student_id);

printf("\nEnter student name: ");


scanf(" %s", student_name);

printf("\nEnter student mark: ");


scanf("%d", &mark);

fprintf(fp, "%d,%s,%d\n", student_id, student_name, mark);


fclose(fp);
printf("\nStudent mark is written successfully!");
}

Output:

$ cc file-write.c
$ ./a.out
Enter student id: 35

Enter student name: student1

Enter student mark: 90

Student mark is written successfully!

created text file:

$ cat student_mark_list.txt
35,student1,90

Result:
Thus the c program for file operations was verified successfully.
EXP.NO:10(d) RANDOM ACCESS

Aim:
To create a Random Acccess file using for fopen,fclose,fread,fwrite,fseek and ftell.

Steps:

 fopen - open a file- specify how it's opened (read/write) and type (binary/text)
 fclose - close an opened file.
 fread - read from a file.
 fwrite - write to a file.
 fseek/fsetpos - move a file pointer to somewhere in a file.
 ftell/fgetpos - tell you where the file pointer is located.

Random accessing of files in C language can be done with the help of the following functions −

 ftell ( )
 rewind ( )
 fseek ( )
ftell ( )
It returns the current position of the file ptr.
The syntax is as follows −
int n = ftell (file pointer)
For example,
FILE *fp;
int n;
_____
_____
_____
n = ftell (fp);
Note − ftell ( ) is used for counting the number of characters which are entered into a file.
rewind ( )
It makes file ptr move to beginning of the file.
The syntax is as follows −
rewind (file pointer);
For example,
FILE *fp;
-----
-----

rewind (fp);
n = ftell (fp);
printf ("%d”, n);
Output
The output is as follows −
0 (always).
fseek ( )
It is to make the file pntr point to a particular location in a file.
The syntax is as follows −
fseek(file pointer, offset, position);
Offset

 The no of positions to be moved while reading or writing.


 If can be either negative (or) positive.
o Positive - forward direction.
o Negative – backward direction.
Position
It can have three values, which are as follows −

 0 – Beginning of the file.


 1 – Current position.
 2 – End of the file.
Example
 fseek (fp,0,2) - fp moved 0 bytes forward from the end of the file.
 fseek (fp, 0, 0) – fp moved 0 bytes forward from beginning of the file
 fseek (fp, m, 0) – fp moved m bytes forward from the beginning of the file.
 fseek (fp, -m, 2) – fp moved m bytes backward from the end of the file.
Errors
The errors related to fseek () function are as follows −

 fseek (fp, -m, 0);


 fseek(fp, +m, 2);
EXP.NO:10(e) PROCESSOR DIRCTIVIES

C PROCESSOR DIRECTIVES:
 Before a C program is compiled in a compiler, source code is processed by a program called
preprocessor. This process is called preprocessing.
 Commands used in preprocessor are called preprocessor directives and they begin with “#”
symbol.

Syntax/Description

Preprocessor
Syntax: #define
This macro defines constant
value and can be any of the basic
Macro data types.
Syntax: #include <file_name>
The source code of the file
“file_name” is included in the
Header file main program at the specified
inclusion place.
Syntax: #ifdef, #endif, #if, #else,
#ifndef
Set of commands are included or
excluded in source program
Conditional before compilation with respect
compilation to the condition.
Syntax: #undef, #pragma
#undef is used to undefine a
defined macro variable. #Pragma
is used to call a function before
Other and after main function in a C
directives program.
A program in C language involves into different processes. Below diagram will help you to
understand all the processes that a C program comes across.
There are 4 regions of memory which are created by a compiled C program. They are,

1. First region – This is the memory region which holds the executable code of the program.
2. 2nd region – In this memory region, global variables are stored.
3. 3rd region – stack
4. 4th region – heap

Result:
Thus the program in processor directives output was verified successfully.

You might also like