[go: up one dir, main page]

0% found this document useful (0 votes)
58 views64 pages

C Lab Manual PDF

The document provides a series of C programming exercises focusing on I/O statements, decision-making constructs, loops, and arrays. Each exercise includes an aim, algorithm, program code, output, and a result indicating successful execution. Additionally, it features viva questions that cover key concepts related to each topic.

Uploaded by

afsira15
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)
58 views64 pages

C Lab Manual PDF

The document provides a series of C programming exercises focusing on I/O statements, decision-making constructs, loops, and arrays. Each exercise includes an aim, algorithm, program code, output, and a result indicating successful execution. Additionally, it features viva questions that cover key concepts related to each topic.

Uploaded by

afsira15
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/ 64

Ex.

No:1 I/O STATEMENTS, OPERATORS AND EXPRESSION

Aim:
To write a C program using I/O statements, operators and expressions.

Algorithm:
1. Read a character, a string, a float value, an integer number, a double value from the user
using scanf() statement and store it in variables ch, str, flt, num, dbl.
2. Display all the variables using printf()statement.
3. Assign the operations like addition, subtraction, multiplication, division and modulus for the
values of a and b.
4. Display the result for various operations

Program:
#include<stdio.h>
int main ()
{
char ch,str[20];
float flt;
int num, a = 5, b = 3, c = a + b;
double dbl;
printf("Enter a character\n");
scanf("%c",&ch);
printf("Enter a string\n");
scanf("%s",&str);
printf("Enter a float value\n");
scanf("%f",&flt);
printf("Enter an integer\n");
scanf("%d",&num);
printf("Enter a double value\n");
scanf("%lf",&dbl);
printf("\nDisplaying:\n");

1
printf("Character is %c\n",ch);
printf("String is %s\n",str);
printf("Float value is %f\n",flt);
printf("Integer value is %d\n",num);
printf("Double value is %lf\n",dbl);
printf("\nExpressions:\n");
printf("Prefix value is %d\n",++c);
printf("Postfix value is %d\n",c++);
printf("Infix value is %d\n",a+b);
printf("\nOperations:\n");
printf("Addition is %d\n",a+b);
printf("Subtraction is %d\n",a-b);
printf("Muliplication is %d\n",a*b);
printf("Division is %d\n",a/b);
printf("Modulus is %d\n",a%b) return 0;

2
Output:
Enter a
character
a
Enter a
string“welc
ome”
Enter a float
value10.53
Enter an integer
number350
Enter a double
value20.23451

Displaying:
Character
isa
String
is“welcome
”Float value
is10.53
Integer value
is350
Double value
is20.23451

Expressions:
Prefix value
is9
Postfix value
is9
Infix value
3
is8

Operations:
Addition is 8
Subtraction is 2
Multiplication is 15
Division is 1
Modulus is 2

Result:
Thus a C program using I/O statements, operators and expressions is executed successfully.
4
VIVA QUESTION

1. What are input and output statements?


Input and output statements allow data to be transferred between a computer's main and auxiliary
storage. For example, in PL/I, input and output statements include READ, WRITE, GET, and PUT.

2. Mention the different types of operators used in C ?

Arithmetic operator

Relational operators

Logical Operators

Increment and decrements operators

Assignment operators

Conditional operatorBitwise oprators

3. What is an operator and operand?

An operator performs an operation like addition, subtraction and so on and produce a value.
Variables and constants upon which operations are performed are called operands.

4.What are Increment / Decrement Operators?

Increment operators are used to increase the value of the variable by one anddecrement operators
are used to decrease the value of the variable by one in C programs.(Like ++, --)

5. What is mean by Operators precedence and associative?


Ans:The precedence of operators in C dictates the order in which the operators will be evolved in an
expression. Associativity, on the other hand, defines the order in which the operators of the same
precedence will be evaluated in an expression. Also, associativity can occur from either right to left
or left to right.

5
Ex. No:2 DECISION-MAKING CONSTRUCTS: IF-ELSE,GOTO,
SWITCH-CASE, BREAK-CONTINUE

Aim:
To write a C program using decision-making constructs: if-else, goto, switch-case,
break-continue

Algorithm:
1. Start the program.
2. Declare the variables regno , t_mark , n , i, name.
3. Create a function name as student_details
4. Read the student details and check the condition 200<=t_mark, using if...else .if it is true
goto step 5 else goto step 6.
5. Display the mark range using switch case and break.
6. Display the result at theend of if-else statement.
7. Use goto statement in function call and call the function name as students_details.
8. Display the i value using loop in continue statement.
9. Display the result in various decision making statements.
10. End the program
Program:
#include<stdio.h>
#include<conio.h>
int main()
{
int regno,t_mark,n,i=1;
char name[20];
printf("Student Grade Validation\n");
students_details:
{
printf("\nEnter Name of the Student:");
scanf("%s",&name);
printf("\n Enter Student Register Number:");
scanf("%d",&regno);
printf("\nEnter %s's Total Mark obtained:",name);

6
scanf("%d",&t_mark);
if(200<=t_mark)
{
printf("\n 1.450 to 500 \t 2.400 to 450 \t 3.350 to 400 \t 4.300 to 350 \t 5.200 to
300");
printf("\n Choose your mark range:");
scanf("%d",&n);
switch(n)
{
case 1:
printf("\nYour rank is FIRST class and you are passing with A Grade");
break;
case 2:
printf("\nYour rank is FIRST class and you are passing with B Grade");
break;
case 3:
printf("\nYour rank is FIRST class and you are passing with C Grade");
break;
case 4:
printf("\nYour rank is SECOND class and you are passing with D Grade");
break;
case 5:
printf("\nYour rank is SECOND class and you are passing");
break;
}

printf("\nCONGRATULATIONS!!!");
if(499==t_mark)
{
printf("\n Best wishes!!!\n You are a state first to your state!!!");
}
else
{
printf("\n Best wishes!!!\n");
7
}
}
else
{
printf("\n Sorry you are fail, Better luck next time!!!\n");
}
}
i++;
if(i==1)
{
goto students_details;
}
printf("\nContinue statement\n");
for(i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
printf("%d\n",i);
}
printf("End program");
}

Output:

Student Grade Validation


Enter Name of the Student:Sharu
Enter Student Register Number:4046
Enter Sharu's total mark:499
1.450 to 500 2.400 to 450 3.350 to 400 4.300 to 350 5.200 to 250
Choose your mark range:1
Your rank is FIRST class and you are passing with A Grade
CONGRATULATIONS!!!
Best wishes!!!

8
You are a state first to your state!!!
Continue statement
1
2
3
4
6
7
8
9
10
End program

Student Grade Validation


Enter Name of the Student:Sharu
Enter Student Register Number:4046
Enter Sharu's total mark:440
1.450 to 500 2.400 to 450 3.350 to 400 4.300 to 350 5.200 to 250
Choose your mark range:2
Your rank is FIRST class and you are passing with B Grade
CONGRATULATIONS!!!
Best wishes!!!
Continue statement
1
2
3
4
6
7
8
9
10
End program
9
Student Grade Validation
Enter Name of the Student:Sharu
Enter Student Register Number:4046
Enter Sharu's total mark:382
1.450 to 500 2.400 to 450 3.350 to 400 4.300 to 350 5.200 to 250
Choose your mark range:3
Your rank is FIRST class and you are passing with C Grade
CONGRATULATIONS!!!
Best wishes!!!
Continue statement
1
2
3
4

6
7
8
9
10
End program

Result:
Thus a C program using decision-making constructs: if-else, goto, switch-case, break-
continue is executed successfully.

10
VIVA QUESTION

1.What is Decision Making Statement in C?


Decision-making statements decide the direction and the flow of the program. They are
also known as conditional statements because they specify conditions with boolean expressions
evaluated to a true or false boolean value.

2. Types of Conditional Statements in C/C++


 If in C/C++
 If-else in C/C++
 if-else-if ladder in C/C++
 Nested if in C/C++
 Switch in C/C++
 Conditional Operator in C/C++
 Jump Statements in C/C++

3. Write Syntax of if Statement

if(condition)
{
// Statements to execute if
// condition is true
}

4. Write Syntax of Conditional Operator

(condition) ? [true_statements] : [false_statements];

5. Write a for loop to print from 10 to 1.


Ans: for(i=10;i>0;i--)
printf(“%d”,i);

11
Ex. No:3 Loops: for, while, do-while

Aim:
To write a C program using loops: for, while, do-while

Algorithm:
1. Start the program.
2. Declare the variables and read the values.
3. Perform check candidates age by using for, while and do-while.
4. Display the result and greetings.
5. End the program.

Program:
#include<stdio.h>
int main()
{
int i,n,s;
char name[20];
printf("\n\tVOTER'S AGE VALIDATION\n");
printf("\nEnter no of Canditates:");
scanf("%d",&s);
for(i=0;i<s;i++)
{
printf("\nEnter Candidate Name:");
scanf("%s",&name);
printf("\nEnter Candidate Age:");
scanf("%d",&n);
do
{
if(n>=18)
printf("\nYou are ELIGIBLE for voting\n\n");
break;

12
}while(n>=18);
while(n<18)
{
printf("\nYou are NOT ELIGIBLE for voting\n\n");
break;
}
}
printf("\nBETTER LUCK NEXT TIME!!!\n");
return 0;
}

Output:
VOTER'S AGE VALIDATION
Enter no of Candidates:2
Enter Candidate Name: Vinitha
Enter your Age: 23
You are ELIGIBLEfor voting
Enter Candidate Name: Sharumitha
Enter Candidate Age:14
You are NOT ELIGIBLE for voting
BETTER LUCK NEXT TIME!!!

Result:
Thus a C program using Loops: for, while, do-while is executed successfully.
13
VIVA QUESTION

1. Difference between For ,While and Do-While Loop in Programming.


A For loop is used when the number of iterations is known. A While loop runs as long as a
condition is true. A Do-While loop runs at least once and then continues if a condition is true.

2. What is the Need for Looping Statements in C?

 Loops allow the user to execute the same set of statements repeatedly without writing the
same code multiple times.
 It saves time and effort and increases the efficiency.
 It reduces the chance of getting errors during compilation.

3. Write The syntax of a while loop is straightforward?


while (condition){
# Code to be executed while the condition is true
}

4. Write Syntax of do…while Loop?


do {

// body of do-while loop

} while (condition);

5. Differentiate break and continue statement.

Ans: break statement leads to an immediate exit of the innermost switch or enclosing loop. On the
other hand, the continue statement begins the next iteration of the while, enclosing for, or do loop.

14
Ex. No:4a Arrays: 1D and 2D

Aim:
To write a C program using arrays: 1D and 2D

Algorithm:
1. Start the program.
2. Declare the variables and read the values.
3. Read the elements from the matrices.
4. Write elements into matrices using 1D and 2D of Array.
5. Display the result.
6. End the program.

Program:
#include<stdio.h>
#include<conio.h>
int main()
{
int a[5],i;
printf("Enter 5 elements into an array:\n");
for(i=0;i<=4;i++)
{
scanf("%d",&a[i]);
}
printf("The 5 elements are:\n");
for(i=0;i<=4;i++)
printf("%d\n",a[i]);
{
int a[2][2],i,j;
printf("Enter 4 elements into array:");
for(i=0;i<=1;i++)

15
{
for(j=0;j<=1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("The 4 elements are:\n\t");
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n\t");
}
}
getch();
}

Output:

Enter 5 elements into array:

35

23

16
45

67

11

The 5 elements are:

35

23

45

67

11

Enter 4 elements into array:

The 4 elements are:

6 3

2 1

Result:
Thus a C program using arrays: 1D and 2D is executed successfully.
17
VIVA QUESTION

1.What is ARRAY?
Array is a data structure that is used to store variables that are of similar data types
at contiguous locations. The main advantage of the array is random access and cache friendliness.

2. What are types of Array?


There are mainly three types of the array:
 One Dimensional (1D) Array
 Two Dimension (2D) Array
 Multidimensional Array

3. Explain Applications of Arrays:


 2D Arrays are used to implement matrices.
 Arrays can be used to implement various data structures like a heap, stack, queue, etc.
 They allow random access.
 They are cache-friendly.

4. Difference Between one-dimensional and two-dimensional array.

Basis One Dimension Array Two Dimension Array

Store a single list of the Store a ‘list of lists’ of the element of a


Definition
element of a similar data type. similar data type.

Represent multiple data items Represent multiple data items as a table


Representation
as a list. consisting of rows and columns.

18
Ex. No:4b Arrays: Multi-dimensional arrays, traversal

Aim:
To write a C program using arrays: Multi-dimensional arrays, traversal

Algorithm:
1. Start the program.
2. Declare the variables and read the values of first and second matrices.
3. Read the elements from the matrices.
4. Add the two matrices of rows and columns present in the array using Multi dimensional.
5. Declare another variable and values using Traversal.
6. Display the result.
7. End the program.

Program:
#include<stdio.h>
int main()
{
int a[10][10],b[10][10],i,j,m,n,p,q;
printf("Enter the rows and columns of first Matrix\n");
scanf("%d%d",&m,&n);
printf("Enter the rows and columns of second Matrix\n");
scanf("%d%d",&p,&q);
if(m==p&&n==q)
{
printf("Enter the first Matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the second Matrix\n");
for(i=0;i<p;i++)
{
19
for(j=0;j<q;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("\n Sum of the Matrices are:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%8d",a[i][j]+b[i][j]);
}
printf("\n");
}

printf("\n Differences of the Matrices are:\n");


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%8d",a[i][j]-b[i][j]);
}

printf("\n");
}
int i,size;
int arr[]={1,-9,17,4,-3};
size=sizeof(arr)/sizeof(arr[0]);
printf("The array elements are:");
for(i=0;i<size;i++)
{
printf("\narr[%d]=%d",i,arr[i]);
}
}
else
20
printf("\n Operations are not possible....");
return 0;
}

Output:
Enter the rows and columns of first Matrix
2
2
Enter the rows and columns of second Matrix
2
2
Enter the first Matrix
1
2
3
4
Enter the second Matrix
5
6
7
8
Sum of the Matrices are:
6 8
10 12
Differences of the Matrices are:
-4 -4
-4 -4
The array elements are:
arr[0]=1
arr[1]=-9
arr[2]=17
arr[3]=4
arr[4]=-3

Output:
Enter the rows and columns of first Matrix
21
2
3
Enter the rows and columns of second Matrix
2
2
Operations are not possible....

Result:
Thus a C program using arrays: Multi-dimensional arrays, traversal is executed
successfully.

22
VIVA QUESTION

1.Multidimensional Arrays in C – 2D and 3D Arrays.


A multi-dimensional array can be defined as an array that has more than one
dimension.
2. Syntax of Multidimensional Arrays in C – 2D and 3D Arrays.
The general form of declaring N-dimensional arrays is shown below:
type arr_name[size1][size2]….[sizeN];
 type: Type of data to be stored in the array.
 arr_name: Name assigned to the array.
 size1, size2,…, sizeN: Size of each dimension.

3. Examples of 2D & 3D Array.


 Two-dimensional array: int two_d[10][20];
 Three-dimensional array: int three_d[10][20][30];

4. Size of Multidimensional Arrays.


The total number of elements that can be stored in a multidimensional array can be
calculated by multiplying the size of both dimensions.
Consider the array arr[10][20]:
The array int arr[10][20] can store total of (10*20) = 200 elements.

5. Declaration of 3D Array in C.
We can declare a 3D array with x 2D arrays each having m rows and n columns using the
syntax shown below:
type arr_name[x][m][n];
 type: Type of data to be stored in each element.
 arr_name: name of the array
 x: Number of 2D arrays. (also called depth of the array)
 m: Number of rows in each 2D array.
 n: Number of columns in each 2D array.

23
Ex. No:5 Strings: operations

Aim:
To write a C program using Strings: operations

Algorithm:
1. Start the program.
2. Declare the variables.
3. Read the two strings and Perform string operations.
4. Display the result.
5. End the program.

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char s1[25],s2[25],s3[25];
int l;
printf("\n\t\tString operations in C language are\n");
printf("\nEnter the first string:");
scanf("%s",&s1);
printf("\nEnter the second string:");
scanf("%s",&s2);
printf("\nString operations strat");
l=strlen(s1);
printf("\nLength of the first string is:%d",l);
strcat(s1,s2);
printf("\nConcatenation of the string is:%s",s1);
printf("\nString comparison:");
if(strcmp(s1,s2)==0)
{
24
printf("string 1 and string 2 are same.");
}
else
{
printf("String 1 and string 2 are different.");
}
strcpy(s3,s2);
printf("\nCopied string :String 3 is %s",s3);
return 0;
}
Output:
String operations in C language are
Enter the first string:Hello
Enter the second string:Sharumitha
String operations start
Length of the first string is:5
Concatenation of the string is:HelloSharumitha
String comparison :String 1 and string 2 are different
Copied string: string 3 is Sharumitha

