C Programming Control Structures Guide
C Programming Control Structures Guide
CONTROL STRUCTURE
1
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
LOOPING STATEMENTS
While Do while
It is top tested loop It is bottom tested loop
The condition is first tested, if the condition It executes the body once, after it checks
is true then the block is executed until the the condition, if it is true the body is
condition becomes false. executed until the condition become false.
2
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
Loop will not be executed if the condition is Loop will be executed at least once even
false. though the condition is false.
8) What will be the outputs for the following program? when the value of i is 5 and
10?
Void main()
{
int i;
Scanf(“%d”,&i);
if(i=5)
{
Printf(“five”);
}
}
Output:
five (if i is 5)
No output if i is 10
9) Write a code segment using while statement to print numbers from 10 down to 1
-----
i=10;
while(i>=1)
{
Printf(“%d\n”,i);
i--;
}
-----
10) Write a C Program to print the number 10 ten times the number 9 nine times and
so on.
main()
{
int i,j,n=10;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(“%d\t”,n);
}
n--;
}
}
3
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
Feature if if-else
13) Write a for loop to calculate the sum of first 10 natural numbers.
#include <stdio.h>
int main() {
int sum = 0;
sum += i;
return 0;
JUMP STATEMENTS
[Link]
[Link]
[Link]
[Link]
4
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
Example:
if(i == 3) break;
printf("%d\n", i);
// Output: 1 2
continue skips the current iteration of the loop and moves to the next iteration.
Example:
if(i == 3) continue;
printf("%d\n", i);
// Output: 1 2 4 5
int main()
return 0;
5
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
// statements to be executed
Example:
printf("%d\n", i);
6
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
CONTROL STRUCTURE
1) What is purpose of Decision Control Statements in C? Explain any two of
such types with the general form of simple statements.
C has some kinds of statements that permit the execution of a single statement, or a
block of statements, based on the value of a conditional expression or selection among several
statements based on the value of a conditional expression or a control variable.
These are all the following conditional statements
(i) if statement
(ii) if-else statement
(iii) Nested if-else statement
(iv) if-else ladder (else if ladder)
(i) if statement:
It is otherwise known as One-way decisions. It is used to control the flow of
execution of the statements.
The decision is based on a ‘test expression or condition’ that evaluates to either true or
false.
If the test condition is true, the corresponding statement is executed.
If the test condition is false, control goes to the next executable statement.
Syntax: Flowchart
if(condition is true)
{
Statement 1;
------------
------------
Statement n;
}
Next Statement;
Program:
#include<stdio.h>
main()
{
int salary;
float bonus=0.0;
printf(“Enter salary=”);
scanf(“%d”,&salary);
if(salary>=25000)
7
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
{
bonus=salary*20/100;
}
printf(“Bonus=%f”,bonus);
}
Output 1:
Enter salary=27000
Bonus=5400.0
Output 2:
Enter salary=24000
Bonus=0.0
if(condition is true)
{
True block;
}
else
{
false block;
}
Next statement;
Program 1:
#include<stdio.h>
main()
{
int salary;
float bonus=0.0;
printf(“Enter salary=”);
scanf(“%d”,&salary);
if(salary>=25000)
8
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
{
bonus=salary*20/100;
}
else
{
bonus=salary*10/100;
}
printf(“Bonus=%f”,bonus);
}
Output 1:
Enter salary=27000
Bonus=5400.0
Output 2:
Enter salary=24000
Bonus=2400.0
Syntax: Flowchart
if(condition 1)
{
if(condition 2)
{
True statement 2
}
else
{
False statement 2;
}
}
else
{
False statement 1;
}
Next Statement;
9
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
{
int a b c;
printf(“Enter the value for A, B and C:”);
scanf(“%d%d%d”,&a,&b,&c);
if((a>b)&&(a>c))
{
printf(“A is largest”);
}
else
{
if(b>c)
{
printf(“B is largest”);
}
else
{
printf(“C is largest”);
}
}
}
Output:
Enter the value for A,B and C:12 13 5
B is largest
if(condition1)
statement 1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
--------
--------
else
default
statement;
10
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
Example:
--------
if(per >= 60)
printf(" You got 1st Class");
else if( per >= 45)
printf(" You got 2nd Class ");
else if(per>=27)
printf("\n You got 3rd Class ");
else
printf("\n NO Class ");
--------
--------
Feature if if-else
11
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
Example:
if(num > 0)
printf("Positive\n");
else
printf("Non-positive\n");
Output:
Non-positive
12
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
Syntax Flowchart
switch(expression)
{
case label1:
block 1;
break;
case label2:
block 2;
break;
……..
……..
default:
Default
block;
break;
}
Program:
#include<stdio.h>
main()
{
13
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
char c;
printf(“Choose any one from RGB”);
c=getchar();
switch(c)
{
case ‘R’:
printf(“Red Color \n”);
break;
case ‘G’:
printf(“Green Color \n”);
break;
case ‘B’:
printf(“Blue Color\n”);
break;
default:
printf(“Wrong in Input\n”);
break;
}
}
Output:
Choose any one from RGB
R
Red Color
LOOPING STATEMENT
4) What is the purpose of a looping statement? Explain in detail the
operation of various looping statements in c with suitable examples.
(OR)
Explain the looping statement in c with suitable examples.
Explain about the various looping statements available in ‘C’ with
appropriate sample programs.
A loop is defined as a block of statements which are repeatedly executed for certain
number of times. A loop can either be a “pre-test loop or be a post-test loop i.e. entry
controlled loop or exit controlled loop”.
Requirements for looping block:
Initialization of a counter variable
14
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
Syntax: Flowchart
while(condition)
{
….
Body of the loop;
….
}
….
Program:
main()
{
int i=1;
while(i<=10)
{
printf(“%d\t”,i);
i++;
}
15
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
}
Output:
1 2 3 4 5 6 7 8 9 10
Program:
#include<stdio.h>
main()
{
int i=1;
do
{
printf(“%d\t”,i);
i++;
}while(i<=10);
}
Output:
1 2 3 4 5 6 7 8 9 10
16
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
for(initialization;test condition;increment/[Link])
{
…
Body of loop;
….
}
Next statement;
Initialize counter:
o used to initialize counter variable
Test condition:
o used to test the condition.
Increment/decrement is used to increment/decrement the counter variable.
for() loop working manner
false
2
1
for(i=1;i<=10;i++)
{
true 3 4
printf(“%d”,i);
Program:
#include<stdio.h>
main()
{
int i=1,sum=0;
for(i=1;1<=10;i++)
{
17
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
sum=sum+i;
}
printf(“Answer is %d”,sum);
}
Output:
Answer is 55
18
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
Example: while
#include <stdio.h>
int main() {
int i = 6;
while (i <= 5) {
printf("Value of i: %d\n", i);
i++;
}
return 0;
}
19
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
Output:
Example: do-while
#include <stdio.h>
int main() {
int i = 6;
do {
printf("Value of i: %d\n", i);
i++;
} while (i <= 5);
return 0;
}
Output: Value of i: 6
Nested loop: A nested loop means placing one loop inside another. The outer loop
controls the number of rows, and the inner loop controls the number of columns or
characters printed per row.
Syntax:
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
// Inner loop logic
}
}
#include <stdio.h>
int main() {
int rows = 5;
return 0;
20
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
Output:
// *
// **
// ***
// ****
// *****
Program:
#include<stdio.h>
main()
{
int i;
for(i=1;i<=10;i++)
{
if(i==6)
break;
printf(“%d”,i);
}
}
Output:
12345
21
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
Syntax:
continue;
Program:
#include<stdio.h>
main()
{
int i,n,sum==0;
for(i=1;i<=5;i++)
{
print(“Enter any number…\n”);
scanf(“%d”,&n);
if(n<0)
continue;
else
sum=sum+n;
}
printf(“sum is…%d”,sum);
}
Output:
Enter any number…10
Enter any number…15
Enter any number…25
Enter any number…10
Enter any number…50
Sum is …100
22
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
Syntax:
goto label;
………
………
label:
label:
…….
…….
goto label;
Program:
#include<stdio.h>
main()
{
int a,b;
printf(“Enter the numbers”);
scanf(“%%d”,&a,&b);
if(a==b)
goto equal;
else
{
printf(“\n A and B are not equal”);
exit(0);
}
equal:
printf(“A and B are equal”);
23
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
}
Output:
1. Enter the numbers 3 3
A and B are equal
2. Enter the numbers 3 4
A and B are not equal
#include <stdio.h>
int main() {
if (i == 5) {
return 0;
Output: 1 2 3 4
ii) continue: Skips the current iteration and jumps to the next iteration of the loop.
#include <stdio.h>
int main() {
24
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
if (i == 3) {
return 0;
Output: 1 2 4 5
iii) goto: Transfers control to a labeled statement. Use with caution—it can make code
harder to read.
#include <stdio.h>
int main() {
int i = 1;
start:
if (i <= 5) {
printf("%d ", i);
i++;
goto start; // Jump back to label
}
return 0;
Output: 1 2 3 4 5
iv) return: Ends the execution of a function and optionally returns a value.
#include <stdio.h>
25
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II
int main() {
int result = add(3, 4);
printf("Sum: %d", result);
return 0;
}
Output: Sum: 7
Example:
#include <stdio.h>
int main() {
int num;
return 0;
}
Output:
7 x 1=7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
26
MAILAM ENGINEERING COLLEGE UNIT II CS25C01-COMPUTER PROGRAMMING IN C
#include <stdio.h>
#define MAX 100
int main()
{
int arr[MAX];
int i, n, sum=0;
return 0;
}
Output
Enter size of the array: 5
Enter 5 elements in the array:
10 12 1 14 13
Sum of all elements of array = 50
11) Find the output of the following C code. Discuss the steps of execution.
for (i=1,j=1;i<=10;++i, ++i)
{
if(i==3) {continue;}
else {
if(j==4) {break;}
else {
printf(“\I am in loop, the values of I and J are:%d,%d”,i,j)
}
}
} [AU – Dec 2023]
Output
I am in loop, the values of I and J are:1,1
I am in loop, the values of I and J are:5,1
I am in loop, the values of I and J are:7,1
I am in loop, the values of I and J are:9,1
MAILAM ENGINEERING COLLEGE UNIT II CS25C01-COMPUTER PROGRAMMING IN C
12) Write a C program to get age and vaccination detail as input. Print
"senior citizen and Eligible for Booster" if age>60 and vaccination input as
"2". Otherwise print "Below 60, and Eligible for Vaccination". Use conditional
operator.
#include <stdio.h>
main()
{
int age, vaccination;
printf("Enter your vaccination status (1 for vaccinated, 2 for booster shot): ");
scanf("%d", &vaccination);
(age > 60 && vaccination == 2) ? printf("Senior citizen and Eligible for Booster\n") :
printf("Below 60, and Eligible for Vaccination\n");
if (choice == 1)
{
printf("You chose Red.\n");
}
else if (choice == 2)
{
printf("You chose Green.\n");
}
else if (choice == 3)
{
printf("You chose Blue.\n");
}
else
{
printf("Invalid choice. Please choose 1, 2, or 3.\n");
}
}
Program for switch case:
#include <stdio.h>
main()
{
int choice;
{
case 1:
printf("You chose Red.\n");
break;
case 2:
printf("You chose Green.\n");
break;
case 3:
printf("You chose Blue.\n");
break;
default:
printf("Invalid choice. Please choose 1, 2, or 3.\n");
break;
}
}
14) Write a C program to check whether the person is eligible for voting
using if/else.
#include <stdio.h>
int main()
{
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 18)
{
printf("You are eligible to vote.\n");
}
else
{
printf("You are not eligible to vote.\n");
}
return 0;
}
15) Write a C program to print the grade of student using switch statement.
#include <stdio.h>
int main()
{
int marks;
printf("Enter your marks: ");
scanf("%d", &marks);
switch (marks / 10)
{
case 10:
case 9:
printf("Grade: A\n");
break;
case 8:
printf("Grade: B\n");
break;
case 7:
printf("Grade: C\n");
break;
case 6:
printf("Grade: D\n");
break;
MAILAM ENGINEERING COLLEGE UNIT II CS25C01-COMPUTER PROGRAMMING IN C
case 5:
printf("Grade: E\n");
break;
default:
printf("Grade: F (Fail)\n");
}
return 0;
}
CS25C01 COMPUTER PROGRAMMING:C
MAILAM(PO),Villupuram(DT).Pin:604304
(Approved by AICTE, New Delhi, Affiliated to Anna University, Chennai,
Accredited by NBA, NAAC with ‘A’ Grade and TATA Consultancy Services)
PART–A
FUNCTION DECLARATION
1) What is a function?List out the types of functions.
A function is a self- contained program, or a sub program of one or more statements which is used to
do some particular task.
Function in C can perform a particular task, and supports the concept of modular programming design
techniques.
Types:
I. Pre-defined Functions(Library Function)
II. User-defined Functions.
2) What is meant by library function with example? (or)List any two math built-in functions.
Library functions are also known as built-in functions or intrinsic [Link] compiler
itself evaluates these functions. This is known as library functions.
Example:
sqrt(), log(x), exp(), sin() and soon…
1
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
It tells the return type of the data that the function will return.
It tells the number of arguments passed to the function.
It tells the data types of the each of the passed arguments.
Also it tells the order in which the arguments are passed to the function.
Therefore essentially, function prototype specifies the input/output interlace to the
function i.e. what to give to the function and what to expect from the function.
2
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
14) What are formal parameters and actual parameters in C functions?
Formal Parameters:
These are the variables declared in the function definition's parameter list.
They act as placeholders to receive values passed during a function call.
Actual Parameters or Arguments:
These are the values or expressions passed to a function when it is called.
They are used to initialize the formal parameters.
15) What is meant by parameter passing method? List out the various parameter passing method in
function.
Passing input parameters into a module or function and receiving output parameters back from the module
or function. There are two types of parameter passing method, they are given below,
o Call by value
o Call by reference
int x=456,*p1,**p2;
p1=&x; p2=&p1;
printf(“Value of x is: %d\n”,x);
3
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
printf(“Value of *p1 is: %d\n”,*p1);
printf(“Value of *p2 is: %d\n”,*p2);
Output:
Call by Value: The function receives a copy of the variable. Changes made inside the function do not
affect the original value.
Call by Reference: The function receives the address of the variable. Changes made inside the
function do affect the original value.
RECURSION FUNCTIONS
34) Write a modular C program structure that includes a main file and a header file.
#include "math.h"
int main()
{
int r = add(2, 3);
}
-----------------------------------------------------------------------------------
5
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
PART – B
FUNCTION DECLARATION
USER-DEFINEDFUNCTIONS
The functions which are created by user for program are known as 'User defined functions'.
C functions can be classified into two categories, namely,
Library functions:
o printf() and scanf() belong to the category of library functions.
User defined functions:
o main() is an example of user-defined functions.
i)Function Declaration
Function declaration is also known as function prototype.
A Prototype can occur at the top of a C source code file to describe what the function
returns and what it takes (return type and parameter list).
The function prototype Should be followed by a semi-colon.
The general form of function declaration is given below.
Syntax
return_type function_name(parameter list);
Example
int sum(int,int); (or)
int sum(int a,int b); /*This type of function declaration is also allowed*/
Function Call
ii)
A function can be called by specifying the name of the function, followed by a list of
arguments enclosed in parentheses. It is appear within main() function.
Example
main()
{
sum(a,b);
Syntax
Function_type Function_name(parameter list)
{
local variable declarations;
executable statement-1;
executable statement-2;
………
………
7
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
return(expression);
}
Function Header
a) Function type.
b) Function name.
c) Parameter list.
a) Function type
It is used to specifies the type of value that the function is expected to return to the
calling function. The void data type refers ‘its return nothing’.
b) Function name
The name of the function is formed by any valid C identifiers.
c) Parameter list
The parameters are also known as arguments. List of variables are separated by comma
enclosed within parentheses.
There are two types of parameters are available, they are
Actual parameters.
Formal parameters.
Example:
#include<stdio.h>
intsum(int,int); /*Function prototype*/
main()
{
inta,b,c;
printf(“\nEnter the values for A and B:\n”);
scanf(“%d%d”,&a,&b);
Actual arguments
8
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
2) Write different types of functions with respect to returns type arguments and explain all types
with syntax and example. (or) Classify the function prototypes with suitable examples.
In general, functions can be classified in to four categories depending up on the presence of the
following facts, they are
Arguments.
Return type.
A function may be long to one of the following categories.
i. Functions with no arguments and no return values.
ii. Functions with arguments and no return values.
iii. Functions with no arguments and return values.
iv. Functions with arguments and return values.
(i)Functions with No Arguments and No Return Values
A function does not receive any data from the calling function. Similarly,It does not return any
value.
Calling Function Called Function
No arguments
main() sample()
{ {
----------------- }
}
The dotted lines specify that,no data transfer and no return value of any computation in block.
Example:
#include<stdio.h>void
sum(void); main()
{
voidsum(void);
}
voidsum(void)
{
inta,b,c;
printf(“Enter the values for A and B:\n”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“Answer is%d”,c);
}
Output
Enter the values for A and B:
10 20
Answer is 30
9
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
main() sample(x,y)
{ {
---------------- With arguments ----------------
sample(a,b); ----------------
----------------- No return values ----------------
}
}
Example:
#include<stdio.h>
voidsum(int,int);
main()
{
int a,b;
printf(“\n Enter the values for A and B:\n”);
scanf(“%d%d”,&a,&b);
void sum(a,b);
}
void sum(int x,int y)
{
int z;
z=x+y;
printf(“\n Answer is%d”,z);
Output
Enter the values for A and B:
10 20
Answer is 30
10
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
Calling Function Called Function
main() sample()
{ With no arguments {
c=sample(); return(z);
----------------- Return values -------------------
Example:
#include<stdio.h>
sum(void);
main()
{
int z;
z=sum(void);
printf(“\n Answer is%d”,z);
}
int sum(void)
{
inta,b,c;
printf(“\n Enter the values for A and B:\n”);
scanf(“%d%d”,&a,&b);c=a+b; return(c);}
Output
Enter the values for A and B:
10 20
Answer is 30
} }
11
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
Example:
#include<stdio.h>
int sum(int, int);
main()
{
inta,b,c;
printf(“Enter the values for A and B:\n”);
scanf(“%d%d”,&a,&b);
c=sum(a,b);
printf(“\n Answer is %d”,c);
}
int sum(int x,int y)
{
int z;
z=x+y;
return(z);
}
Output
Enter the values for A and B:
10 20
Answer is 30
3) Explain the purpose of a function prototype and specify the difference between user-defined function
and built-in functions.
It tells the return type of the data that the function will return.
It tells the number of arguments passed to the function.
It tells the data types of the each of the passed arguments.
Also it tells the order in which the arguments are passed to the function.
Therefore, essentially, function prototype specifies the input/output interlace to
the function i.e. what to give to the function and what to expect from the
function.
Prototype of a functions also called signature of the function.
Example:
void main(int a,int b);
OR
void main(int,int);
First of all, function prototypes include the function signature, the name of the function, return type
and access specifier. In this case the name of the function is "main".
The function signature determines the number of parameters and their types. In the
above example, the return type is"void".This means that the function is not going to return
any value.
12
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
Difference between user-defined function and built-in functions
User defined function Built-in function
User defined functions are the function Built-in functions are known
which are created by user. as Predefined functions or
library functions.
User defined functions are part of the Built-in functions are part of header file
program which compile runtime. (such as math.h) which is called run time.
In User defined functions the name of In Built-in functions it is given by
Function id decided by user. developers.
In User defined functions name of function Name of the function can’t be changed.
can be changed any time.
Example: Example:
int sum() math.h
voids wap() string.h
sqrt()
pow()
13
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
Program: Formal arguments
#include<stdio.h>
int sum(int, int); main()
{
int a,b,c;
printf(“\n Enter the values for A and B:\n”);
scanf(“%d%d”,&a,&b);
c=sum(a,b);
printf(“\n Answer is %d”,c);
}
Output
Enter the values for A and B:
10 20
Answer is 30
Example:
Actual arguments
14
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
Formal arguments
Let see the example program as swapping of two numbers for this concept.
This concept is al so considered for Pointers as function parameters.
Program:
#include<stdio.h>
voidswap(int*,int*);
main()
{
inta,b;
printf(“\n Enter the values for A and B:\n”);
scanf(“%d%d”,&a,&b);
printf(“\n Before Swapping\n”);
printf(“A=%d\tB=%d\n”,a,b);
swap(&a,&b);
printf(“\n After Swapping\n”);
printf(“A=%d\tB=%d\n”,a,b);
}
voidswap(int*x,int*y)
{
int z;
z=*x;
*x=*y;
*y=z;
}
Output
Enter the values for A and B:
12 34
Before Swapping
A=12B=34
After Swapping
A=34B=12
15
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
5) Distinguish between Library functions and User defined functions in C and Explain with examples.
(i) Library Functions in C
C provides library functions for performing some operations. These functions are present in the c
library and they are predefined.
For example sqrt() is a mathematical library function which is used for finding the square root of
any number .The function scanf and printf() are input and output library function similarly we
have strcmp() and strlen() for string manipulations. To use a library function we have to include
some header file using the preprocessor directive #include.
For example to use input and output function like printf() and scanf() we have to include stdio.h,
for math library function we have to include math.h for string library string.h should be included.
(ii) User Defined Functions in C
A user can create their own functions for performing any specific task of program are called user
defined functions. To create and use these function we have to know these 3 elements.
I. Function Declaration
II. Function Definition
III. Function Call
I. Function declaration
The program or a function that calls a function is referred to as the calling program or calling function.
The calling program should declare any function that is to be used later in the
program this is known as the function declaration or function prototype.
II. Function Definition
The function definition consists of the whole description and code of a function. It tells that
what the function is doing and what are the input outputs for that. A function is called by
simply writing the name of the function followed by the argument list inside the parenthesis.
Function definitions have two parts:
Function Header
The first line of code is called Function Header.
int sum( int x, int y)
It has three parts
(i). The name of the function i.e. sum
(ii). The parameters of the function enclosed in parenthesis
(iii). Return value type i.e. int
Function Body
Whatever is written with in { } is the body of the function.
#include<stdio.h>
void fun1(int, int);
void main( )
{
int a=10, b=15;
fun1(a,b);
printf(“a=%d,b=%d”, a,b);
}
void fun1(int x, int y)
{
x=x+10;
y= y+20;
}
Output:a=10 b=15
The result clearly shown that the called function does not reflect the original values in main
function.
(ii) Pass by reference (or) call by address:-
In this method calling function sends address of actual values as a parameter to called function,
called function performs its task and sends the result back to calling function.
Thus, the changes in called function reflect the original values of calling function. To return multiple
values from called to calling function we use pointer variables.
Calling function needs to pass „&‟ operator along with actual arguments and called function
need to use „*‟ operator along with formal arguments. Changing data through an address
variable is known as indirect access and „*‟ is represented as indirection operator.
Example program:
#include<stdio.h>
void fun1(int,int);
void main( )
{
int a=10, b=15;
fun1(&a,&b);
printf(“a=%d,b=%d”, a,b);
}
void fun1(int *x, int *y)
{
*x = *x + 10;
*y = *y + 20;
}
17
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
Output: a=20 b=35
The result clearly shown that the called function reflect the original values in main function. So that it
changes original values.
The list of variables in calling function is The list of variables in called function is
known as actual parameters. known as
formal parameters.
Actual parameters are variables that are Formal parameters are variables that are
declared in function call. declared in
the header of the function definition.
Actual parameters are passed without Formal parameters have type preceding with
using type them.
main() return_type function_name(formal
{ ..... parameters)
function_name (actual parameters);
……………. .....
}
function body;
…….
}
Formal and actual parameters must match exactly in type, order, and number.
Formal and actual parameters need not match for their names.
RECURSIVE FUNCTIONS
When a function in turn calls another function a process of ‘chaining’ occurs. Recursion
is a special case of this process, ‘where a function calls itself’.
18
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
Example:
void main()
{
recur();
}
void recur()
{
recur(); /*function calls itself*/
}
/*Program to calculate the factorial of an integer number*/
#include<stdio.h>
int fact(int);
main()
{
int a;
printf("Enter the number:");
scanf("%d",&a);
printf("The factorial of %d=%d",a,fact(a));
}
int fact(int x)
{
if(x==1)
return(1);
else
return(x*fact(x-1));
}
Output:
Enter any number 4
Factorial value=24
Explanation
Advantages of recursion
• Recursive solutions often tend to be shorter than non-recursive ones.
• Recursion represents like the original formula to solve a problem.
• Follows a divide and conquer technique to solve problems.
• In some(limited)case, recursion may be more efficient.
19
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
Disadvantages of recursion
• For some programmers and readers, recursion is a difficult concept.
• Recursion is implemented using systems tack. If the stack space on the system is limited,
recursion to a deeper level will be difficult to implement.
• Using a recursive function takes more memory and time to execute as compared to its
non-recursive counterpart.
• It is difficult to find bugs, particularly when using global variables.
20
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
Example:
void example Function() {
int localVar = 10; // Function-level local variable
if (localVar == 10) {
int blockVar = 20; // Block-level local variable
printf("blockVar: %d\n", blockVar); // Accessible here
}
// printf("%d", blockVar); // Error: blockVar is not accessible here
printf("localVar: %d\n", localVar); // Accessible within the whole function
}
2)Global Scope
A variable has global scope when it is declared outside of all functions.
This means the variable is accessible from any function in the program.
Global variables remain in memory for the entire duration of the program and can be accessed by
any function after their declaration.
Example:
int globalVar = 100; // Global variable with global scope
void function1()
{
printf("Global variable in function1: %d\n", globalVar);
}
void function2()
{
globalVar = 200; // Modifying global variable
int main() {
return 0;}
#include <stdio.h>
// Function declarations
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
float divide(int a, int b);
#endif
// -----------------------------------------------------------
return 0;
}
/ ------------------------------------------------------------
---------x------------------x------------------------The End--------------------------x---------------x----------
22
Unit 3
CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV
I YEAR B.E/[Link]
SEMESTER-I
UNIT IV- Strings & Pointers:
SYLLABUS:
One-dimensional and Multi-dimensional Arrays, Array operations and traversals,
String Handling: String declaration, input/output, string library functions, Pointer
arithmetic, Pointers and Arrays, Pointers to function, Dynamic memory
allocation.
Part-A
1) What is an array? What are the classifications of an array?
Array means sequence of elements that share a common name with similar as
types This is known as Array.
Types:
One-dimensional array
Two-dimensional array and,
Multi-dimensional array
2) Write the features of arrays.
An array is a derived data types. It is used to represent a collection of elements
of the same data type.
The elements can be accessed with base address and the subscript defined for the
position of the element.
The elements are stored in continuous memory location.
The starting memory location is represented by the array name and it is known
as the
base address of the array.
3) List out the disadvantages of an array.
The elements in the array must be same data types
The size of an array is fixed.
If we need more space at run time, it is not possible to extend array.
The insertion and deletion an operation is an array require shifting of elements
takes time
4) What will happen if in a C program you assign a value to an array element
whose subscript exceeds the size of array?
Possible Outcomes:
PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 1
CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV
The program may run without error and print an unexpected value.
It may crash with a segmentation fault.
It may corrupt adjacent memory, leading to erratic behavior elsewhere.
5) List out the properties of an array.
All the elements of an array share the same name and they are distinguished from
one
another with the help of an element number.
String Handling
15) What is string? Give example.
String is the sequence of character or array of character enclosed within double
quotes That string must terminate with null character (10)
Example: "super
16) How strings are represented in language C?
String is the sequence of character or array of character enclosed within double
quotes. That string must terminate with null character (10).
Example:
char str[]="super";
The elements of the array are
str[0]='s';
str[1]='u';
str[2]='p';
str[3]='e';
str[4]='r';
str[5]=’\0';
17) If string1="C Programming" and string2="Language"; Write the built-in
functions to
(a) Find the length of the string 1;
(b) Compare two strings. Whether they are equal.
strlen(string1), answer is 13
string1 and string 2 are not equal.
18) Define strlen() function.
strlen(), this function is used to count and return the number of character present
in a
string.
Syntax:
len=strlen(string);
19) Define strcat() function.
strcat(), tres function is usert to concatenate or comlane twe sings together then
forms a [Link]
Syntax:
strcat(str1.str2)
20) Define strrev() function.
Strrev(), this fonction is used to reverse a string. This function takes and returns
only
one argument
Syntax: strrev(str);
21) Define strcmp() function.
stromp(), this function which compares two strings to find whether they are same
or different. If two strings are equal means it returns a zero otherwise numeric difference
between the non-matching characters
Example:
var strcmp("Hello", "World"); // value of var is 1
22) What is the purpose and prototype of the function strcpy()?
The purpose of strcpy() is used to copy the contents of a string to another strings
Syntax:
strcpy(str1,str2);
Note: 'str' and 'str2' are two essential prototype of this function.
23) Design a C program to compare any two strings.
main()
{
char s1[10]="Hello";
char s2[10]="World";
if(strcmp(s1,s2)==0)
printf("Both are equal");
else
In general, the null pointer is used to denote the end of a memory search or
processing event. In programming, a null pointer is a pointer that does not point to any
objects or function. A null pointer is a false value.
28) What is Pointers to Pointers?
Pointer variable contains the address of another variable. Similarly another
pointer variable can store the address of a pointer variable. The pointer variable is said
to be pointer to pointer. Example: int **p2;
29) What is pointer arithmetic? Explain with examples.[AU DEC 2020]
One of the interesting uses of pointer is pointer arithmetic. Like an pointer
variables can also be used in arithmetic expressions. Assu pointer variables, and the
values are 10, 20, 30 respectively. Then example of pointer expression.
#include<stdio.h>
PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 6
CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV
*ptr = 30;
}
int main()
{
int y=20;
fun(&y);
printf("%d", y);
}
Output is 30
ARRAYS AND POINTERS
32) Define arrays of pointers.
Arrays are collection of elements stored in continuous memory locations. An
array of pointers is similar to any other array in C. It is an array which contains
numerous pointer variables and these pointer variables can store address values of some
other variables having the same data type.
36) What are the return type of malloc() and calloc(), how can we use?
malloc() and calloc() both functions return void* (a void pointer), to use/capture the
returned value in pointer variable we convert it's type.
Suppose we create memory for 10 integers then we have to convert it into int"
int *ptr;
ptr=(int*)malloc(N*sizeof(int));
Here, malloc() will return void and ptr variable is int type, so we are converting it into
(int*).
It has the ability to release unwanted memory space during the program
execution.
It is very useful to modify the size of the previously allocated memory.
It is very useful to allocate memory space to an array of elements and initialize
them to zero.
Initialization of Arrays
We can also initialize the elements of arrays like an ordinary variable
initialization. An array can be initialized in two way, they are
(i) Compile time initialization.
(ii) Run time initialization.
(i) Compile time Initialization
Initialization in made at the time of declaration (in the declaration part) is
known as compile time initialization. The general form of initialization of arrays is:
Syntax:
PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 10
CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV
#include<stdio.h>
void cube(int),
main()
{
int i,num[5]=(2,4,6,8,9);
for(i=0;i<5;i++)
{
cube(num[i]);
}
void cube(int n)
{
printf("%d\n",n*n*n);
}
Output
8
64
216
512
729
sum(n,a);
}
void sum(int x,int b[])
{
int add=0,1;
for(i=0;i<5;i++)
{
add=add+b[i];
}
printf("The Answer is %d",add);
}
Output
Enter 5 elements:
1
2
3
4
5
The Answer is 15
The Answer is 15
TWO-DIMENSIONAL ARRAYS
Program
/*Program for two dimensional array*/
#include<stdio.h>
main()
{
int i,j,a[3][3];
printf("Enter the First Matrix");
for ( i = 1 ; i <= 3 i ++)
{
for(j=1;j<=3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Transpose Matrix");
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
printf("%d\t",a[j][i]);
}
printf("\n");
}
}
Output
Enter the First Matrix
123
234
587
Transpose Matrix
125
238
347
There are two types of array initialization, they are given below.
Types:
The above two examples will never work. To make the above two initialization
in better manner means we must mention the column size then only the compiler
knows where the first row ends.
The row size is optional if we initialize the array in the declaration part itself.
b) Run time initialization.
An array can be explicitly initialized at run time by using scanf() function.
Example:
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
STRING-HANDLING FUNCTIONS
(4) List out and explain in briefly about string handling functions with
example.(or) Write about the significant of header file, 'string.h' and write short
notes on any three string functions.
Significant of string.h:
The string.h header file C provides various functions for manipulating stings,
such strings. Some of the commonly used functions from string.h are discussed below
copying strings, concatenating strings, comparing strings, and searching for subistings
within
Popular string functions
strcat() Concatenates two strings.
strcmp() Compares two strings.
strcpy() Copies one string over another.
strlen() Finds the length of the string..
strrev() Finds the reverse string
Let see one by one as follows,
(i) strcat() Function program) String concatenation (Explain the usage of strcat() with
the C
The strcat() function is used to joins two strings together.
Syntax:
strcat(string1, string2);
String1 and String2 are character type arrays or string constant
Example:
strcat("THINK ", "POSITIVE");
strcat(strcat(string1, string2), string3);
Here three strings are concatenated and the result is stored in string1.
Program:
#include <stdio.h>
#include <string.h>
main()
{
char str1[50),str2[50];
printf("Enter the first string)
gets(str1);
printf("Enter the second string);
gets(str2);
strcat(str1,str2); printf("Result=%s", str1);
}
Output:
Enter the first string: Computer
Enter the second string: Science
Result Computer Science
strcmp("ram", "rom");
Program:
#include<stdio.h>
#include<string.h>
main()
{
char str1[50],str2[50];
int n;
printf("Enter the first string:");
gets(str1);
printf("Enter the second string:");
gets(str2);
n=strcmp(str1,str2);
if(n==0)
printf("Strings are equal");
else
printf("Strings are not equal");
}
Output 1
Enter the first string: computer
Enter the secorid string Programming Strings are not equal
Output 2
Enter the first string computer
Enter the second string: computer Strings are equal
(iii) strcpy() Function - String Copy
This function works almost like a string assignment operator It takes the form
Syntax:
strcpy(string1, string2);
This assigns the content of string2 to string1.
Example:
strcpy(str1, "SUPER");
strcpy(str1,str2);
Program:
#include<stdio.h>
#include <string.h>
main()
{
char str1[50], str2[50], str3[50];
int n;
printf("Enter the first string:");
gets(str1);
strcpy(str2, "SUPER");
strcpy(str3,str1);
printf("String1=%s\n",str1);
printf("String2=%s\n",str2);
printf("String3=%s\n", str3);
}
Output:
Enter the first string: computer
String1 Computer
String2 SUPER
String3 Computer
(iv) strlen() Function - String Length
The process of finding the number of characters in a string with the help This
function counts and returns the number of characters in a given string.
Syntax:
n = strlen(string);
Program
Illustration of string-handling functions/
#include <stdio.h>
#include<string.h>
main()
{
char s1[20],62(20),83[20];
int x,len 1, len2,len3,
printf("Enter two string constants V)
scanf("%s%s",51,52);
x=strcmp(s1,s2);
if(x!=0)
printf("Strings are not equal \n");
ese
printf("Strings are equal \n");
strcat(s1, s2);
strcpy(s3,51);
len1=strlen(s1);
len2=strlen(s2);
len3=strlen(s3);
printf("\ns1=%s\tlength=%dcharacters\n",s1, len
printf("\ns2= %s \tlength=%dcharacters\n",s2, le
printf("\ns3=%s\tlength=%dcharacters\n",s3,len.
}
Output:
Enter two string constants
New York
Strings are not equal
s1-New York length 7 characters
s2=York length=4 characters
s3=New York length 7 characters
str2=strrev("success");
The reverse of the string "success" is stored in str
Program:
#include<stdio.h>
#include <string.h>
main()
{
char str1[50],str2[50];
clrscr();
printf("Enter the string:");
gets(str1);
str2=strrev(str1);
printf("String1=%s\n", str1);
printf("String2=%s\n",str2);
getch();
}
Output:
Enter the string: success
String1 = success
String2= sseccus
POINTER ARITHMETIC
5) What is pointer arithmetic? Explain with examples.
One of the interesting uses of pointer is pointer arithmetic. Like an ordinary
variable. pointer variables can also be used in arithmetic [Link] x,y and
z are pointer variables,and the values are 10,20,30 respectively. Then the following is
an example of pointer expression
Output
Address of var[3]= bfedbcd8
Value of var[3]=200
Address of var(2)= bfedbcd4
Value of var[2]=100
Address of var[1] = bfedbcd0
Value of var[1]=10
(iii) Addition
Addition of two numbers can be performed using pointers. In the below
program two integer variables x, y and two pointer variables p and q.
Example Program:
#include <stdio.h>
main()
{
int first, second, *p, *q, sum;
printf("Enter two integers to add\n");
scanf("%d%d", &first, &second);
p=&first;
q=&second;
sum=*p+*q;
printf("Sum of entered numbers %d\n",sum);
}
Output
Enter two integers to add:
4
5
Sum of entered numbers =9
(iv) Subtraction
We can subtract an integer number from pointer type like addition.
#include<stdio.h>
main()
{
int num,*ptr1,*ptr2;
ptr1=#
ptr2=ptr1+2;
printf("difference is: %d", ptr2-ptr1);
}
Output:
difference is : 2
The base address of the array, starts with O ^ (0) element of the array. The array
is in Integer type.
The integer will have 2 bytes.
The address of the next address element is incremented by 2.
Program:
Program to add the sum of number using pointer
#include<stdio.h>
main()
{
Output:
Enter the number 1:10
Enter the number 2:20
Enter the number 3:30
Enter the number 4:40
Enter the number 5:50
Total =150
Pointers and Multi-dimensional Arrays
In two dimensional arrays, array elements are stored row by row. When we pass
2D array to a function we must specify the number of columns, the number of rows is
Irrelevant. This is because C needs to know how many columns in order that it can
jump row to row in memory.
int a[10][20];
int *b[10];
OUTPUT:
The value of 0= 10, address is 65518
The value of 1= 20, address is 65516
The value of 2= 30, address is 65514
MAHA
11)Convert the given string from lower case character to upper case and upper
MAILAM(PO),Villupuram(DT).Pin:604304
(Approved by AICTE, New Delhi, Affiliated to Anna
University, Chennai, Accredited by NBA, NAAC with ‘A’ Grade
and TATA Consultancy Services)
Structures & Unions: Defining and using structures, Array of structures, Pointers to
structures, Unions and their uses, Enumerations.
PART-A
1
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
5. State the meaning of the root word struct.
The keyword of struct is used to define a structure. The keyword struct followed by
structure name or tag name.
Example:
struct stud
{
int rno;
char name [25]; }
Arrays Structures
S.N
o
5 An array cannot have bit fields. A structure may contain bit fields.
2
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
struct MyStruct {
int value;
};
struct MyStruct s;
struct MyStruct *ptr = &s;
Here, (ptr)holds the address of(S)
12. Illustrate with an example for each, the following operators with regards to
pointers and structures. &, * ,. -> [AU-DEC 2023]
● Address-of Operator (&):
The address-of operator (&) is used to get the address of a variable.
Example: printf("Address of num: %p\n", &num);
● Indirection or Dereference Operator (*):
The indirection or dereference operator (*) is used to access the value
stored at the address held by a pointer.
Example: printf("Value of num using pointer: %d\n", *ptr);
● Member Access Operator (.):
The member access operator (.) is used to access members of a
structure using a structure variable.
Example: printf("Coordinates of point: (%d, %d)\n", p.x, p.y);
3
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
● Structure Pointer Operator (->):
The structure pointer operator (->) is used to access members of a
structure using a pointer to the structure.
Example: printf("Coordinates of point: (%d, %d)\n", ptr->x, ptr->y);
14. How can you access the members of the union? [AU-DEC 2020]
We use the . Operator to access members of a union. And to access pointer variables,
we use the -> operator.
Example:
union car
{
char name[50];
int price;
} car1, car2, *car3;
In the above example,
● To access price for car1, [Link] is used.
● To access price using car3, either (*car3).price or car3->price can be used
4
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
16. Compare structures and unions. (or) What are the key difference between structure
and union? [AU-MAY 2022, Dec 2023]
S.N Structure Union
o
1 Every member has its own memory. All members use the same memory.
3 All members occupy separate memory Different interpretations for the same
location, hence different interpretations of memory location are possible.
the same memory location are not possible.
17. What is the output of the following code fragment? [AU MAY 2019]
Strcut point
{
int x,y;
} origin, *pp;
main() { pp=&origin;
printf(“Origin is (%d%d)\n”,(*pp).x,pp->y);
}
Output: Origin is 00
5
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
22. Define the Structure called ID_card to hold the details of the student. (Jan 1 )
struct ID_card
{
char name [50];
char address [50];
int age;
} b1,b2;
23. Write the syntax of pointers to structures.
A pointer can be declared in such a way that it points to a structure data type.
A pointer to a structure is created as follows
struct student
{
int rno;
char name [23];
float avg;
};
struct student *str;
6
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
PART-B
STRUCTURE
1) Explain about structure with example program. [AU-DEC 2021, DEC 2024] (or)
What is the purpose of the concept ‘structure’ in language C? Explain in detail with an
example program. [AU-MAY 2022] (or)
What is structure? Create a structure with data members of various types and declare
two structure variables. Write a program to read data into these and print the same.
Justify the need for structured data type. [AU-DCE 2022]
Definition of structure:
It is a user defined data type. A structure is a collection of variables of different types
grouped together under a single name. By using structures we can make a group of variables,
arrays, pointers and etc..,
Declaration
It contains data members and each is accessed by the structure variable. A structure is
declared using the keyword struct followed by a structure name. All the variables of the
structures are declared within the structure.
Syntax
Struct structure__name
{
Structure_element 1;
Structure_element 2;
--------------
--------------
Structure_element n;
}; struct structure_name v1,v2,….,vn;
7
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
Int marks;
Float avg;
Char grade;
}
Memory allocation
The structure definition does not allocate any memory. Structure provides a model of
how the structure is to be in memory and gives details of the member names. Memory is
allocated for the structure when we declare a variable of the structure.
Initialization
Initializing a structure means assigning some constants to the members of the structure.
The initializes are enclosed in braces and are separated by commas.
Example:
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
}struct student stud1 = {01, “Rahul”, “IT”, 45000};
Accessing the Members of a Structure
Array elements are accessed using the Subscript variable, Similarly Structure members
are accessed using dot [.] operator. It is called as “Structure member Operator”. Use this Operator
in between “Structure name” & “member name”
Syntax:
struct_var. member_name
Example:
[Link] = 01;
strcpy([Link], “Kalama”);
[Link] = “IT”;
[Link] = 45000;
Here the dot is an operator which selects a member from a structure. Selecting a member from a
structure pointer happens frequently, it has its own operator -> which acts as follows. Assume that
stud1 is a pointer to a structure of type student we would refer to the name member as
[Link]->name
8
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
2. Program using structures to read and display the information about a
student.[AU –NOV/DEC 2014]
(or)
Write a C program to create mark sheet for students using self-referential
structure.
OUTPUT:
Enter the roll number : 101
Enter the name : rahul
Enter the fees : 45000
Enter the DOB : 11.2.1995
9
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
3. Write a c program to add two distance (in inch-feet) system using structures.
#include <stdio.h>
struct Distance
{
int feet;
float inch;
} distance1, distance2, sum;
main()
{
printf ("Enter feet and inch for the first distance with a space: \n");
scanf ("%d %f", & [Link], & [Link]);
printf ("Enter feet and inch for the second distance with a space: \n"); scanf
("%d %f", & [Link], & [Link]);
10
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
ARRAYS OF STRUCTURE
Example
Now, to assign values to the ith student of the class, we will write,
stud[i].r_no = 09;
stud[i].name = “RAM”;
stud[i].course = “CSE”;
stud[i].fees = 60000;
Program
#include<stdio.h>
struct studentinfo
int roll;
char name[20];
int age;
} s[100];
main()
int n,i;
scanf("%d",&n);
11
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
printf("Enter Student Information:");
for(i=1;i<=n;i++)
scanf("%d",&s[i].roll);
scanf("%s",&s[i].name);
scanf("%d",&s[i].age);
for(i=1;i<=n;i++)
printf("\n Name:%s",s[i].name);
Structures can be created and accessed using pointers. A pointer variable of a structure can be
created as below:
Syntax:
struct name{
member1;
member2;
..
};
12
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
● They enable efficient manipulation of large structures since only addresses are passed, not the
whole structure.
● Functions can modify original structures when given their pointers, instead of working with local
copies.
● Structure pointers are essential for building dynamic and complex data structures, such as linked
lists and trees, where elements are allocated at runtime and linked using pointers.
example:
int main()
{
struct name *ptr;
}
We can define pointers to structures in the same way as you define pointer to any other variable
struct student*ptr;
Now, we can store the address of a structure variable in the above defined pointer
variable. To find the address of a structure variable, place the '&'; operator before the structure's
name as follows
ptr = &stu;
Accessing members using Pointer
There are two ways of accessing members of structure using pointer:
o Using indirection (*) operator and dot(.) operator.
o Using arrow (->) operator or membership operator.
Example
struct Person {
int age;
float weight;
};
struct Person p;
struct Person *ptr = &p;
ptr->age = 30;
ptr->weight = 65.5;
Here, ptr allows access to p's members using ->
Summary Table
13
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
Syntax Description
Pointers to structures are a cornerstone for efficient, dynamic data manipulation in C/C++
programs
Example
To access the members of a structure using a pointer to that structure, we must use the →
operator as follows
ptr->studentid;
Program
#include <stdio.h>
#include<string.h>
struct student
{
int id;
char name[30];
float percentage;
};
main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student *ptr;
14
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
ptr = &record1;
printf("Records of STUDENT1: \n");
printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);
}
Output:
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
6. Program using pointer to structure to initialize the members in the structure.
15
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
6. Briefly explain about union with its relevant syntax and example.
A union is a special data type available in C to store different data types in the same
memory location. We can define a union with many members, but only one member can
contain a value at a time. Unions provide an efficient way of using the same memory location
for multi-purpose.
Syntax
union
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
16
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
char grade;
};
Now, a variable of sample type can store an integer, a floating-point number, or a
string of characters. This means that a single variable ie. same memory location can be used to
store multiple types of data. We can use any built-in or user defined data types inside a union
based on requirement.
Memory allocation
➢ In union
union student
{
int marks;
float avg;
char grade;
};
17
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
Output:
Memory size occupied by data:20
Explanation:sizeof()returns the memory allocated for union
18
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
union myUnion
{
int var1;
long var2;
}newUnion={10.5};
newUnion.var1= 10;
19
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
enum enum_name
{
const1,
const2,
……..
……..
constn
};
uses:
● Readability:
Enums make code more understandable by replacing "magic numbers" with descriptive names.
● Maintainability:
Changes to the underlying integer values only require modification within the enum definition, not
throughout the code.
● Type Safety (to some extent):
While enum variables are essentially integers, using them as distinct types can help prevent accidental
assignment of invalid values (though the compiler may not enforce this strictly).
Example 1:
#include main()
{
enum Day
20
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
{
Monday =1,
Tuesday,
Wednesday,
Thursday
};
enum { A= 3, B , C , Z = 400, X, Y };
printf("Wednesday = %d\n", Wednesday);
printf("B = %d \t C = %d\n", B,C);
printf("X = %d \t Y = %d\n", X,Y);
printf("Thursday/Tuesday = %d\n", Thursday/Tuesday);
}
Output:
Wednesday = 3
B=4C=5
X = 401 Y = 402
Thursday/Tuesday = 2
Example 2:
#include<stdio.h>
enum year
{
Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
};
main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);
}
Output: 0 1 2 3 4 5 6 7 8 9 10 11
21
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
Enumerated Type Declaration
When you create an enumerated type, only blueprint for the variable is created.
Here's how you can create variables of enum type. enum boolean { false, true }; enum boolean
check; Here, a variable check of type enum boolean is created.
Syntax
enum boolean
{
false, true
} check;
8. Consider structure ‘furniture’ that includes the information about furniture in a shop.
Write a function call statement that has the argument as a pointer to the structure and
number of furniture. Also, provide the corresponding function definition statement that
receives the arguments. [AU – DEC 2023]
22
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
23
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
24
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
Open, read write, close file operations, Binary vs Text files, File Pointers, Error handling in
file operations.
PART – A
FILES: OPEN, READ, WRITE, CLOSE FILE OPERATIONS
1) What is a file?
A file is a collection of related data stored on a secondary storage device like hard
disk. Every file contains data that is organized in hierarchy as fields, records, and
databases. Stored as sequence of bytes, logically contiguous (may not be physically
contiguous on disk).
MODE DESCRIPTION
Open a text file for reading. If the stream (file) does not exist then an error
r
will be reported.
Open a text file for writing. If the stream does not exist then it is created
w
otherwise if the file already exists, then its contents would be deleted.
UNIT-6 1
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
Open a binary file for reading. B indicates binary. By default this will be a
rb
sequential file in Media 4 format.
Open a text file for both reading and writing. The stream will be positioned
r+ at the beginning of the file. When you specify "r+", you indicate that you
want to read the file before you write to it. Thus the file must already exist.
Open a text file for both reading and writing. The stream will be created
w+
if it does not exist, and will be truncated if it exist.
Open a text file for both reading and writing. The stream will be
a+
positioned at the end of the file content.
4) What are the opening modes are available for binary files?
MODE DESCRIPTION
Open a binary file for reading. B indicates binary. By default this will be a
rb
sequential file in Media 4 format
UNIT-6 2
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
11) How is fopen()used ? (or) Describe the prototype of the function fopen().
[AU-MAY 2023]
• The function fopen() returns a file pointer. Hence a file pointer is declared and it is
assigned as FILE *fp.
• fp= fopen(filename, mode); filename is a string representing the name of the file
and the mode represents.
13) What will be the impact if ‘fclose()’ function is avoided in a file handling C
program? [AU-MAY 2022]
• fclose() function is used for closing the stream and at the same time all the buffers
are also flushed.
• If the fclose() function is avoided means the used buffers are not cleared in file
processing.
14) How can you restore a redirected standard stream? [AU-MAY 2018]
By using the standard C library functions named dup() and fdopen(), you can
restore a standard stream such as stdout to its original state.
UNIT-6 3
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
The dup() duplicates a file handle. You can use this to save the file handle
corresponding to the stdout standard stream.
The fdopen() opens a stream that has been duplicated with the dup() function.
• Sequential access
• Random access
UNIT-6 4
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
24) Difference between sequential and random access file. [AU-DEC 2024]
Sequential Access File Random Access File
Results in continuous stream of data Results in fragment of data
Follows an order while writing in memory Doesn’t follow any order while writing in
memory
Utilizes the entire storage device’s capacity Only a small percentage of the device’s
capacity is utilized
Takes less time than random write Take longer to finish compared to
sequential write
Must wait until all of the data on the No need to wait for the completion of
storage device has been written before writing the current data chunk before
moving on to the next chunk of data moving to the next chunks
FILE POINTERS
UNIT-6 5
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
return 0;
}
Output
Size of FILE Structure: 216 bytes
We use a file pointer to refer to the file opened using fopen() function and the
behavior of a file pointer can vary depending on the access modes specified when
opening the file using the fopen() function.
Let's see how the C file pointer works in files with different access modes:
✓ In read mode(‘r’)
✓ In write mode(‘w’)
✓ In append mode(‘a)
29) What will be the values for argc and argv[] when the input “run with my
values” is passed as command line arguments? [AU-DEC
2023]
✓ argv[0] -> "run"
✓ argv[1] -> "with"
✓ argv[2] -> "my"
✓ argv[3] -> "values"
30) Name any two functions used in Random access files and specify their use
in C programming. [AU-DEC 2023]
✓ fseek: This function is used to move the file pointer to a specific position within a
file.
✓ fwrite: This function is used to write data to a file.
32)Write some common errors that can occur during file operations.
✓ File Not Found
✓ Permission Denied
✓ Disk Full
✓ File Already Exists
✓ Invalid File Pointer
✓ End-of-File (EOF)
✓ File Not Open
UNIT-6 6
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
PART B
INTRODUCTION TO FILES
1) What is file? What are facilities available in language C to handle files?
Explain. [AU-MAY 2022]
• A file is a collection of related data stored on a secondary storage device like hard
disk.
• Every file contains data that is organized in hierarchy as fields, records, and
databases.
• Stored as sequence of bytes, logically contiguous (may not be physically
contiguous on disk). (Refer Figure 6.1).
Streams
• Stream is a Sequence of data bytes, which is used to read and write data to a
file.
• A Stream acts as an interface between a program and an input/output Device.
Input streams get the data from Output Streams obtain data from
different input devices such as the program and write that on
keyboard and mouse and provide different Output Devices such as
input data to the program. Memory or print them on the Screen.
Buffer in files
• A buffer is a block of memory that is used for temporary storage of data that has
to be read from or written to a file.
• The buffer acts as an interface between the stream (which is character-oriented)
and the disk hardware (which is block oriented).(Refer Figure 6.2).
UNIT-6 7
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
Structure of files
Example
UNIT-6 8
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
2) Explain in detail various operations that can be done on file giving suitable
examples. [AU-MAY 2019]
• A file is a collection of related data stored on a secondary storage device like hard
disk.
• Every file contains data that is organized in hierarchy as fields, records, and
databases.
• Stored as sequence of bytes, logically contiguous (may not be physically
contiguous on disk).
File Operations
➢ Declaring a file
➢ Creating a new file
➢ Opening an existing file
➢ Processing a file
o Reading from file
o Writing information to a file
➢ Closing a file
FILE *file_pointer_name;
Example:
FILE *fp;
• Then, fp is declared as a file pointer.
• An error will be generated if you use the filename to access a file rather than
the file pointer
(ii) Creating a new file or Opening an existing File:
• A file must be first opened before data can be read from it or written to it. In
order to open a file and associate it with a stream, the fopen() function is used.
• The prototype of fopen() can be given as:
Syntax:
UNIT-6 9
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
MODE DESCRIPTION
Open a text file for reading. If the stream (file) does not exist then
r
an error will be reported.
Open a text file for writing. If the stream does not exist then it is
w created otherwise if the file already exists, then its contents would be
deleted
Open a binary file for reading. B indicates binary. By default this will
rb
be a sequential file in Media 4 format
Open a text file for both reading and writing. The stream will be
positioned at the beginning of the file. When you specify "r+", you
r+
indicate that you want to read the file before you write to it. Thus the
file must already exist.
Open a text file for both reading and writing. The stream will be
w+
created if it does not exist, and will be truncated if it exist.
Open a text file for both reading and writing. The stream will be
a+
positioned at the end of the file content.
Syntax:
UNIT-6 10
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
Example:
#include<stdio.h>
void main()
{
FILE *fp;
char name[80];
int roll_no;
fp = fopen("[Link]", "r");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
printf("\n Enter the name and roll number of the student : ");
fscanf(stdin, "%s %d", name, &roll_no); // read from keyboard
printf(“\n NAME : %s \t ROLL NUMBER = %d", name, roll_no);
fscanf(fp, "%s %d", name, &roll_no); // read from file- [Link]
printf(“\n NAME : %s \t ROLL NUMBER = %d", name, roll_no);
fclose(fp);
}
Output:
Enter the name and roll number of the student : raj 101
NAME : raj ROLL NUMBER = 101
NAME : raj ROLL NUMBER = 101
Syntax:
int fprintf ( FILE * stream, const char * format, ... );
The parameter format in the fprintf() is a C string that contains the text that has
to be written on to the stream.
Example:
#include <stdio.h>
main()
{
FILE *fptr;
char name[20];
int age;
float salary;
fptr = fopen ("[Link]", "w"); /* open for writing*/
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n", name);
printf("Enter the age \n");
scanf("%d", &age);
UNIT-6 11
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
Output:
Enter the name
raj
Enter the age
30
Enter the salary
50000
fscanf() fprintf()
fgets() fputs()
fgetc() fputc()
fread() fwrite()
UNIT-6 12
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
• fgetc()
• fread()
(i) fscanf()
The fscanf() is used to read formatted data from the stream. The syntax of the
fscanf() can be given as.
Syntax:
int fscanf(FILE *stream, const char *format,…);
Example:
printf("\n Enter the name and roll number of the student : ");
fscanf(stdin, "%s %d", name, &roll_no); // read from keyboard
(ii) fgets()
• fgets() stands for file get string. The fgets() function is used to get a string from
a stream.
Syntax:
char *fgets(char *str, int size, FILE *stream);
• The fgets() function reads one less than the number of characters specified by
size from the given stream and stores them in the string str.
• The fgets() terminates when newline character or end-of-file or any other error.
• When all the characters are read without any error, a '\0' character is appended
to end the string.
Example:
while (fgets(str, 80, fp) != NULL)
printf("\n %s", str);
(iii) fgetc()
• The fgetc() function returns the next character from stream, or EOF if the end of
file is reached or if there is an error.
Syntax:
int fgetc( FILE *stream );
• fgetc() reads a single character from the current position of a file .
• After reading the character, increment the file pointer to point to the next
character.
Example:
fp = fopen("Program.C", "r");
ch = fgetc(fp); // Read 79 characters and store them in str
UNIT-6 13
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
char buffer[11];
if (f ==fopen("[Link]", “r”))
{
fread(buffer, 1, 10, f);
buffer[10] = 0;
fclose(f);
printf("first 10 characters of the file:\n%s\n", buffer);
}
}
(i) fprintf( )
The fpritnt() is used to write formatted output to stream. Its syntax can be given
as,
Syntax:
int fprintf ( FILE * stream, const char * format, ... );
The parameter format in the fprintf() is nothing but a C string that contains the
text that has to be written on to the stream.
Example:
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n", name);
(ii) fputs()
The fputs() is used to write a line into a file. The syntax of fputs() can be given
as
Syntax:
(iii) fputc()
• The fputc() is used to write a character to the stream.
Syntax:
• The fputc() function will write the byte specified by c (converted to an unsigned
char) to the output stream pointed to by stream.
• Upon successful completion, fputc() will return the value it has written.
Otherwise, in case of error, the function will return EOF and the error indicator for
the stream will be set.
UNIT-6 14
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
Example:
FILE *fp;
char feedback[100];
fp = fopen("[Link]", "w");
gets(feedback);
for(i=0i<feedback[i];i++)
fputc(feedback[i], fp);
Example:
#include <stdio.h>
main()
{
char a[10]={'1','2','3','4','5','6','7','8','9','a'};
FILE *fs;
fs=fopen("[Link]","w");
fwrite(a,1,10,fs);
fclose(fs);
}
4) How to read and write the binary file? Explain with example.
Definition:
In binary files data is in the form of sequence of bytes. There are no lines or new
line character. An EOF marker is used to indicate the end of file.
Binary files have two features that distinguish them from text files:
• Data may be read in any direction.
• Data stored in file are in same format that they are stored in memory.
We can read and write a structure or seek a specific position in the file. A file position
indicator points to record 0 when the file is opened.
struct student
{
char name[50];
int height;
}
main()
{
UNIT-6 15
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
ptr=fopen(“[Link]”,”wb”);
for(i=0;i<3;i++)
{
fflush(stdin);
printf(“\nEnter the name:”);
gets(a[i].name);
printf(“\nEnter the height”);
scanf(“%d”,&a[i].height);
}
fwrite(a,sizeof(a),1,ptr);
fclose(ptr);
ptr=fopen(“[Link]”,”rb”);
fread(b, sizeof(b),1,ptr);
for(i=0;i<5;i++)
{
printf(“Name %s \t Height \n%d,b[i].name,b[i].height”);
}
fclose(ptr);
}
Output:
Enter the name: Sarvesh
Enter the height: 150
Enter the name: Devesh
Enter the height: 145
Enter the name: Selva
Enter the height: 152
Name: Raj Height 150
Name: Rahul Height 145
Name: Ram Height 152
Explanation:
The binary file called [Link] is created. The file is set in write mode by ”wb”. The
fwrite ( ) function is used to write the input into the file with necessary arguments. The
file is closed after performing the write operation. To read the content from the binary file
the fread( ) function is used which reads the content of the file and by using printf()
statement the contents of the file are displayed on the screen.
UNIT-6 16
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
(i) fseek() Mention the purpose of fseek() in random files. [AU-DEC 2023]
It is used to move the reading control to different positions using fseek function.
The fseek() function is used to set the file position indicator for the stream to a new
position.
Syntax:
• The first argument is the FILE stream pointer returned by the fopen() function.
• The second argument ‘offset’ tells the amount of bytes to seek.
• The third argument ‘whence’ tells from where the seek of ‘offset’ number of
bytes is to be done.
Example:
#include <stdio.h>
main()
{
FILE * f;
f = fopen("[Link]", "w");
fputs("Hello World", f);
fseek(f, 6, SEEK_SET);
fputs(" India", f);
fclose(f);
}
Output:
[Link]
Hello India
Explanation:
The file [Link] is created and pointed by the file pointer. The fseek ( ) function
in example seeks from the position 6, and replaces the text “world” with “India”.
(ii) ftell()
It tells the byte location of current position of cursor in file pointer.
"ftell" returns the current position for input or output on the file
Syntax:
ftell(FILE POIN TER);
Example:
#include <stdio.h>
int main(void)
{
FILE *stream;
stream = fopen("[Link]", "w");
fprintf(stream, "This is a test");
UNIT-6 17
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
Example:
rewind(fp);
n=ftell(fp);
(iv) fgetpos()
• The fgetpos() is used to determine the current position of the stream. It’s
prototype can be given as
Syntax:
(v) fsetpos()
• The fsetpos() is used to move the file position indicator of a stream to the
location indicated by the information obtained in "pos" by making a call to the
fgetpos(). Its prototype is
Syntax:
(vi) remove()
• The remove() as the name suggests is used to erase a file. The prototype of
remove() as given in stdio.h can be given as,
Syntax:
UNIT-6 18
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
UNIT-6 19
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
Creating file:
FILE *rf;
• Creates a FILE pointer called cfPtr
UNIT-6 20
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
exit(1);
}
fprintf(fh,"Look what I made!n");
fclose(fh);
}
Example Program:
Finding average of numbers stored in sequential access file
#include <stdio.h>
main ()
{
FILE *input;
int term, sum,avg,count;
sum = 0;
count=0;
input = fopen("[Link]","r");
while(!feof(input))
{
fscanf(input,"%d",&term);
count+=1;
sum = sum + term;
}
avg=sum/count
fclose(input);
Output:
[Link]
5
3
4
1
The sum and average of the numbers is 13 3
UNIT-6 21
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
8) Explain in detail random access in files along with the functions used for the
same in C. Give suitable examples. [AU MAY 2019, DEC 24]
• Access individual records without searching through other records
• Instant access to records in a file
• Data can be inserted without destroying other data
• Data previously stored can be updated or deleted without overwriting
• Implemented using fixed length records but Sequential files do not have fixed
length records.(Refer Figure 6.6).
UNIT-6 22
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
fseek()
This function is used for seeking the pointer position in the file at the specified byte.
Syntax:
fseek( file pointer, displacement, pointer position);
Where
file pointer ---- It is the pointer which points to the file.
displacement ---- It is positive or [Link] is the number of bytes
which are skipped backward (if negative) or forward( if positive) from the current
[Link] is attached with L because this is a long integer.
Pointer position
This sets the pointer position in the file.
Value pointer position
0 Beginning of file
1 Current position
2 End of file
Example:
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file, from this statement
pointer position is skipped 10 bytes from the beginning of the file.
2) fseek( p,5L,1)
1 means current position of the pointer position. From this statement
pointer position is skipped 5 bytes forward from the current position.
3) fseek(p,-5L,1)
From this statement pointer position is skipped 5 bytes backward from the
current position.
ftell()
This function returns the value of the current pointer position in the file. The value is
count from the beginning of the file.
Syntax:
ftell(fptr);
rewind()
This function is used to move the file pointer to the beginning of the given file.
Syntax:
rewind( fptr);
Program to read last ‘n’ characters of the file using appropriate file
functions(Here we need fseek() and fgetc()).
void main()
{
FILE *fp;
char ch;
fp=fopen("file1.c", "r");
UNIT-6 23
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
if(fp==NULL)
else
scanf("%d",&n);
fseek(fp,-n,2);
while((ch=fgetc(fp))!=EOF)
printf("%c\t",ch);
fclose(fp);
#include <stdio.h>
struct clientData
{
unsigned int acctNum;
char lastName[ 15 ];
char firstName[ 10 ];
double balance;
};
main()
{
FILE *cfPtr;
struct clientData client = { 0, "", "", 0.0 };
if ( ( cfPtr = fopen( "[Link]", "rb+" ) ) == NULL )
{
puts( "File could not be opened." );
}
else
{
printf( "%s", "Enter account number ( 1 to 100, 0 to end input )\n " );
scanf( "%d", &[Link] );
while ( [Link] != 0 )
{
printf( "%s", "Enter lastname, firstname, balance\n? " );
fscanf( stdin, "%14s%9s%lf", [Link],[Link],
&[Link] );
fseek( cfPtr, ( [Link] - 1 ) * sizeof( struct clientData ),
SEEK_SET );
fwrite( &client, sizeof( struct clientData ), 1, cfPtr );
UNIT-6 24
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
Output:
Enter account number ( 1 to 100, 0 to end input )
37
Enter lastname, firstname, balance
Barker Doug 0.00
Enter account number
29
Enter lastname, firstname, balance
Brown Nancy -24.54
Enter account number
96
Enter account number
0
FILE POINTERS
Syntax
FILE *ptr;
Here, FILE is the typedef name of the predefined file pointer structure and ptr is
a pointer variable of type FILE.
#include <stdio.h>
int main()
FILE* fptr;
sizeof(FILE));
return 0;
Output:
UNIT-6 25
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
We use a file pointer to refer to the file opened using fopen() function and the
behavior of a file pointer can vary depending on the access modes specified when
opening the file using the fopen() function.
Let's see how the C file pointer works in files with different access modes:
Syntax
FILE *fp;
fp = fopen("fileName", "r");
• The position of the file pointer is initially at the beginning of the file.
• When we read data from a file using functions like fgetc(), fgets(), etc., the file
pointer moves forward automatically to the next position after the read operation.
• We cannot perform write operations using file pointer referring to the file opened
in read mode.
Syntax
FILE *fp;
fp = fopen("fileName", "w");
• If the file exists, the position of the file pointer is initially at the beginning of the
file.
• The existing content in the file is overwritten when we write data to the file.
• When we write data to the file using functions like fputc(), fprintf(), etc., the file
pointer moves forward automatically to the next position after the write
operation.
3. In Append Mode("a")
Syntax
FILE *fp;
fp = fopen("fileName", "a");
• In append mode, the file pointer is positioned at the end of the file.
• The file pointer automatically moves forward to the next position after each write
operation.
Parameters
• offset: The number of bytes to move the file pointer that can be positive or
negative.
UNIT-6 26
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
• origin: The starting point from where the offset is calculated. It can take one of
the following values:
File operations are a common task in C programming, but they can encounter
various errors that need to be handled gracefully. Proper error handling ensures that
your program can handle unexpected situations, such as missing files or insufficient
permissions, without crashing. In this article, we will learn how to handle some common
errors during file operations in C.
Here are some common errors that can occur during file operations:
Error Cause
File not Found Trying to open a file that doesn’t exist.
Permission Denied Insufficient permissions to access the file.
Disk Full No Space Left on the disk for writing data.
File Already Exists Attempting to create a file that already exists in W mode.
Invalid File Using a null or invalid file pointer for file operations.
End of file(EoF) Attempting to read past the end of the file.
File Not Open Attempting to perform operations on a file that wasn’t opened
successfully.
Failure to check for errors then the program may behave abnormally therefore an
unchecked error may result in premature termination for the program or incorrect output
A file not found error can occur when opening a file in read mode (r) or append
mode (a). Use fopen() and check for NULL. If it is, the error message can be printed
using perror() function.
Example:
#include <stdio.h>
int main() {
// read mode
UNIT-6 27
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
// is opened/found
if (file == NULL) {
perror("Error");
return 1;
fclose(file);
return 0;
Output
In the above program, fopen() returns a NULL pointer because the file is not present in
the current directory, then the perror() function prints the error message.
If the file exists but the program lacks the required permissions, fopen() will fail and
return NULL pointer. We can change the perror() output to "permission denied" as shown
in the below snippet.
if (file == NULL) {
perror("Permission denied");
When writing to a file, ensure the disk has enough space. Errors during file
operations can be detected using ferror(). In the below program, we assume that there
is no space in memory to store any data.
Example:
#include <stdio.h>
int main() {
if (fptr == NULL) {
return 1;
UNIT-6 28
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
// write operation
if (ferror(fptr)) {
fclose(fptr);
return 0;
Output
When creating a new file with fopen() in w mode, the existing file will be
overwritten. To avoid this, we open a new file in wx mode because if file is already
present then fopen() return NULL and set the EEXIST value to the errno. In the below
program, we assume that "[Link]" file is already present in current directory.
Example:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main() {
FILE *fptr;
// write mode
if (fptr == NULL) {
if (errno == EEXIST)
UNIT-6 29
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
fclose(fptr);
return 0;
Output
Always verify that the file pointer is not NULL before performing operations like
reading or writing. FILE *file = NULL;
if (file == NULL) {
When we are reading data from a file and the file pointer reaches the end of the
file, we can use the feof() function to handle the end of the file.
#include <stdio.h>
int main() {
char ch;
putchar(ch);
if (feof(file))
else if (ferror(file))
fclose(file);
return 0;
Output
UNIT-6 30
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
Whenever we attempt to open a file and the file cannot be opened due to some
error, the fopen() function returns NULL. We can handle this easily using an if-else
statement.
#include <stdio.h>
int main() {
if (file == NULL) {
} else {
fclose(file);
return 0;
Output
Sometimes, when we are closing a file using the fclose() function and it fails to close the
file due to an error, it returns -1.
#include <stdio.h>
int main() {
if(fclose(fptr) == -1)
else
printf("File closed");
return 0;
Output
UNIT-6 31
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
#include<stdio.h>
void main(int argc, char *argv[])
{
int a,b,c;
if(argc==4)
{
a=atoi(argv[1]);
b=atoi(argv[2]);
c=atoi(argv[3]);
printf("Entered values for A, B and C %d\t%d\t%d\n", a,b,c);
if((a>b) && (a>c))
{
printf("A is largest value \n");
}
else if(b>c)
{
printf("B is largest value \n");
}
else
{
printf("C is largest value \n");
}
}
else
{
printf("enter three argument");
}
}
UNIT-6 32
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
Output
Enter the filename:
[Link]
UNIT-6 33
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
printf("%c", ch);
}
printf("\n");
}
Output:
Enter the file name with extension:[Link]
The original content is:
Ragavan
Raju
Devesh
hseveD
ujaR
navagaR
#include<stdio.h>
main()
{
int n,i;
char *str="abcdefghijklmnopqrstuvwxyz";
FILE *fp;
fp= fopen("[Link]","w");
if(fp==NULL)
{
printf("\nCannot open file.");
exit(0);
}
fprintf(fp,"%s",str);
fclose(fp);
fp = fopen("[Link]","r");
fseek(fp, 3 ,SEEK_SET);
printf("\nText from position %d : \n\t",ftell(fp));
UNIT-6 34
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
Output:
Text from position 3 :
defgh
Text from position 12 :
mnopqr
Text from position 16 :
qrstu
Current position : 21
Text from starting :
abcdefgh
main()
{
int i ;
FILE *fp;
fp = fopen ( "[Link]", "w");
if(fp == NULL)
{
printf ("\nCannot open file.");
exit(0);
}
for(i=0;i<3;i++)
{
printf("Enter name, age, runs of a player : ");
scanf("%s %d %d",[Link], &[Link],&[Link]);
fwrite(&p1,sizeof(p1),1,fp);
}
fclose(fp);
fp = fopen("[Link]","r");
printf("\nRecords Entered : \n");
for(i=0;i<3;i++)
{
UNIT-6 35
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
fread(&p2,sizeof(p2),1,fp);
printf("\nName : %s\nAge : %d\nRuns : %d",[Link],[Link],[Link]);
}
fclose(fp);
}
Output:
Enter name, age, runs of a player :
Sachin
39
700
Records Entered :
Name : Sachin
Age : 39
Runs : 700
Name : Dhoni
Age : 30
Runs : 500
Name : Virat
Age : 25
Runs : 400
15) Write a C program to get name and marks of ‘n’ number of students from
user and store them in a file. [AU-DEC 2022]
#include <stdio.h>
main()
{
FILE *fptr;
char name[50];
int marks[10],i,n,m;
printf("Enter number of students: ");
scanf("%d",&n);
fptr=fopen("C:\\[Link]","w");
if(fptr==NULL)
{
printf("Error!");
exit(1);
}
for (i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
fprintf(fptr,"\nName: %s\n",name);
UNIT-6 36
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
16) Write a C program to read name and marks of ‘n’ number of students from
user and store them in a file. If the file previously exits then append the
information into the existing file. [AU-DEC 2022]
#include <stdio.h>
main()
{
FILE *fptr;
char name[50];
int marks[10],i,n,m;
printf("Enter number of students: ");
scanf("%d",&n);
fptr=fopen("C:\\[Link]","a");
if(fptr==NULL)
{
printf("Error!");
exit(1);
}
for (i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
fprintf(fptr,"\nName: %s\n",name);
printf(“Enter number of subjects:”);
scanf(“%d’,&m);
printf("Enter %d marks: ",m);
for (i=0;i<m;++i)
{
scanf("%d",&marks[i]);
fprintf(fptr,"\nMark %d=%d \n",i+1,marks[i]);
}
}
fclose(fptr);
}
UNIT-6 37
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
typedef struct
{
char name[50];
char aadhaar[13];
char pan[10];
char employment[50];
char gender[10];
int age;
} Application;
Application applications[MAX_CANDIDATES];
int num_applications = fread(applications, sizeof(Application), MAX_CANDIDATES,
input_file);
fclose(input_file);
int num_rejected = 0;
for (int i = 0; i < num_applications; i++) {
if (strcmp(applications[i].gender, "male") == 0 &&
strcmp(applications[i].employment, "self-employed") == 0) {
fwrite(&applications[i], sizeof(Application), 1, output_file);
num_rejected++;
}
}
fclose(output_file);
printf("%d applications rejected and written to %s.\n", num_rejected,
output_filename);
}
int main() {
Application applications[MAX_CANDIDATES];
UNIT-6 38
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
return 0;
}
int main()
{
char sourceFile[100],
destFile[100];
printf("Enter the source file name: ");
scanf("%s", sourceFile);
printf("Enter the destination file name: ");
scanf("%s", destFile);
copyFile(sourceFile, destFile);
return 0;
}
UNIT-6 39
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C
IMPORTANT TOPICS:
UNIT-6 40
MAILAM ENGINEERING COLLEGE UNIT 7
PART A
Using standard libraries like stdio.h, stdlib.h, string.h,
math.h,
Scanf() function is used to read the value from the input device.
getchar() and
putchar().
They are standard file pointers representing input, output, and error
streams respectively.
9. What is getchar()?
b. These functions are used to carry out many of the string manipulations.
#include<stdio.h>
int main() {
char para[100];
printf("Enter Paragraph:");
scanf("%[^\t]s", para); // accept all the characters except tab
printf("Accepted Paragraph: %s", para);
return 0;
}
ceil(x)
sqrt(x)
log(x)
pow(x,y)
sin(x)
Example:
#include "myheader.h"
Example: mathutils.h.
25. Write the steps to create and use a user-defined header file.
The input & output statements are classified into formatted &
unformatted I/O.
a. ceil(x)
b. sqrt(x)
c. log(x)
d. pow(x,y)
e. sin(x)
b. When you use the #include preprocessor directive, the compiler copies
the contents of the header file into your source code.
c. This allows for code reusability and helps organize large programs by
separating declarations from definitions.
• The difference lies in the search path the preprocessor uses to find the file:
• The #include preprocessor directive copies its contents into the source
code.
• The linker resolves the function calls made in your code with the definitions
in the library file.
Create a new text file with a .h extension. In this file, write the
declarations (prototypes) of your functions, classes, or macros.
Include header guards to prevent multiple inclusions.
PART-B
Standard libraries like stdio.h, stdlib.h, string.h, math.h.
Synopsis:
Standard libraries
Standard libraries
TABLE 7.1
TABLE 7.2
TABLE 7.3
Table 7.4
Table 7.5
Table 7.6
Table 7.7
Synopsis:
stdio.h
string.h
math.h
stdlib.h
1. stdio.h:
Definition:
The stdio.h header file stands for Standard Input Output and provides
functions for input and output operations.
#include<stdio.h>int
main()
{
printf("GEEKSFORGEEKS");
return0;
}
Output
2. string.h
Definition:
Strings are defined as an array of characters.
The difference between a character array and a string is that a
string is terminated with a special character ‘\0’.
These string functions make it easier to perform tasks such
as string copy, concatenation, comparison, length, etc.
The <string.h> header file contains these string functions.
Example1: strcat():
char*strcat(char*destination, constchar*source)
#include<stdio.h>#include<strin
g.h>
{
charstr1[100]="Geeks",
str2[100]="ForGeeks";
strcat(str1,str2);
puts(str1);
return 0;
}
Output
Example 2-strlen():
Syntax:
intstrlen(chara[]);
#include
<stdio.h>#include<st
ring.h>int main()
{
chara[20]="Program";
charb[20]={"GeeksforGeeks"};
printf("Lengthofstringa=%zu\n"
strlen(a));
printf("Lengthofstringb=%zu\n"strle
n(b));
return0;
}
Output
Length of string a = 7
3. math.h:
Definition:
All the Functions in this library take double as an argument and return
double as the result.
Syntax-
doublesqrt(doublex)
Example1: sqrt()
#include<math.h>
#include <stdio.h>
int main()
doublenumber,squareRoot;
number = 12.5;
printf("Squarerootof%.2lf=%.2lf",
number,squareRoot); return
0;
Output:
stdlib.h
As we all know that files with extension are called header files in C.
Header files are simply files in which you can declare your own functions
that you can use in your main program or these can be used while writing
large C programs
Creating myhead.h.
1. Creating myhead.h:
Write the below code and then save the file as myhead.h or you can give
any name but the extension should be .h indicating its a header file.
We will also need to include the above header file myhead. has
#include"myhead.h".
The""here are used to instructs the preprocessor to look into the present
folder and into the standard folder of all header files if not found in present
folder.
So, if you wish to use angular brackets instead of "" to include your header
file you can save it in the standard folder of header files otherwise.
If you are using "" you need to ensure that the header file you created is
saved in the same folder in which you will save the C file using this header
file.
Output:
Added value:10
Multiplied value:25
BYE! See you Soon
NOTE: The above code compiles successfully and prints the above output only if
you have created the header file and saved it in the same folder the above c file
is saved.
These functions are not predefined in These functions are predefined in the
1. the Compiler. compiler of C language.
These functions are created by users These functions are not created by
2. as per their own requirements. users as their own.