Result:
Thus a C program using Strings: operations are executed successfully.

25
VIVA QUESTION

1. What are C String Functions?

C also has many useful string functions, which can be used to perform certain operations
on strings.To use them, you must include the <string.h> header file in your program:

#include <string.h>

2. Explain C String Initialization?


A string in C can be initialized in different ways. We will explain this with the help of
an example.
We can initialize a C string in 4 different ways which are as follows:
 Assigning a String Literal without Size
 Assigning a String Literal with a Predefined Size
 Assigning Character by Character with Size
 Assigning Character by Character without Size

3. Some C String Functions.

There are many important string functions defined in "string.h" library.

No. Function Description

1) strlen(string_name) returns the length of string name.

copies the contents of source string to


2) strcpy(destination, source)
destination string.

concats or joins first string with second


3) strcat(first_string, second_string) string. The result of the string is stored in
first string.

strcmp(first_string, compares the first string with second string.


4)
second_string) If both strings are same, it returns 0.

26
5) strrev(string) returns reverse string.

6) strlwr(string) returns string characters in lowercase.

7) strupr(string) returns string characters in uppercase.

4. How to Read a String Separated by Whitespaces in C?


We can use multiple methods to read a string separated by spaces in C. The two of the
common ones are:
 We can use the fgets() function to read a line of string and gets() to read characters from
the standard input (stdin) and store them as a C string until a newline character or
the End-of-file (EOF) is reached.
 We can also scanset characters inside the scanf() function

5. Declare a float array of size 5 and assign 5 values to it .


Ans: Declaration : float price[5];
Initialization : float price[5]={200.50,150.25,25.5,55.75,40.00}; (or)
float price[]={1.2,3.4,6.5,7.8,9.8};

27
Ex. No:6a Functions: call, return, passing parameters by
(value, reference)

Aim:
To write a C program using Functions: call, return, passing parameters by (value,
reference)

Algorithm:
1. Start the program.
2. Declare the variables.
3. Define the user defined function as change by value and change by reference.
4. Display the result.
5. End the program.

Program:
#include<stdio.h>
void chan_by_val(int x)
{
printf("Before adding value inside function num=%d\n",x);
x+=100;
printf("After adding value inside function num=%d\n",x);
}
void chan_by_ref(int *x)
{
printf("Before adding value inside function num=%d\n",*x);
*x+=100;
printf("After adding value inside function num=%d\n",*x);
}
int main()
{
int x=100;
printf("\n\t\tPassing by Value");
printf("\nBefore function call x=%d\n",x);
chan_by_val(x);
printf("After function call x=%d\n",x);
printf("\n\t\tPassing by Reference");
28
printf("\nBefore function call x=%d\n",x);
chan_by_ref(&x);
printf("After function call x=%d\n",x);
return 0;
}

Output:
Passing by Value
Before function call x=100
Before adding value inside function num=100
After adding value inside function num =200
After function call x=100
Passing by Reference
Before function call x=100
Before adding value inside function num=100
After adding value inside function num =200
After function call x=200

Result:
Thus a C program using Functions: call, return, passing parameters by (value,
reference)are executed successfully.

29
VIVA QUESTION
1. What is a function?
 Function is a set of instructions
 Self contained block
 Performs a specific task
 Used to avoid redundancy of code

2. What is the need for functions?


 To reduce the complexity of large programs

 To increase the readability


 To achieve reusability
 To avoid redundancy of code
 To save Memory

3. What is a function prototype?


Function prototype is a function declaration statement.
Syntax : return_type function_name( parameters_list)
Example: int factorial(int);

4. What are the steps in writing a function in a program?


Function Declaration (Prototype declaration): Every user-defined functions has to be
declared before the main().
Function Callings: The user-defined functions can be called inside any functions like main(),
userdefined function, etc.
Function Definition: The function definition block is used to define the user-defined functions
with statements.

5. What is meant by Recursive function?


If a function calls itself again and again, then that function is called Recursive function.
Example:
void recursion()
{
recursion(); /* function calls itself */
}
int main()
{
recursion();}
30
Ex. No:6b Passing arrays to function
Aim:
To write a C program using Passing arrays to function.

Algorithm:
1. Start the program.
2. Define (or) declare the user defined function and goto step3.
3. Display the function result and goto step6.
4. Declare the variables.
5. Call the user defined function and goto step2
6. Display the result.
7. End the program.

Program:
#include<stdio.h>
void display(int age1,int age2)
{
printf("%d\n",age1);
printf("%d\n",age2);
}
int main()
{
int age_array[]={2,3,7,5,6};
display(age_array[1],age_array[2]);
return 0;
}

Output:

Result:
Thus a C program using Passing arrays to function are executed successfully.

31
VIVA QUESTION
1. Define Array.
Ans:Array is a collection of similar type of values All values are stored in continuous memory
locations All values share a common name Linear data structure. The elements are organized in
a sequential order.

2. Name any two library functions for handling string.


Ans: strlen() – finds the length of a string. It returns an integer value. It counts the no. of
characters except null character & returns the count strlen(str).
strcpy() – copies the source string into destination string. So, the source string should be enough
to store the destination string. strcpy(source,destination)

3. Declare a float array of size 5 and assign 5 values to it .


Ans: Declaration : float price[5];
Initialization : float price[5]={200.50,150.25,25.5,55.75,40.00}; (or)
float price[]={1.2,3.4,6.5,7.8,9.8};

4. Give an example for initialization of string array.


Ans:String is a character array. Collection of one or more characters- enclosed with in double
quotes Declaration : char name[10]; Initialization : char name[10]=‖India‖; car
name[10]={‗I‘,‘n‘,‘d‘,‘i‘,‘a‘}; The char array is terminated by ‗\0‘.

5. How a character array is is declared.


Ans:Declaration : char name[n]; This array can store n-1 characters.
Initialization : char name[10]=”India”;
car name[10]={‘I‘,‘n‘,‘d‘,‘i‘,‘a‘};
The char array is terminated by ‗\0‘.

32
Ex. No:7 Recursion

Aim:
To write a C program using Recursion.

Algorithm:
1. Start the program.
2. Read the values.
3. Declare the variables,sum=0.
4. sum = sum+ x,n-=1.
5. Display the result.
6. End the program.

Program:

#include<stdio.h>
int sumOfRange(int);
int main()
{
int n1;
int sum;
printf("\n\nRecursion:Calculate the sum of numbers from 1 to n:\n");
printf("Input the last number of the range starting from 1:");
scanf("%d", &n1);
sum=sumOfRange(n1);
printf("\nThe sum of numbers from 1 to %d:%d\n\n",n1,sum);
return 0;
}
int sumOfRange(int n1)
{
int res;
if(n1==1)
{
return 1;
}
33
else
{
res=n1+sumOfRange(n1-1);
}
return res;
}

Output:

Recursion: Calculate the sum of numbers from 1 to n:


Input the last number of the range starting from 1:7

The sum of numbers from 1 to 7:28

Result:
Thus a C program using Recursion are executed successfully.

34
VIVA QUESTION
1.What is meant by Recursive function?
Ans: If a function calls itself again and again, then that function is called Recursive function.

2. syntax structure of the recursive functions is:


type function_name (args) {
// function statements
// base condition
// recursion case (recursive call)
}

3. How Recursion works in C?


Recursion is considered difficult to understand by many people but once you
understand the working of recursion, it becomes a powerful weapon in your arsenal to battle
complex problems.
In the nSum() function, Recursive Case is
int res = n + nSum(n - 1);

In the example, n = 5, so as nSum(5)’s recursive case, we get


int res = 5 + nSum(4);

4. Applications of Recursion in C.
Recursion is widely used to solve different kinds of problems from simple ones like
printing linked lists to being extensively used in AI. Some of the common uses of recursion
are:
 Tree-Graph Algorithms
 Mathematical Problems
 Divide and Conquer
 Dynamic Programming
 In Postfix to Infix Conversion
 Searching and Sorting Algorithms

35
5. What is the difference between iteration and recursion in C?

Answer:
The following table lists the differences between recursion and iteration.

Property Iteration Recursion

A set of instructions
Definition Function calls itself.
repeatedly executed.

When the termination


Through base case, where
Termination condition for the iterator
there will be no function call.
ceases to be satisfied.

Used when code size needs Used when time complexity


Usage to be small, and time needs to be balanced against
complexity is not an issue. an expanded code size.

Very high(generally Relatively lower time


Time Copmlexity exponential) time complexity(generally
complexity. polynomial-logarithmic).

The space complexity is


Space Complexity Space complexity is lower.
higher than iterations.

36
Ex. No:8 Pointers: Pointers to functions, Arrays, Strings, Pointers to
Pointer, Array of Pointers

Aim:
To write a C program using Pointers: Pointers to functions, Arrays, Strings, Pointers to
Pointers, Array of Pointers.

Algorithm:

1. Start the program.


2. Define user defined function and perform the function statement and goto step 9.
3. Declare all variable and pointer variables.
4. First perform pointer to string and display the result
5. Next perform pointer to array using for loop and display the result
6. Next perform pointer to pointer display the result
7. Next perform array of pointer and display the result
8. Next perform pointer to function and goto step 2
9. End the program.

Program:

#include<stdio.h>
#include<conio.h>
#include<string.h>
int addOne(int *ptr)
{
(*ptr)++;
return *ptr;
}
int main()
{
char p[20]="POINTER";
int(*a)[5];
int b[5] = { 1, 2, 3, 4, 5 };

37
int i = 0;
char *p1;
int n=45;
int *ptr,**pptr,x,*s;
int var[]={1000,2000,3000};
int *parr[3]={var};
p1=strdup(p);
printf("\nPointer to string:");
printf("%s\n",p1);
ptr=&n;
pptr= &ptr;
a = &b;
printf("\nPointer to array:\n");
for (i = 0; i < 5; i++)
{
printf("%d\n", *(*a + i));
}
printf("\nPointer to pointer:\n");
printf("Value of var=%d\n",n);
printf("Value available at *ptr=%d\n",*ptr);
printf("Value available at **pptr=%d\n",**pptr);
for(x=0;x<1;x++)
{

printf("\nArray of pointer:");
printf("\nValue of Array[%d]=%d",x,*parr[x]);
}
i=10;
s=&i;
addOne(s);
printf("\n\nPointer to function:");
printf("\n%d",*s);
return 0;
}

38
Output:

Pointer to string:POINTER

Pointer to array:
1
2
3
4
5

Pointer to pointer:
Value of var=45
Value available at *ptr=45
Value available at **pptr=45

Array of pointer:
Value of Array[0]=1000

Pointer to function:
11

Result:
Thus a C program using Pointers: Pointers to functions, Arrays, Strings, Pointers to
Pointers, Array of Pointers are executed successfully.
39
VIVA QUESTION
1. Write the syntax for pointers to structure.
Ans:
Struct S
{
char datatype1;
int datatype2;
float datatype3;
}; Struct S *sptr; //sptr is a pointer to structure S

2. Syntax to Create an Array of Pointers to Strings in C.

To create an array of pointers to strings in C we can use the following syntax:


char * arr[size] ={ "String1", "String2", ....}
Here,
 char*: is the type of pointers we will store in the array.
 arr: is the name of the array of pointers.
 size: is the size of the array of pointers.

3. What are the uses of pointer?


 Saves Memory Space
 Used for dynamic memory allocation
 Faster execution
 Used to pass array of values to a function as a single argument

4.Write C program to sort an array using pointers.


Given an array of size n, the task is to sort this array using pointers in C.
Examples:
Input: n = 5, arr[] = {0, 23, 14, 12, 9}
Output: {0, 9, 12, 14, 23}

5. What are the various dynamic memory allocation functions?


 malloc() - Used to allocate blocks of memory in required size of bytes.
 free () - Used to release previously allocated memory space.
 calloc() - Used to allocate memory space for an array of elements.

40
Ex.No 9a PROGRAM TO STORE STUDENT INFORMATION IN
STRUCTURE AND DISPLAY IT

AIM:
To store student information in structure and display it
ALGORITHM:
Step 1: START
Step 2: Read student details like name, mark1,2,3
Step 3: Calculate total, and average
Step 4: Display the grade Step
5: STOP
PROGRAM:
#include<stdio.h> struct student
{
int roll_no, mark1, mark2, mark3, total; float average;
char name[10],grade;
};
void struct_funct_student(struct student stu);
int main()
{
struct student stud;
printf("\nRoll No.=");
scanf("%d",&stud.roll_no);
printf("Name=");
scanf("%s",stud.name);
printf("Mark1=");
scanf("%d",&stud.mark1);
printf("Mark2=");
scanf("%d",&stud.mark2);
printf("Mark3=");
canf("%d",&stud.mark3);
struct_funct_student(stud);

41
return 0;
}
void struct_funct_student( struct student stu)
{
stu.total = stu.mark1 + stu.mark2 + stu.mark3;
stu.average = stu.total / 3;
if(stu.average >= 90) stu.grade='S';
else if(stu.average >= 80) stu.grade='A';
else if(stu.average >= 70) stu.grade='B';
else if(stu.average >= 60) stu.grade='C';
else if(stu.average >= 50) stu.grade='D';
else stu.grade='F';
printf("\n ROLL NO. \t NAME \t TOTAL \t AVG \t GRADE \n");
printf("%d \t %s \t %d \t %f \t %c", stu.roll_no,stu.name,stu.total,stu.average,stu.grade);
}

OUTPUT:

Roll No.= 1
Name= a
Mark1= 95
Mark2= 94
Mark3= 96

ROLL NAME TOTAL AVG GRADE


NO.
1 a 285 95.000000 S

RESULT:
Thus the C Program to store and display student details using structures has been executed and the
result was verified.
42
VIVA QUESTION
1.Compare arrays and structures.
Comparison of arrays and structures is as follows.
Arrays Structures
An array is a collection of data items of same A structure is a collection of data items of
data type. different data types.
Arrays can only be declared. Structures can be declared and defined.
There is no keyword for arrays. The keyword for structures is struct.
An array cannot have bit fields. A structure may contain bit fields.

2.Compare structures and unions.

Structure Union
Every member has its own memory. All members use the same memory.
The keyword used is struct. The keyword used is union.
Consumes more space compared to union. Conservation of memory is possible

3. What are storage classes?


A storage class defines the scope (visibility) and life time of variables and/or functions within a C
Program.

4.What are the storage classes available in C?


There are following storage classes which can be used in a C Program
1. auto
2. register
3. static
4. extern

5.Write the syntax for pointers to structure.


Struct S
{
char datatype1;
int datatype2;
float datatype3;
}; Struct S *sptr; //sptr is a pointer to structure S

43
Ex.No 9b Program To Read The Student Data And Calculate The Total Marks

AIM:
To read the student data and calculate the total marks

ALGORITHM:
Step 1: Start the program
Step 2: Get the details of the 10 students in five subjects
Step 3: Calculate the total marks of each student
Step 4 : Calculate the student who got the highest total marks Step
5: Display the results
Step 6: Stop the Program

PROGRAM:
#include<stdio.h>
struct student
{
int sub1;
int sub2;
int sub3;
int sub4;
int sub5;
};
void main()
{
struct student s[10];
int i,total=0;
clrscr(); for(i=0;i<=9;i++)
{
printf("\nEnter Marks in Five Subjects = ");
scanf("%d%d%d",& s[i].sub1,&s[i].sub2,&s[i].sub3,&s[i].sub4,&s[i].sub5);
total=s[i].sub1+s[i].sub2+s[i].sub3+s[i].sub4+s[i].sub5;
printf("\nTotal marks of s[%d] Student= %d",i,total);
}
getch();

44
}

OUTPUT:
Enter Marks in Five Subjects 80 70 90 80 98
Total Marks of 1 student = 83.6

RESULT:
Thus the C Program to print the student details has been executed and the result was verified.

45
VIVA QUESTION
1.Define C Structure Declaration.
We have to declare structure in C before using it in our program. In structure declaration, we
specify its member variables along with their datatype. We can use the struct keyword to declare the
structure in C using the following syntax:
Syntax

struct structure_name {

data_type member_name1;

data_type member_name1;

};

2. What are typedef for Structures?


The typedef keyword is used to define an alias for the already existing datatype. In structures,
we have to use the struct keyword along with the structure name to define the variables. Sometimes,
this increases the length and complexity of the code. We can use the typedef to define some new
shorter name for the structure.

3. Uses of Structure in C.
C structures are used for the following:
 The structure can be used to define the custom data types that can be used to create some
complex data types such as dates, time, complex numbers, etc. which are not present in the
language.
 It can also be used in data organization where a large amount of data can be stored in different
fields.
 Structures are used to create data structures such as trees, linked lists, etc.
 They can also be used for returning multiple values from a function.

4. Limitations of C Structures.
In C language, structures provide a method for packing together data of different types. A
Structure is a helpful tool to handle a group of logically related data items. However, C structures
also have some limitations.

46
 Higher Memory Consumption: It is due to structure padding.
 No Data Hiding: C Structures do not permit data hiding. Structure members can be accessed by
any function, anywhere in the scope of the structure.
 Functions inside Structure: C structures do not permit functions inside the structure so we
cannot provide the associated functions.
 Static Members: C Structure cannot have static members inside its body.
 Construction creation in Structure: Structures in C cannot have a constructor inside
Structures.

5. Structure Pointer in C.
We can define a pointer that points to the structure like any other variable. Such pointers are
generally called Structure Pointers. We can access the members of the structure pointed by the
structure pointer using the ( -> ) arrow operator.

47
Ex.No:10a Telephone Directory Using Random Access File

AIM :
To insert, update, delete and append telephone details of an individual or a company into a telephone
directory using random access file.

ALGORITHM :
Step 1: Create a random access file
Step 2: call the respective procedure to insert, update, delete or append based on user choice
Step 3: Access the random access file to make the necessary changes and save

PROGRAM
#include "stdio.h"
#include "string.h"
#include<stdlib.h>
#include<fcntl.h>
struct dir
{
char name[20];
char number[10];
};
void insert(FILE *);
void update(FILE *);
void del(FILE *);
void display(FILE *);
void search(FILE *);
int record = 0;
int main(void) {
int choice = 0;
FILE *fp = fopen( "telephone.dat", "rb+" );
if (fp == NULL ) perror ("Error opening file");
while (choice != 6)
{
printf("\n1 insert\t 2 update\n");
printf("3 delete\t 4 display\n");

48
printf("5 search\t 6 Exit\n Enter choice:");
scanf("%d", &choice);
switch(choice)
{
case 1: insert(fp); break;
case 2: update(fp); break;
case 3: del(fp); break;
case 4: display(fp); break;
case 5: search(fp); break;
default: ;
}
}
fclose(fp);
return 0;
}
void insert(FILE *fp)
{
struct dir contact, blank;
fseek( fp, -sizeof(struct dir), SEEK_END );
fread(&blank, sizeof(struct dir), 1, fp);
printf("Enter individual/company name: ");
scanf("%s", contact.name);
printf("Enter telephone number: ");
scanf("%s", contact.number);
fwrite(&contact, sizeof(struct dir), 1, fp);
}
void update(FILE *fp)
{
char name[20], number[10];
int result;
struct dir contact, blank;
printf("Enter name:");
scanf("%s", name);
rewind(fp);
while(!feof(fp))
{
49
result = fread(&contact, sizeof(struct dir), 1, fp);
if(result != 0 && strcmp(name, contact.name) == 0)
{
printf("Enter number:");
scanf("%s", number);
strcpy(contact.number, number);
fseek(fp, -sizeof(struct dir), SEEK_CUR);
fwrite(&contact, sizeof(struct dir), 1, fp);
printf("Updated successfully\n");
return;
}
}
printf("Record not found\n");
}
void del(FILE *fp)
{
char name[20], number[10];
int result, record=0;
struct dir contact, blank = {"", ""};
printf("Enter name:");
scanf("%s", name);
rewind(fp);
while(!feof(fp))
{
result = fread(&contact, sizeof(struct dir), 1, fp);
if(result != 0 && strcmp(name, contact.name) == 0)
{
fseek(fp, record*sizeof(struct dir), SEEK_SET);
fwrite(&blank, sizeof(struct dir), 1, fp);
printf("%d Deleted successfully\n", record-1);
return;
}
record++;
}
printf("not found in %d records\n", record);
}
50
void display(FILE *fp)
{
struct dir contact;
int result;
rewind(fp);
printf("\n\n Telephone directory\n");
printf("%20s %10s\n", "Name", "Number");
printf("*******************************\n");
while(!feof(fp))
{
result = fread(&contact, sizeof(struct dir), 1, fp);
if(result != 0 && strlen(contact.name) > 0)
printf("%20s %10s\n",contact.name, contact.number);
}
printf("*******************************\n");
}
void search(FILE *fp)
{
struct dir contact;
int result; char name[20];
rewind(fp);
printf("\nEnter name:");
scanf("%s", name);
while(!feof(fp))
{
result = fread(&contact, sizeof(struct dir), 1, fp);
if(result != 0 && strcmp(contact.name, name) == 0)
{
printf("\n%20s %10s\n",contact.name, contact.number);
return;
}
}
printf("Record not found\n");
}

51
OUTPUT:
1 insert 2 update
3 delete 4 display
5 search 6 Exit
Enter choice: 4
Telephone directory
Name Number
*******************************
bb 11111
*******************************
1 insert 2 update
3 delete 4 display
5 search 6 Exit
Enter choice: 5
Enter name: bb
bb 11111
1 insert 2 update
3 delete 4 display
5 search 6 Exit
Enter choice: 1
Enter individual/company name: aa
Enter telephone number: 222222
1 insert 2 update
3 delete 4 display
5 search 6 Exit
Enter choice: 2
Enter name: aa
Enter number: 333333
Updated successfully
1 insert 2 update
3 delete 4 display
5 search 6 Exit
Enter choice:
Telephone directory
Name Number
52
*******************************
bb 11111
aa 333333
*******************************
1 insert 2 update
3 delete 4 display
5 search 6 Exit
Enter choice: 3
Enter name: aa
1 Deleted successfully
1 insert 2 update
3 delete 4 display
5 search 6 Exit

RESULT:
Thus the C Program to print insert, update, delete and append telephone using random access file has
been executed and the result was verified.

53
VIVA QUESTION
1. Why files are needed?
 When a program is terminated, the entire data is lost. Storing in a file will preserve your
data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of the
file using few commands in C.
 You can easily move your data from one computer to another without any changes.

2. Write Types of Files .


Ans:When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files

3. Enlist the File Operations.


Ans: In C, you can perform four major operations on the file, either text or binary:
1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file
Working with files
When working with files, you need to declare a pointer of type file. This declaration is needed for
communication between the file and program.
FILE *fptr;

4. How to open a file?


Ans: Opening a file is performed using the library function in the "stdio.h" header file: fopen().
The syntax for opening a file in standard I/O is: ptr = fopen("fileopen","mode")

5. How to close a file?


Ans:The file (both text and binary) should be closed after reading/writing. Closing a file is performed
using library function fclose(). fclose(fptr); //fptr is the file pointer associated with file to be closed.
Reading and writing to a text file
For reading and writing to a text file, we use the functions fprintf() and fscanf(). They are just the file
versions of printf() and scanf(). The only difference is that, fprint and fscanf expects a pointer to the
structure FILE.
54
Ex.No 10b Program to Count the Number of Account Holders Whose Balance is
less than the Minimum Balance using Sequential Access File

AIM:
To count the number of account holders whose balance is less than the minimum
balance using sequential access file.

ALGORITHM :
Step 1 : Start the program
Step 2 : Read choice to insert records & count minimum balance account
1. If choice is 1, then
 Open a dat file in write mode

 Read the No. of records

 Write the records into the file using fprintf() function

 Close the file

2. If Choice is 2, then
 Open the file in Read mode

 Read the records one by one using fscanf(0 function until reach the end of file.

 Check the account balance with min bal.

 If account balance is less than min balance, then display the account details

 Close the file Step

3 : Stop the program

PROGRAM:
#include <stdio.h> void insert();
void count();
int main(void)
{
int choice = 0; while (choice != 3)
{
printf("\n1 insert records\n");

55
printf("2 Count min balance holders\n");
printf("3 Exit\n");
printf("Enter choice:");
scanf("%d", &choice);
switch(choice)
{
case 1: insert(); break; case 2: count(); break;
}
}
}
void insert()
{
unsigned int account,i; char name[30];
double balance; FILE* cfPtr;
if ((cfPtr = fopen("clients.dat", "w")) == NULL) { puts("File could not be opened");
}
else {
int records,i=0;
printf("Enter the No. of records "); scanf("%d", &records);
while (i<records)
{
printf("Enter the account, name, and balance."); scanf("%d%29s%lf", &account, name, &balance);
fprintf(cfPtr, "%d %s %.2f\n", account, name, balance); i++;
}
fclose(cfPtr);
}
}
void count()
{
unsigned int account; char name[30]; double balance;
float minBal = 5000.00; int count = 0;
FILE *cfPtr;
if ((cfPtr = fopen("clients.dat", "r")) == NULL) printf("File could not be opened");
else
{

56
printf("%-10s%-13s%s\n", "Account", "Name", "Balance"); fscanf(cfPtr, "%d%29s%lf", &account,
name, &balance);
while (!feof(cfPtr))
{
if (balance < minBal)
{
printf("%-10d%-13s%7.2f\n", account, name, balance); count++;
}
fscanf(cfPtr, "%d%29s%lf", &account, name, &balance);
}
fclose(cfPtr);
printf("The number of account holders whose balance is less than the minimum balance:
%d", count);
}
}
OUTPUT:
1 insert records

2 Count min balance holders


3 Exit

Enter choice:1
Enter the No. of records 2
Enter the account, name, and balance.1001 A 10000
Enter the account, name, and balance.1002 B 300
1 insert records

2 Count min balance holders


3 Exit

Enter choice:2
Account Name Balance
1002 B 300.00
The number of account holders whose balance is less than the minimum balance: 1
1 insert records
2 Count min balance holders
3 Exit

57
RESULT :
Thus the C Program to count the number of account holders whose balance is less than the minimum
balance using sequential access file

58
VIVA QUESTION
1.What are two main ways a file can be organized?
Ans: i. Sequential Access — The data are placed in the file in a sequence like beads on a string.
Data are processed in sequence, one after another. To reach a particular item of data, all the data
that proceeds it first must be read.
ii. Random Access — The data are placed into the file by going directly to the location in the file
assigned to each data item. Data are processed in any order. A particular item of data can be
reached by going directly to it, without looking at any other data.

2.What is file?
Ans: A file is a semi-permanent, named collection of data. A File is usually stored on magnetic
media, such as a hard disk or magnetic tape.
Semi-permanent means that data saved in files stays safe until it is deleted or modified. Named
means that a particular collection of data on a disk has a name, like mydata.dat and access to the
collection is done by using its name.

3.Write the functions for random access file processing.


Ans:1. fseek()
2.ftell()
3. rewind()

4.Write short notes on fwrite().


Ans: This function is used for writing an entire block to a given file.
Syntax: fwrite( ptr, size, nst, fptr);
Where ptr is a pointer which points to the arrayof struture in which data is written. Size is the size
of the structure nst is the number of the structure fptr is a filepointer.

5. What are the storage classes available in C?


Ans:There are following storage classes which can be used in a C Program
1. auto
2. register
3. static
4. extern

59
ST. JOSEPH’S COLLEGE OF ENGINEERING & Format No.
ACD-
TECHNOLOGY CF-CBL
Elupatti, Thanjavur – 613 403 Issue No. 01
CONTENT BEYOND EXPERIMENT Rev. No. 00

Sub Code/Name : CS3271/Programming in C


Course Instructor : Ms. R. Jayashree
Year/Sem/Sec : I/II
IMPLEMENTATION OF LINEAR AND BINARY SEARCH

AIM:
To write a C program to perform linear search and binary search
ALGORITHM:
Linear Search
1.Read n numbers and search value.
2.If search value is equal to first element then print value is found.
3.Else search with the second element and so on.
Binary Search
1.Read n numbers and search value.
2.If search value is equal to middle element then print value is found.
3.If search value is less than middle element then search left half of list with the same
method.
4.Else search right half of list with the same method.

PROGRAM:
# include <stdio.h>
# include <stdlib.h>
# include <conio.h>
void main()
{
int a[100],i,n,item,s=0,ch,beg,end,mid; clrscr();
printf("Enter No. of Elements:");
scanf("%d",&n);
printf("\nEnter Elements:\n");
for(i=1;i<=n;i++)

60
{ scanf("%d",&a[i]); }
while(1)
{
printf("\n1.Linear Search\n2.Binary Search\n3.Exit\n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("<-----LINEAR SEARCH----->\n");
printf("\nEnter Element you want to Search:");
scanf("%d",&item);
for(i=1;i<=n;i++)
{
if(a[i]==item)
{ printf("\nData is Found at Location : %d",i); s=1;
break; }
}
if(s==0)
{ printf("Data is Not Found"); }
break;
case 2:
printf("<-----BINARY SEARCH----->\n");
printf("\nEnter Item you want to Search:");
scanf("%d",&item);
beg=1;
end=n;
mid=(beg+end)/2;
while(beg<=end && a[mid]!=item)
{
if(a[mid]<item)
beg=mid+1;
else end=mid-1;
mid=(beg+end)/2;
}
if(a[mid]==item)
61
{ printf("\nData is Found at Location : %d",mid); }
else
{ printf("Data is Not Found"); }
break;
case3:
default: exit(0); }
}
getch();
}

OUTPUT:

Enter No. of Elements: 5


Enter Elements: 2 4 3 5 1

1.Linear Search
2.Binary Search
3.Exit
Enter your choice: 1

<-----LINEAR SEARCH----->
Enter Element you want to Search: 1
Data is Found at Location : 5

1.Linear Search
2.Binary Search
3.Exit
Enter your choice: 2

<-----BINARY SEARCH----->
Enter Item you want to Search: 3
Data is Found at Location : 3
62
1.Linear Search
2.Binary Search
3.Exit
Enter your choice: 3

RESULT:
Thus a C program to implement the linear search and binary search is written and executed
successfully.

63
64

You might also like