0% found this document useful (0 votes)
8 views169 pages

C Programming Control Structures Guide

The document outlines Unit II of a Computer Programming course focused on control structures in C, including decision control statements, looping statements, and jump statements. It provides definitions, comparisons, and examples of various control structures such as if, if-else, switch-case, while, and for loops. Additionally, it includes two-mark questions and answers related to these concepts, illustrating their usage and differences.

Uploaded by

silvertitus4
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)
8 views169 pages

C Programming Control Structures Guide

The document outlines Unit II of a Computer Programming course focused on control structures in C, including decision control statements, looping statements, and jump statements. It provides definitions, comparisons, and examples of various control structures such as if, if-else, switch-case, while, and for loops. Additionally, it includes two-mark questions and answers related to these concepts, illustrating their usage and differences.

Uploaded by

silvertitus4
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

MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II

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)

UNIT II - CONTROL STRUCTURE


if, if-else, nested if, switch-case, while, do-while, for, nested loops,
Jump statements.

TWO MARK QUESTIONS WITH ANSWER

CONTROL STRUCTURE

1) What is the control statement? Give examples.


‘C’ language provides all the standard control structure that is available in
programming languages. These structures are capable of processing any information.
These are all the following conditions statements
 if statement
 if...else statement
 nested if...else statement
 if...else ladder or else...if ladder

2) List out the rules for writing switch statement.


 No real numbers are used in expression
 The switch can be nested
 The case keyword must be terminating with colon (:)

3) Compare switch and nested if statement.

Switch case Nested if


Switch can only test constant values. If can evaluate relational and logical
expressions.
In switch case statement nested if can In nested if statement , switch 0 case can be
be used. used.

1
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II

Characters constants are automatically Character constants are automatically converts


converts to integers. to integer.
4) Difference between break and continue statement.
Break Continue
Break statement takes the control to the Continue statement takes the control to the
outside of the loop. beginning of the loop.
It is also used in switch statement. It is used only in loop statement
It is always associated with if condition It is always associated with if condition
loops. loops.

5) Difference between nested if and switch case.


Switch ( ) case Nested if
It can test only constant values. It can evaluate relational or logical expression
Character constant are automatically Character constant are automatically
converted to integers converted to integers.
Switch ( ) case statement nested if can In nested if statement, switch ( ) case
be used statement can be used.

LOOPING STATEMENTS

6) What is looping statements? List out with examples.


Loop is defined as block of statements which are repeatedly executed for certain
number of times. In ‘C’ language there are two types of looping statements are available they
are:
 Conditional looping
 Unconditional looping
Conditional looping:
 While
 do…while
 for
Unconditional looping:
 Switch( ) case
 Break
 Continue
 goto

7) Differentiate: while and do while statement in C.

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--;
}
}

11) Write is the output of the following program?


main()
{
int i,;
i=1,2,3;
printf(“%d”,i);
}
Output: 1

3
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II

12)Differentiate between if and if-else .

Feature if if-else

Execution Executes block if condition Executes one block if true,


is true another if false

Syntax if(condition){} if(condition){ } else { }

Output Only when condition true One of two possible


outputs

13) Write a for loop to calculate the sum of first 10 natural numbers.

#include <stdio.h>

int main() {

int sum = 0;

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

sum += i;

printf("Sum of first 10 natural numbers is %d\n", sum);

return 0;

JUMP STATEMENTS

14) List four jump statements in C.

[Link]

[Link]

[Link]

[Link]

15)What is the use of break in loops?

 break exits the loop immediately, regardless of the loop condition.


 It is often used to stop the loop when a certain condition is met.

4
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II

Example:

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

if(i == 3) break;

printf("%d\n", i);

// Output: 1 2

16) What is the use of continue in loops?

 continue skips the current iteration of the loop and moves to the next iteration.
Example:

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

if(i == 3) continue;

printf("%d\n", i);

// Output: 1 2 4 5

17) What is the role of return statement in a function?

 return is used to send a value back to the calling function.


 It also terminates the execution of the function.
Example:

int sum(int a, int b)

return a + b; // returns the sum to the caller

int main()

int result = sum(5, 10);

printf("%d\n", result); // Output: 15

return 0;

5
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II

18) List out the rules for writing switch statement.


 No real numbers are used in expression
 The switch can be nested
 The case keyword must be terminating with colon (:)
19) Write the syntax of a for loop.

for(initialization; condition; increment/decrement)

// statements to be executed

Example:

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

printf("%d\n", i);

20) What is a nested loop?

 A nested loop is a loop placed inside another loop.


 The inner loop executes completely for every single iteration of the outer loop.
Example:

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

for(int j = 1; j <= 2; j++)

printf("i=%d, j=%d\n", i, j);

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

(ii) if-else statement:


It is otherwise known as Two-way decisions. It is handled with if-else 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 true block will be executed then control goes to the
next executable statement.
 If the test condition is false, the false block will be executed control goes to the next
executable statement.
Syntax: Flowchart

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

(iii) Nested if-else statement


It is otherwise known as Two-way with sub-way decisions. If else statement is
enclosed within another if else structure.

Syntax: Flowchart
if(condition 1)
{
if(condition 2)
{
True statement 2
}
else
{
False statement 2;
}
}
else
{
False statement 1;
}
Next Statement;

Program: Find largest among three numbers.


#include<stdio.h>
main()

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

(iv) if – else ladder


It is otherwise known as Multi-way decisions. Each and every else block will have if
statement. Last else block cannot have if block. Last else will have default statement.
Syntax Flowchart

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 ");
--------
--------

2) Differentiate between if and if-else with examples.

Feature if if-else

Purpose Executes one block if the


Executes code only if the
condition is true, another
condition is true
block if it's false

Structure if (condition) { /* code */ if (condition) { /* code */


} } else { /* alternate code
*/ }

Condition Outcome If true → executes code If true → executes if


block<br>If false → skips block<br>If false →
block executes else block

Fallback Option No fallback; nothing


Provides a fallback block
happens if condition is
when condition is false
false

Control Flow One-way decision Two-way decision

When action is needed for


When action is needed only
Use Case both true and false
for true condition
outcomes

Simpler when only one More flexible for handling


Code Simplicity
condition matters both outcomes

11
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II

Always executes one of


Execution Possibilities Executes zero or one block
two blocks

Checking if a number is Checking if a number is


Example Scenario
positive positive or negative

Grading, eligibility checks,


Common Usage Logging, alerts, validations
binary decisions

Example:

int num = -5;

if(num > 0)

printf("Positive\n");

else

printf("Non-positive\n");

Output:

Non-positive

3) Illustrate switch () case statement in c.


It is an alternative solution for else-if ladder concept. Switch statement is used to
execute a particular group of statements from several groups of statements. It is a multi way
decision statement, test the value of given variable or expression in a list of case values.
Rules of using switch case
 Values for ‘case must’ be integer or character constants.
 Floating point values are not allowed as case label.
 Switch case should have one default label.(optional)
 Const Variable is allowed in switch Case Statement.
 The order of the ‘case’ statements is unimportant.
 Case Label must be unique
 Case labels must have constants / constant expression
 Case labels must end with (:) colon.

12
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II

Empty Switch case is allowed.


Each compound statement of a switch case should contain break statement to exit from
case.
 Two or more cases may share one break statement
 Comparison operators are not accepted
 Nesting (switch within switch) is allowed.
Advantages of Using Switch statement
 Easier to debug
 Faster execution potential
 Easier to read
 Easier to understand
 Easier to maintain

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

o It is a variable used in the loop


 Test condition
 Body of the loop
o Block of statements depends on the test condition
 Updating the counter variable
o Example: Increment/Decrement
Three Types of Looping
(i) while loop
(ii) do-while loop
(iii) for loop
(i) While loop:
It is an ‘entry control loop’ statement. The body of the loop is executed until the
condition will occur false.
It is also known as ‘top-tested loop’ or ‘pre-tested loop’.

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

ii) do…while loop:


The while loop makes a test of condition before the loop is executed. Body of the loop
may not be executed at all only if the condition is not satisfied at first attempt.
It is also known as ‘bottom-tested loop’ or ‘post-tested loop’.
Syntax: Flowchart
do
{
…..
Body of loop;
…..
}while(condition);

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

(iii) for loop:


For loop is another repetitive control structure and it is used to execute set of instructions
repeatedly until the condition becomes false. It is also known as ‘top-tested loop’ or ‘pre-
tested loop’.
Syntax: Flowchart

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

COMPARISON OF WHILE AND DO-WHILE


 The loop construct iterates over a set of statements. The iteration is either range based
or it depends on a condition.
 This condition is checked every time, if it's true then the statements are executed, if
false then the loop is terminated and the control moves on to the next statement after
the loop. int main()
Entry Controlled Loop
{ for (counter=5; counter>0; counter--)
int counter=5; {
while(counter>0) printf("\n%d", counter);
printf ("\n%d", counter); return 0;
counter--; }
}
Exit Controlled Loop
There is a different loop constructs called exit controlled. This checks the condition at
the end of the block of statements of loop, instead at the beginning.
Example:
main( )
{
int counter=5;
do
{
printf ("\n%d", counter);
counter--;
} while(counter>1); //condition is checked in the end.
}
Difference between entry controlled loop and exit controlled loop:
Entry Controlled Loop Exit controlled loop
An entry control loop would run zero or more The exit controlled loop would run at least
times depending on the result of the once irrespective of the result of conditional
evaluation of the conditional expression. expressions evaluation because the first time
the condition is checked, the block of
statements has already been executed once.

18
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II

5) Differentiate between while and do-while loop.

Feature while do-while

Checked before loop body Checked after loop body


Condition Check
executes executes

Minimum Execution May execute zero times Executes at least once

Syntax while(condition) { ... } do { ... } while(condition);

When you want to check When you want to run at


Use Case
before execution least once

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:

(no output, because condition is false initially)

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

6) Explain nested loops with an example program to display a star pattern.

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
}
}

Example: Star Pattern in C

Let's create a right-angled triangle of stars:

#include <stdio.h>

int main() {
int rows = 5;

for (int i = 1; i <= rows; i++) { // Outer loop for rows


for (int j = 1; j <= i; j++) { // Inner loop for stars
printf("*");
}
printf("\n"); // Move to next line
}

return 0;

20
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II

Output:

// *

// **

// ***

// ****

// *****

7) Briefly explain the unconditional looping statements in c.


 Break
 Continue
 Goto
(i) break statement:
1. It is used to terminate the loop. When the keyword break is used inside any ‘C’
loop,control automatically transferred to first statement after the loop.
2. A break is usually associated with an if statement.
Syntax:
break;

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

(ii) Continue statement:


It is mainly used to take the control to the beginning of the loop, for these purposes
continue statement is used.
When the statements continue is used inside any ‘C’ loop, control automatically passes
to the beginning of the loop.
It is also associated with if statement.

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

(iii) Goto statement:


 It is used to transfer control unconditionally from one place to another place.
 A goto statement can cause program control almost anywhere in the program
unconditionally.
 It requires a label to identify the place to move the execution.
 A label is a valid variable name and must be ended with colon (:).

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

8)Explain jump statements (break, continue, goto, return) with example


Programs using C language.

Jump statements in C control the flow of execution by transferring control to another


part of the program.

i) break: Used to exit a loop or switch statement prematurely.


Program: Break in a loop

#include <stdio.h>

int main() {

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

if (i == 5) {

break; // Exit loop when i is 5

printf("%d ", i);

return 0;

Output: 1 2 3 4

ii) continue: Skips the current iteration and jumps to the next iteration of the loop.

Program: Continue in a loop

#include <stdio.h>

int main() {

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

24
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II

if (i == 3) {

continue; // Skip printing 3

printf("%d ", i);

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.

Program: Goto usage

#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.

Program: Return from a function

#include <stdio.h>

int add(int a, int b) {

25
MAILAM ENGINEERING COLLEGE CS25C01 - COMPUTER PROGRAMMING: C UNIT II

return a + b; // Return sum


}

int main() {
int result = add(3, 4);
printf("Sum: %d", result);
return 0;
}

Output: Sum: 7

9) Program using for loop to print multiplication table of a number.

Example:

#include <stdio.h>

int main() {
int num;

// Ask user for input


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

// Print multiplication table


for (int i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", num, i, num * i);
}

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

10) Write a c program to find the sum of 10 non-negative numbers entered


by the user. [AU MAY 2019]

#include <stdio.h>
#define MAX 100

int main()
{
int arr[MAX];
int i, n, sum=0;

printf("Enter size of the array: ");


scanf("%d", &n);

printf("Enter %d elements in the array: ", n);


for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}

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


{
sum = sum + arr[i];
}

printf("Sum of all elements of array = %d", sum);

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 age: ");


scanf("%d", &age);

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");

13) Is it possible to convert ‘if-else’ ladder to ‘switch....case’ statements? If


yes, illustrate with an example. If no, justify the reason.
Answer:
Yes.
Program for else if:
#include <stdio.h>
main()
{
int choice;

printf("Choose a color (1=Red, 2=Green, 3=Blue): ");


scanf("%d", &choice);

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;

printf("Choose a color (1=Red, 2=Green, 3=Blue): ");


scanf("%d", &choice);
switch (choice)
MAILAM ENGINEERING COLLEGE UNIT II CS25C01-COMPUTER PROGRAMMING IN C

{
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)

CS25C01 COMPUTER PROGRAMMING: C

UNIT III FUNCTIONS


Function Declaration, Definition and Calling, Function Parameters and Return Types,
Call by Value and Call by Reference, Recursive Functions, Scope and Lifetime of
Variables, Header files and Modular Programming.

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…

3) How pow() is defined and which header file provides it?


The pow() function is defined in the math.h header [Link] is used to calculate the power of a
number.
4) What are the elements of user-defined function? (or) What is the need of function?
 Function Definition
 Function Declaration & Function Call

5) State the advantages of user defined functions over pre-defined functions.


• The length of the source program can be reduced by dividing into the smaller function.
• It is very easy to locate and debug an error.
• It can be used in many other programs whenever necessary.
• Reduce the length of the program

6) What is difference between library function and user-defined function?


Library functions are the functions which are already written in some standard libraries.
User defined function means the function which are written by the user to perform particular task.

1
Unit 3
CS25C01 COMPUTER PROGRAMMING:C

DEFINITION AND CALLING

7) What is function prototyping? Why it is necessary?(or) What is function prototype?


Give an example.
Function prototype is otherwise known as “function declaration”. It is necessary to
declared before they defined and invoked.
Example: intsum(int,int);/*Function prototype*/

8) List out the types of function prototype.


a. Function with no arguments and no return values.
b. Function with no arguments and return values.
c. Function with arguments and no return values.
d. Function with arguments and return values.

9) Define function definition and function call.


Function Definition: It provides the actual body of the function. It is also refered as “called
function block”.
Function Call: It is mentioned inside the program whenever it is required to call
a function. It is only called by its name in the main() function of a program.

FUNCTION PARAMETERS AND RETURN TYPES

10) What is a parameter in a C function?


A parameter (formal parameter) is a variable declared in the function definition
(inside ()) which acts as a placeholder for the value passed when the function is called.

11) What is call by value in C?


In call by value, a copy of the actual parameter is passed to the function. Changes made inside the
function do not affect the original variable..

12) Can a function in C have no parameters? Give an example.


Afunction can have no parameters.
Example:
void greet()
{
printf("Hello!");
}

13) What is The Purpose of a Return Type 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.

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.

CALL BY VALUE AND CALL BY REFERENCE

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

16) Differentiate:Pass by value and pass by reference.


Pass byValue PassbyReference
When a new location is created it is The existing memory location is used
Very slow. Through its address,it very fast.
Values of the actual arguments are Addresses of the actual arguments
Passed to the formal arguments. Are passed to the formal arguments.
Different memory locations are Same memory location occupied.
occupied.
There is no possibility of wrong data There is a possibility of wrong data
manipulation. manipulation.
The change made in the formal arguments The change made in the formal arguments
does not affect the actual affects the actual
arguments. arguments.

17) What is the purpose of the return statement?


The purpose of the return statement is, the return statement may or may not send back any
values to the main program (calling program). If it does, it can be done using the return statement.

18) Define a C function to exchange the content of two variables.


Voide x change(int*a,int*b)
{
int
c;
c=*
a;
*a=*b;
*b=c;
}

19) What is the output of the following code fragment?

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:

Value of x is: 456 Value of *p1 is: 456


Value of *p2 is: -1099537668

20) What is Call by Value and Call by Reference in C?

 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

21) Define the term recursion in language C.


In C it is possible to call a function by itself. Recursion is a process by which a function calls
itself repeatedly until some specified condition has been satisfied.
Example:
intfact(intn)
{
if(n==0)
return1;
else
return n*fact(n-1)
}

22)What are the Applications of Recursive Function?


 Calculating Fibonacci Series.
 Calculating factorial of a program.
 Tower of Hanoi.

23)List the Advantages of Recursion.


 It is written with less number of statements.
 Recursive functions are effective where the terms are generated successively to compute a
value.
 It requires few variables which requires program clean.
 It is useful for branching processes.
24) List out the Disadvantages of Recursive Function.
 It is also difficult to debug the code containing recursion.
 It is hard to think the logic of are cursive function.

SCOPE AND LIFETIME OF VARIABLES

25) What is the Scope and Lifetime of Variables in C functions?


 Scope is the region of the program where a variable can be accessed.
Example: Local variables have scope within the function only.
 Lifetime is the duration for which the variable exists in memory.
Example: Local variables exist only during function execution.
4
Unit 3
CS25C01 COMPUTER PROGRAMMING:C

26) Define scope and lifetime of a variable in C.


o Scope is where the variable can be accessed in the program.
o Lifetime is how long the variable exists in memory during program execution.

27) What is a local variable? How is it different from a global variable?


o A local variable is declared inside a function and accessible only within that
function.
o A global variable is declared outside all functions and accessible throughout the program

28) What is a static variable in C? Explain its lifetime and scope.


o A static variable inside a function retains its value between function calls.
o Its scope is local to the function, but its lifetime is the entire program execution.

HEADER FILES AND MODULAR PROGRAMMING


29) What is the purpose of header files in C?
Header files in C contain function declarations, macros, and constants which are shared between multiple
source files. They help in code reuse and organizing the program by providing interfaces to
Functions and libraries.

30) What is modular programming?


Modular programming is a technique where a program is divided into separate, independent modules or
functions. Each module performs a specific task, making the program easier to understand, debug, and
maintain.

31) What are the types of header files in C?


 Standard Header Files: Provided by the C compiler, like <stdio.h>,<stdlib.h>, <math.h>, which
contain standard library functions.
 User-defined Header Files: Created by programmers to declare their own functions and macros,
typically included using double quotes like "my header.h".

32) Differentiate between user-defined and standard header files.


 User-defined header files are created by the programmer.
(e.g., myheader.h).
 Standard header files are provided by the compiler.
(e.g., stdio.h).
33) What is the need for modularization in software development?
 Modularization improves code organization,
 simplifies testing,
 enables team collaboration, and
 enhances maintainability.

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

1) What is a function? Briefly explain about user-defined functions.


The C language is allowing the use of functions, self-contained "modules" of code that take
inputs (raw data), do a computation, and produce a new piece of information based on the
parameter information.
“Function is a block of statement that is used to execute for a specific task which repeatedly
occurs in the main program. This is known as function”.
Purpose
 To improve re-usability
 Modularity (Understandability and to keep track on them)
Types
In general, functions are classified in to two types. They are given below.
Types of Functions

Library functions User-defined


(or) function
Pre-defined

[Link].3.1 Types of funtions

Example for predefined functions are sqrt(),pow(),tan() and etc….

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.

Advantages of user defined functions:


 A large C program can easily be tracked when it is divided into functions.
 All C functions are used to avoid rewriting same logic/code again and again in a
program.
 There is no limit in calling C functions to make use of same functionality wherever
required.
 We can call functions any number of times in a program and from any place in a
program.
 The core concept of C functions is, re-usability, dividing a big task into small pieces to
6
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
achieve the functionality and to improve understandability of very large C programs.

Need for User-Defined Functions


 Function declaration (Function prototype)
 Function call (Calling function)
 Function definition.

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);

It have three segments,they are


a. Return type (Function name)
b. Function name
c. 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);

iii) Function Definition


Function definition consists of two parts, they are given below.
 Function header.
 Function body.

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);

c=sum(a,b); /* Function Call */

Actual arguments

printf(“\n Answer is%d”,c);


}
Formal arguments

intsum(intx,inty) /*Called Function*/


{
int z;
z=x+y;;
return(z); /*Return statement*/
}

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()
{ {

sample(); No return values ------------

----------------- }
}

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

(ii) Functions with Arguments and No Return Values


The nature of data communication between the calling function and the called function
with arguments but no return values.
i.e.,
 The arguments are passed through the function call.
 The called function receives and operates the value.
 But no result is sent to main() function.
Let see the general form.

Calling Function Called Function

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

(iii) Function with No Arguments and Return Values


A called function does not receive any data from the calling function but the called function
will return some values to calling function.

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

(iv)Function with Arguments and Return Values


This is a two-way data communication between the calling and the called function.

Calling Function Called Function


main() With arguments sample(x,y)
{ {

c=sample(a,b); Return values return(z);

} }

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()

FUNCTION PARAMETERS AND RETURN TYPES


4) What is the necessity of parameter passing in C programs? What are the two types of doing
that? Explain any one in detail.
(Or)
Explain the concept of pass by value and pass by reference. Write a C program to swap the content of
two variables using pass by reference.
In C language, a Parameter is the symbolic name for "data" that goes in to a function.
There are two types of parameters in C, they are
i) Pass by Value(or) Call by Value.
ii) Pass by Reference(or)Call by Reference.
Let see one by one as follows,

(i) Pass by Value(or)Call by Value.


This method is otherwise known as ‘Call by Value’.
When the value is passed directly to the function it is called call by value. In call by value
only a copy of the variable is only passed so any changes made to the variable does not reflects in
the calling function.
Example:
Actual arguments

c=add(a,b); Calling function

Values are copied

int add(int x,int y) Called function

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);
}

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

(ii) Pass by Reference (or) Call by Reference


This method is otherwise known as ‘Call by Address’(or)‘Pass by Address’.
When the address of the value is passed to the function it is called call by reference. In call
by reference since the address of the value is passed any changes made to the value reflects in the
calling function.

Example:
Actual arguments

swap(&a,&b); Calling function

Addresses are copied

void swap(int*x,int*y) Called function

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

Difference between call by value and call by reference:

[Link] Call by value Call by reference


Different memory locations are Same memory location occupied by formal and
1 occupied by formal and actual actual arguments, so there is a saving of
arguments Memory location.
Only the value of the variable is The address of the variable is passed as
2
Passed as an arguments arguments.
When a new location is created, it The existing memory location is used through its
3
is very slow. address, it is very fast.
4 There is no possibility of wrong There is a Wrong Data Manipulation
Data manipulation

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.

III. Function Call


In order to use the function, we need to invoke it at a required place in the program. This is
known as the function call.

6) Write some properties and advantages of user defined functions in C.


Properties of Functions
 Every function has a unique name. This name is used to call function from “main()”
function.
 A function performs a specific task.
 A function returns a value to the calling program.
Advantages of Functions in C
 Functions has top down programming model. In this style of programming, the high level
logic of the overall problem is solved first while the details of each lower level functions is
solved later.
 A C programmer can use function written by others
 Debugging is easier in function
16
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
 It is easier to understand the logic involved in the program
 Testing is easier

CALL BY VALUE AND CALL BY REFERENCE

7) Explain the Parameter Passing Mechanisms in C-Language with examples.


Most programming languages have 2 strategies to pass parameters. They are
(i) pass by value
(ii) pass by reference

(i) Pass by value (or) call by value: -


In this method calling function sends a copy of actual values to called function, but the changes in
called function does not reflect the original values of calling function.
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;
}

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.

8) Differentiate actual parameters and formal parameters.

Actual parameters Formal parameters

Actual parameters Formal parameters

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

9) Briefly explain the logic of recursion with example.

 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’.

 In other term, it is in ‘a potential cycle of function calls’.

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

a=4,we call factorial(4)


Since a=4 or 0, f=x*factorial(x-1)
Factorial=4*fact(3)(again call fact function with x=3)
=4*3*fact(2)(again call fact function with x=2)
=4*3*2*fact(1)(again call fact function with x=1)
=4*3*2*1(terminating condition)
=24

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.

10) Write a program to find factorial of a number using recursion.


#include<stdio.h>
int fact(int);
main()
{
int n,f;
printf(“\n Enter any
number:”); scanf(“%d”,&n);
f=fact(n);
printf(“\n Factorial of %d is %d”,n,f);
}
int fact(int n)
{
int f;
if(n==0||n==1) //base case
f=1;
else
f=n*fact(n-1); //recursive case
return f;
}
Output:-Enter any number: 5
Factorial of 5 is 120
SCOPE AND LIFETIME OF VARIABLES

11) What is Scope of Variables in C?


 Scope of variables in C language refers to the region or part of the code where a variable can be
accessed or used. It defines the visibility of a variable within different parts of a program.
For example:
 If a variable is declared inside a function, it can only be used within that function, and this is called
local scope.
 If a variable is declared outside of all functions, it can be accessed from anywhere in the program,
and this is known as global scope.
 Simply put, scope determines where in the program a variable is available for use.
Types of Scope of Variables in C
 Variables in C programming have different scopes depending on where and how they are declared.
Learning these scopes is essential for managing variable visibility and lifetime throughout the
program.
1. Local Scope
 A variable has local scope when it is declared inside a function or block (within {} braces). This
means that the variable is accessible only within that function or block and is not visible to other
parts of the program.
 Function-Level Scope: Variables declared inside a function are accessible only within that
function.
 Block-Level Scope: Variables declared inside a block (such as within an if statement or a loop) are
accessible only within that block.

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

printf("Global variable in function2: %d\n", globalVar);

int main() {

function1(); // Accesses globalVar


function2(); // Modifies and accesses globalVar

return 0;}

HEADER FILES AND MODULAR PROGRAMMING

12) Explain the concept of Header Files and Modular Programming in C.


Header Files:
 Header files in C/C++ are files with the .h or .hpp extension that contain function declarations, macro
definitions, constants, and sometimes class declarations. They do not contain function definitions
(logic) – that’s done in the .c or .cpp files.

Purpose of header files:

 Code Reusability: Share declarations across multiple source files.


 Avoid Redundancy: Write a function declaration once and reuse it.
 Improve Readability: Keeps the source code clean by separating interface from implementation.
 Simplify Maintenance: Changes in declarations are made only in one place (the header file).

#include <stdio.h>

// ----------- Simulated Header File (mathutils.h) -----------


// Normally, this would be in a separate file
#ifndef MATHUTILS_H
21
Unit 3
CS25C01 COMPUTER PROGRAMMING:C
#define MATHUTILS_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
// -----------------------------------------------------------

// ----------- Simulated Source File (mathutils.c) -----------


// Function definitions
int add(int a, int b) {
return a + b;
}

int subtract(int a, int b) {


return a - b;
}

int multiply(int a, int b) {


return a * b;
}

float divide(int a, int b) {


if (b == 0) {
printf("Error: Division by zero!\n");
return 0.0;
}
return (float)a / b;
}
// -----------------------------------------------------------

// ---------------------- Main Program ------------------------


int main() {
int a = 20, b = 10;

printf("a = %d, b = %d\n", a, b);


printf("Addition: %d\n", add(a, b));
printf("Subtraction: %d\n", subtract(a, b));
printf("Multiplication: %d\n", multiply(a, b));
printf("Division: %.2f\n", divide(a, b));

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.

 The type of an array is the data type of its elements.


 The array elements are storest in continuous memory Incations.
 The location of an array is the location of its first element
6) Define one dimensional array.
The collection of data item can be stored under a one vanabile name using only
one subscript, such a variable is called one-dimensional array
Example:
int a[10];
7) What is two dimensional array? Give an example for initialization of a 20 array
with a set of values.
An array with two subscripts is termed as two-dimensional array A two
dimensional array enables us to store multiple rows of elements
Initialization:
int arr[2][2]={
{1.2},
{3,4}
};
8) Write down the syntax for array declaration.
One Dimensional Array:
datatype arrayname[size];
Two Dimensional Arrays:
datatype arrayname[rows] [columns];
Multi-Dimensional Arrays:
datatype arrayname[s1][s2]...[sn];
9) Write syntax for multi-dimensional array.
Syntax:
datatype arrayname[st][s2]...[sn];
Example:
int table[6][4][3][2];
10) What are the different ways of initialization array?
An array can be initialized at the time of declaration is known as compile time
initialization.
Example:

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 2


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

int a[5]= {5,8,7,4,1}; \\ An array can be explicitly initialized at run time.


for(i=0;i<5;i++)
scanf("%d",&a[i]);
11) What is the value of b[0] in the following program?
main()
{
int a[5]={1,3,6,7,0), *b;
b=&a[2];
}
Output: 6.
12) Declare a float array of size 5 and assign 5 values to it.
float a[5]={12.5,0.234,45.67,6.7,89.6} (or)
float a[5]={12.5,0.234,45.67,6.7,89.6}
13) What is the output of the following code?
main()
{
int a[4]={1,2,3,4};
a++;
printf("%d", *a);
}
Output: error: Ivalue required as increment operand
14) What is the minimum index of an array? (Or) What is the starting index of an
array?
The minimum index of a one-dimensional array is 0(zero), which marks the first
element of the array.
Example:
int a[8];
The first element of the array is a[0]. Likewise, for a multidimensional array, the
minimum index of each dimension starts at 0(zero).

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';

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 3


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

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

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 4


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

printf("Both are not equal");


}

24) Declare a character array of size 5 and assign vowels to it.


type array_name[size]={value_list};
Example: char vowel[6]={'a', 'e',’i’,’o’,’u’,’\o’};
25) Give some examples of string functions.
(or) Write any two string handling functions in C with their syntax and purpose.
Strlen() find the length of a string
char str1[20] "Beginners Book";
printf("Length of string str1: %d", strlen(str1));
Strcat()
char s1[10] "Hello";
char s2[10] "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", 51);
Strcpy()
char $1[30]="string 1";
char s2[30] "string 2: I'm gonna copied into s1";
strcpy(s1,s2);
printf("String s1 is: %s", 51);
25) What are the Features (or) Advantages of Using Pointers?
 Pointers also provide an alternative way to access an array element.
 Pointers can be used to achieve clarity and simplicity.
 Pointers enable us to access the memory directly.
 Pointers are more compact and efficient code.
 Pointers are used to pass information between function
 It helps to save memory space and to increase the execution speed of the
program.

26) What is Null Pointers?


A null pointer is a regular pointer of any pointer type which has a special value
that indicates that it is not pointing to any valid reference or memory address. This value
is the result of type-casting the integer value zero to any pointer type.
Example:
int *p;
p = 0 //phas a null pointer value

27) When null pointer is used?[AU MAY 2018]

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 5


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

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.

POINTERS, POINTERS OPERATORS AND POINTERS ARITHMETIC


30) What are pointers?
Pointer is a variable which is used to store address of another variable. It is
declared same as other variable but it must be denoted by operator preceding the
variable name.
Eg.
int *a,b=10;
b=&a;

31) What is the output of following programs?

#include<stdio.h>
PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 6
CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

void fun(int *ptr)


{

*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.

Dynamic Memory Allocations(DMA)


33)What is Dynamic Memory Allocation (DMA)?
(OR)
In language C can we allocate memory dynamically? How?
DMA stands for Dynamic Memory Allocation, DMA allows us to allocate
memory at run time. Using the concept of DMA you can allocate exact memory for the
variables. Here are the functions that are used to allocate or free the memory at run time:
malloc(): To allocate dynamic memory for one dimensional array i.e. contiguous
memory allocation.
calloc(): To allocate dynamic memory for two dimensional array i.e. memory
allocates in row and column manner.
realloc(): Τo re allocate dynamic memory.
free(): To free dynamically allocated memory.
34)Write down the Difference between static memory allocation and dynamic
memory allocation

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 7


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

35)Write down the Difference between malloc and calloc functions in c.

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*).

37) Write the advantages of dynamic memory allocation.


 It has the ability to reserve or allocate additional memory space during the
program execution.

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 8


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

 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.

38) What is the use of malloc()? Give its syntax.


It is used to allocate block of memory 1.e., it allocates a block of memory
of specified size and return a pointer of type void.
Syntax:
pointer variabie (type cast*)malloc(size in bytes);
39) What is memory leak in C?
Memory leak is really a panic, the insufficient memory/ memory resources leaks are
known as memory leaks. Memory leak occurs when program does not manage the
memory allocation correctly. >
40) What is dangling pointer?
In C, a pointer may be used to hold the address of dynamically allocated
memory. After this memory is freed with the free() function, the pointer itself will still
contain the address of the released block. This is referred to as a dangling pointer.
Using the pointer in this state is a serious programming error. Pointer should be
assigned NULL after freeing memory to avoid this bug.

ARRAY – DECLARATION & INITIALIZATION


PART - B
1) What is an array? Explain about various types of arrays in detail with
example.
(or) What is an array? Explain about one dimensional array with a sample
program.
"An array is a group of related data items that share a common name. The value is
indicated by writing a number called index (subscript) in brackets after the array
name." This is called an array.
Types of array
One Dimensional Array
Two Dimensional Array
Multi Dimensional Array

(a) One Dimensional Array


An array with a single subscript is known as one dimensional array. It is
used to allocate continuous memory location.

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 9


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

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

datatype array-name[size] = {list of values};


Example: int rollno[3] = {26,32,12};
 The value of array are enclosed in braces and separated by commas.
 The values are assigned to the array by assignment operator (=).
 If the number of values in the list is less than the number of elements, then only
that many elements will be initialized.
 The remaining elements will be set to zero automatically.
(ii) Run time Initialization
When the users have to initialize more number of elements means it is difficult
to use compile time initialization. To avoid this situation the user can initialize
elements in runtime.
Program
/*Program showing one-dimensional array*/
#include<stdio.h>
main()
{
int a[100],sum=0,i,n;
printf("Enter no. of terms:");
scanf("%d",&n);

printf("Enter %d integer numbers\n",n);


for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
//Run time Initialization
}
sum=sum+a[i];
printf("The sum of given numbers is: %d\n",sum);
}
Note: The entire sorting & searching algorithm must use the one-dimensional

ONE DIMENSIONAL ARRAY


2) How will passing one dimensional array to function? Explain with example.
(Or) Arrays as function arguments.
User can pass an array element or an entire array as argument to a function.
Passing an entire array as argument is some differ from passing its individual elements
as arguments.
(1) Passing individual elements
We can pass individual elements to a function like any other variable. The type
of array element matches the function parameter type, it can be passed. This method
passes the value of the array element. Since it is a passed by value, the function cannot
change the original value of the array element.
Program

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 11


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

ii) Passing the entire array


An entire array can be transferred to a function as a parameter. To transfe
function, the array name is enough without subscripts as actual paramete nction call.
Program
#include<stdio.h>
void sum(int,int[]);
main()
{
int a[5],i,n=5;
printf("Enter 5 elements: \n");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);

sum(n,a);
}
void sum(int x,int b[])
{
int add=0,1;
for(i=0;i<5;i++)
{
add=add+b[i];

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 12


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

}
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

3) Illustrate two-dimensional arrays with example.


Arrays whose elements are specified by two subscripts are called Two-
dimensional arrays (or) double-subscripted arrays.
Syntax:
datatype array-name[row_size] [column_size];
Example:
int a[3][3];

The pictorial representation of the above example.

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 ++)

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 13


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

{
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:

a) Compile time initialization


b) Run time initialization.

a) Compile time initialization.


The two dimensional array can be initialized at the time of declaration is known
as Compile time initialization.
Example:
int a[2][3]={1,1,1,3,3,3);
int a[2][3]={
{1,1,1),
(3,3,3)
};
This statement will initialize the elements of first row to 1 and second row to 3.
int a[2][]={1,1,1,3,3,3);
int a[][]={1,1,1,3,3,3);

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 14


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

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>

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 15


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

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

(ii) strcmp() Function String Comparison


It is used to compare two strings identified by the arguments and has a value are
equal.
Syntax:
strcmp(string1,string2);
Example:
strcmp(name1, name2);
strcmp(name1,"john";

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:");

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 16


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

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

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 17


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

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

(V) strrev() Function - String Reverse


This function is used to find the reverse of the given string.
Syntax:
strrev(string);
Example:

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 18


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

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

C pointer is an address which is a numeric value. Therefore, you can perform


arithmetic operations on a pointer just as you can a numeric value. There are four
arithmetic operators that can be used on pointers :++,--,+ and - .
(i) Incrementing a pointer
The following program increments the variable pointer to access each
succeedingelement of the array:
#include <stdio.h> const int MAX = 3.
main ()
{

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 19


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

int var[] ={10, 100, 200};


int i, *ptr;
/* let us have array address in pointer */
ptr = var;
for (10:1 < MAX; I++)
{
printf("Address of var[%d] = %x\n", i, ptr);
printf("Value of var[%d] = %d\n", i, *ptr);
/ move to the next location */
ptr++;
}
}
Output:
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Value of var[2] = 200
(ii) Decrementing a pointer
The same considerations apply to decrementing a pointer, which decrease value
by the number of bytes of its data type as shown below:
#include <stdio.h> const int MAX = 3.
main ()
{
int var[] ={10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = var;
for (10:1 < MAX; i--)
{
printf("Address of var[%d] = %x\n", i, ptr);
printf("Value of var[%d] = %d\n", i, *ptr);
/ move to the next location */
Ptr--;
}
}

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

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 20


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

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=&num;
ptr2=ptr1+2;
printf("difference is: %d", ptr2-ptr1);
}
Output:
difference is : 2

POINTERS AND ARRAYS


6) Briefly explain the concept of arrays and pointers in detail with example.
When users declare an array the consecutive memory locations are located to the
elements of an array can be efficiently accessed by using pointers.
Example:
int a[5]={10,20,30,40,50}.
Here, a' has 5 elements

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 21


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

 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()
{

int i, total, a[5] ,* c ;


for ( l = 0; l < 5 ;i++)
{
printf("\nEnter the number %d:" ,i+1)
scanf("%d",&a[i]);
}
C=a;
for(i=0;i<5;i++)
{
total total+c;
c=c+1;
}
printf("\n Total=%d", total);
}

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];

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 22


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

char *name[] = { "Illegal month", "Jan", "Feb", "Mar"};


name:

with those for a two-dimensional array:


char aname[][15] = { "Illegal month", "Jan", "Feb", "Mar" };
name[15] ("regal morth","","","

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 23


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

7)Explain about Pointers to Pointers?

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 24


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

8) How array of pointers will act in c? Explain.


A pointer is a vanabile that contains the memory location of values you assign
to the pointers are memory addresses of other A running program gets a certain space
in the main memory The
Syntax:
data_type_name* variable name;
The asterisk tells the compiler that you are creating a pointer variable. Then
specify the of variable.
Example:
#include <stdio.h>
main()
{ int *array[3];
int x = 10 ,y = 20, z = 30;
int i; array[0] = &x;
array[1] = &y;
array[2] = &z;

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 25


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

for i = 0 i < 3 i ++)


{
printf("The value of %d %d, address is %u\t \n", i, *(array[i]),array[i]);
}
}

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

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 26


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

DYNAMIC MEMORY ALLOCATION


9) What is dynamic memory allocation?Explain various c functions that are used for
the same with example.
A program can obtain its memory while it is running. It allows us to allocate additional
memory space or to release unwanted space at the time of program execution. This is known as
ynamic allocation in C.

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 27


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 28


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

10)Write c program to calculate matrix addition.

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 29


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

11)Convert the given string from lower case character to upper case and upper

case to lower case.

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 30


CS25C01 - C MAILAM ENGINEERING COLLEGE UNIT-IV

12)Program for Vowels & consonants and palindrome.

PREPARED BY: MRS. M. VIJAYALAKSMI, AP/IT 31


MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5

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

[Link] structure with syntax. (OR)


What is meant by structure definition? [AU-DEC 2022]
C supports a constructed data type known as structures, a mechanism for packing data of
different types. A structure is a convenient tool for handling a group of logically related data
items. This is known as Structure.
Syntax:
struct structure__name
{
data_type member1;
data_type member2;
data_type memeber;
};

[Link] the rules for declaring a structure.


● A structure must end with a semicolon.
● Usually a structure appears at the top of a program.
● Each element of structure must be terminated.
● The structure variable must be accessed by using dot (.) operator.

3. What are the characteristics of structure?


● User-defined data type
● Grouping diverse data types
● Representing real-world entities
● Memory allocation
● Accessing members:

4. Write the rules for initializing structure.


● The individual data members of structure cannot be initialized.
● The structure variables can be initialized at compile time only.
● The order of data members in a structure must match the order of values in enclosed
brackets.
● We can initialize only some of the data members of the structure.

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]; }

6. Compare and contrast a structure with an array. [AU-MAY 2019]

Arrays Structures
S.N
o

1 An array is a collection of data items of A structure is a collection of data items of


same data type. different data types.

2 Arrays can only be declared. Structures can be declared and defined.

3 There is no keyword for arrays. The keyword for structures is struct.

4 An array name represents the address of structure name is known as tag. It is a


the starting element. shorthand notation of the declaration.

5 An array cannot have bit fields. A structure may contain bit fields.

7. What is nested structure?


• Structure written inside another structure is called as nesting of two structures.
• We can write one Structure inside another structure as member of another
structure.
Syntax:
struct structure1
{
-----------
---------
};
struct structure2
{
----------
----------
struct structure1 obj;
};

8. Define pointer to structures.


A pointer pointing to a structure is called structure pointer. Pointers and structures in C
together help in accessing structure members efficiently A structure pointer is declared
similar to a pointer for other data types
General syntax:

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)

9. Why Use Structure Pointers?


● 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.

10. Define array of structure.


An array of structures is the same way as we declare an array of built-in data type. The
array of structures can be used when common structure definition is need for the process
of information.
Syntax
struct struct_name struct_var[index];
Example
struct student stud[30];

11. Why we use array of structure in c?


● Structures allow grouping of different data types; arrays of structures organize
multiple records of the same format
● Elements are accessed using both subscript ([ ]) and dot (.) notation (e.g., students.
Marks).
● Arrays of structures improve code manageability and readability compared to multiple
individual variables

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);

13. What is meant by union?


A union is a special data type available in C that allows storing different data types
in the same memory location. Unions provide an efficient way of using the same memory
location for multiple-purpose.
Syntax:
union union_name
{
data_type member1;
data_type member2;
data_type memeber;
};

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

15. Uses of Unions in C Programs


Unions have specific practical uses:
● Optimal Memory Usage: Useful for saving memory by storing multiple variables in the
same location, particularly when working with limited memory like in embedded
systems.
● Type Flexibility: Helpful when an item may have mutually exclusive types (e.g., a
variable might be an int or a float, not both).
● Data Conversion: Used in situations like protocol handling, where a data packet might
need to be interpreted differently depending on context (casting bytes to ints or floats).
● Hardware Programming: Unions let programmers access the same memory space in
different ways, useful for low-level register and device control.
● Variant Structures: Used in structures holding variant types, e.g., processing events or
commands of different type

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.

2 The keyword used is struct. The keyword used is union.

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.

4 Consumes more space compared. Conservation of memory is 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

18 .How Unions Conserve Memory ?


Unions improve memory efficiency in C programs by allowing different data types to share the
same memory space, with total size equal to the largest member, rather than allocating space for
each member separately.
● In a union, each member overlays the same physical memory block, meaning only one
member holds a valid value at any time.
● The union’s size is determined by its largest member, so multiple types can be stored
without allocating extra space for each type.
● This compactness is ideal for scenarios where values are mutually exclusive, such as
storing sensor data that might be either an integer, a float, or a character string, but never
all three simultaneously.
● Example: If a union contains an int (4 bytes), a float (4 bytes), and a char array (20 bytes),
the union occupies only 20 bytes—saving memory compared to a structure, which would
require 28 bytes.

19. What are enumerated data types?


It is a user defined data types .It is provided by “c” language.
Syntax:
enum identifier { value 1,value 2, …value n } ;
enumday w_st, w_end; w_st = mon ;
w_ end = sun;
The identifier follows with keyword enum is used to declare the variable.

5
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5

20. Why use Enums?


● 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).

21. How structure elements can be accessed?


Structure members can be accessed using
1. Direct member access operator/dot operator  Represented as (.) It‟s a Binary
Operator
Syntax: Structure_name. structure_member_name
2. Indirect member access operator/arrow operator Represented as (->) It‟s to
access structure members by the pointer to the structure 
Syntax: Pointer_to_Structure->structure_member_name

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;

Key characteristics of structures in C


● User-defined data type: Structures are not built-in types like int or char; you define
their blueprint according to your needs.
● Grouping diverse data types: Unlike arrays, which store elements of the same data type,
structures can hold variables of different data types, such as integers, characters, floats,
arrays, and even other structures.
● Representing real-world entities: Structures are useful for modeling entities that have
multiple, related attributes. For example, a Student structure could contain name (char
array), roll number (int), and gpa (float).
● Memory allocation: A structure definition itself does not allocate memory. Memory is
allocated only when a variable of that structure type is declared.
● Accessing members: Individual members of a structure variable are accessed using the
dot operator (.).
Example
Struct student
{

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

********STUDENTÆS DETAILS *******


ROLL No. = 101
NAME. = rahul
ROLL No. = 45000.000000
ROLL No. = 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.

[AU – DEC 2020]

#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]);

sum. feet = [Link] + [Link]; sum.


inch = [Link] + [Link];

while (sum. inch >= 12)


{
sum. inch = sum. inch - 12;
sum. feet++;
}
printf ("Sum is %d feet, %.1f inches\n", sum. feet, sum. inch);
}

10
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
ARRAYS OF STRUCTURE

4. Write short notes on ‘arrays of structures’. [AU-MAY 2022]


An array of structures is the same way as we declare an array of built-in data type. The array
of structures can be used when common structure definition is need for the process of
information.
Syntax
Struct struct_name struct_var[index];
Key Points
● Structures allow grouping of different data types; arrays of structures organize multiple records of
the same format.
● Elements are accessed using both subscript ([ ]) and dot (.) notation (e.g., [Link]).
● Arrays of structures improve code manageability and readability compared to multiple individual
variables

Example

struct student stud[30];

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;

printf("\n How many students information do you want to enter?");

scanf("%d",&n);

11
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
printf("Enter Student Information:");

for(i=1;i<=n;i++)

printf("\n Enter Roll no.:");

scanf("%d",&s[i].roll);

printf("\n Enter the name of the student:");

scanf("%s",&s[i].name);

printf("\n Enter the age of the student:");

scanf("%d",&s[i].age);

printf("\n\n Information of all studenst:");

for(i=1;i<=n;i++)

printf("\n Roll no.:%d",s[i].roll);

printf("\n Name:%s",s[i].name);

printf("\n Age of student:%d\n\n",s[i].age);

POINTER AND STRUCTURES


5. What is pointer and structures? Explain with example. [AU-MAY 2018]

Structures can be created and accessed using pointers. A pointer variable of a structure can be
created as below:
Syntax:
struct name{
member1;
member2;
..
};

Use of Structure Pointers

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

struct MyStruct*ptr; Declares a structure pointer

ptr= &s; Assigns address to the pointer

ptr->member Accesses member via pointer

(*ptr).member Alternative equivalent syntax

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

Unions and their uses

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];

Uses of Unions in C Programs


Unions have specific practical uses:
● Optimal Memory Usage:Useful for saving memory by storing multiple variables in the same
location, particularly when working with limited memory like in embedded systems.
● Type Flexibility: Helpful when an item may have mutually exclusive types (e.g., a variable might
be an int or a float, not both).
● Data Conversion:Used in situations like protocol handling, where a data packet might need to be
interpreted differently depending on context (casting bytes to ints or floats).
● Hardware Programming :Unions let programmers access the same memory space in different
ways, useful for low-level register and device control.
● Variant Structures : Used in structures holding variant types, e.g., processing events or
commands of different type
Example
union sample
{
int marks;
float avg;

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

/* Program to display total memory size occupied by union */


#include<stdio.h>
#include<string>
union student
{
int i;
float f;
char str[20];
};
int main( )
{
union student data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
}

Output:
Memory size occupied by data:20
Explanation:sizeof()returns the memory allocated for union

Initializing the Union


We can initialize the union in various ways. For example

18
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5
union myUnion
{
int var1;
long var2;
}newUnion={10.5};
newUnion.var1= 10;

Accessing union members


To access any member of a union, the member access operator (.) is used. would The
union keyword to define variables of union type.
Following is the example to explain usage of union:
#include<stdio.h>
union number
{
int n1;
float n2;
}union number x;
void main()
{
printf("Enter the value of n1: ");
scanf("%d", &x.n1);
printf("Value of n1 =%d", x.n1);
printf("\n Enter the value of n2: ");
scanf("%d", &x.n2);
printf("Value of n2 = %d\n",x.n2);
}
Output:
Enter the value of n1:10
Value of n1 =10
Enter the value of n2:20.5
Value of n2 =20.50000

19
MAILAM ENGINEERING COLLEGE CS25C01- COMPUTER PROGRAMMING
UNIT-5

Applications for union


Use the same memory in different ways.
Creating flexible structure that can hold different types of data.
Enumerations

[Link] to declare the enumerator constant? Explain with example.


It is one of the user-defined data type or constant. We can achieve by using the
keyword of ‘enum’. It attaches names to numbers, thereby improve the readability of the
program.
The compiler will be assign integer value to each constant. By default it starts from 0(zero). The
enumeration type is an integral data type.
Syntax:

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

MAILAM (PO), Villupuram (DT). Pin: 604 304


(Approved by AICTE, New Delhi, Affiliated to Anna University, Chennai,
Accredited by NBA, NAAC with ‘A’ Grade and TATA Consultancy Services)

CS25C01 – COMPUTER PROGRAMMING: C

UNIT VI FILE OPERATIONS

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).

2) Why files are needed? [AU-MAY 2019]


(OR)
Why are files needed? [AU-DEC 2022]
• 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 a few commands in C.
• You can easily move your data from one computer to another without any changes.
Types:
Text file or ASCII text file: Collection of information or data which are easily
readable by humans.
o Example: txt, doc, c, cpp

Binary file: It is collection of bytes. Very tough to read by humans.


o Example: gif, bmp, jpeg

3) List the various modes of accessing a file through C. [AU-MAY 2023]

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.

a Append to a text file. If the file does not exist, it is created.

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.

wb Open a binary file for writing.

ab Append to a binary file.

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.

r+b/ rb+ Open a binary file for read/write

w+b/wb+ Create a binary file for read/write

a+b/ab+ Append a binary file for read/write

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

wb Open a binary file for writing

ab Append to a binary file

r+b/ rb+ Open a binary file for read/write

w+b/wb+ Create a binary file for read/write

a+b/ab+ Append a binary file for read/write

5) What are streams in File?


Streams are sequence of bytes of data; it can be in both directions. If data is
passing to program, it is called input stream and if data is returning (printing) to output
device, it is called output stream.

6) What are standard streams available in C language?


• Standard input (stdin) - Standard input stream from which program receives its
data.
• Standard output (stdout) - Standard output stream where a program writes its
output data.
• Standard error (stderr) - Standard error an output stream used by programs to
report error messages.

UNIT-6 2
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C

7) What are file attributes?


The various file attributes are:
• Filename - String of characters to store the name of files.
• File Position - Pointer that points the position at which next read and write
operation to be performed.
• File Structure - It indicates whether file is text or binary file.
• File Access Methods - Indicates whether file can be accessed sequentially or
randomly.
• Attributes flag - Specifies that hidden or read-only or archive file.

8) What are the basic file operations in C programming?


There are 4 basic operations that can be performed on any files in C programming
language. They are,
• Opening/Creating a file & Closing a file
• Reading a file & Writing in a file

9) What is meant by file opening?


The action of connecting a program to a file is called opening of a file. This
requires creating an I/O stream before reading or writing the data

10) What is a file pointer?


The pointer to a FILE data type is called as a stream pointer or a file pointer. A
file pointer points to the block of information of the stream that had just been opened.

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.

12) When will the fopen ( ) gets failed?


The fopen() can fail to open the specified file under certain conditions that are listed
below:
• Opening a file that is not ready for usage.
• Opening a file that is specified to be on a non-existent directory/drive.
• Opening a non-existent file for reading.
• Opening a file to which access is not permitted.

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.

15) What are unformatted data files? [AU-DEC 2020]


Unformatted data refers to the raw, unstyled state of the data in your source file.
(Note that “format” is not referring to a file format in this case.) Unformatted data is what
exists underside any other applied styles or formats, including those common in Excel.

BINARY Vs TEXT FILES


16)Define Text file.
In C programming, a text file is a type of file that stores data in a human-
readable format, typically using character encoding schemes like ASCII or UTF-8. Unlike
binary files, which store data in its raw, uninterpreted form, text files are designed to be
easily viewed and edited using standard text editors.

17)Define Binary file.


A binary file is a file that stores data in its raw, internal representation, directly as
sequences of bytes (0s and 1s). Unlike text files, which store data as human-readable
characters following a specific encoding (like ASCII or Unicode), binary files are not
intended for direct human interpretation.

18) Differentiate: Text file and binary file.


TEXT FILE BINARY FILE
Data are human readable characters. Data is in the form of sequence of bytes.
Each line ends with a newline character. There are no lines or newline character.
Ctrl+z or Ctrl+d are end of file character. An EOF marker is used.
Data is read in forward direction only. Data may be read in any direction.
Data is converted into the internal format Data stored in file are in same format that
before being stored in memory. they are stored in memory.

TYPES OF FILE PROCESSING

19) What is file processing? List out its types.


Processing the content to the file or accessing content from the file. In general, there
are two types of file processing, they are listed below.

• Sequential access
• Random access

20) What is sequential access file?


It is one containing and stores data in chronological order. The data itself may be ordered
or unordered in the file. Sequential files must be read from the beginning, up to the
location of the desired data.

21) What is a random access file?


A file can be accessed at random using fseek() function fseek(fp,position,origin);
fp file pointer position number of bytes offset from origin 0,1 or 2 denote the beginning
,current position or end of file respectively.

UNIT-6 4
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C

22) What is the purpose of ftell?


The function ftell() is used to get the current file represented by the file pointer.
ftell(fp); returns a long integer value representing the current file position of the file
pointed by the file pointer fp. If an error occurs -1 is returned.

23) What is the purpose of rewind ()?


The function rewind is used to bring the file pointer to the beginning of the file.
rewind(fp); Where fp is a file pointer. Also we can get the same effect by feek(fp,0,0);

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

25) Give an example for fseek(). [AU-DEC 2022]


#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

FILE POINTERS

26) What is file pointer?


A pointer variable is used to points a structure FILE. The members of the
FILE structure are used by the program in various file access operation, but
programmers do not need to concerned about them.
Syntax:FILE *file_pointer_name;
Eg : FILE *fp;

27) Give an example for file pointer.


#include <stdio.h>
int main()
{
// declaring file pointer
FILE* fptr;

UNIT-6 5
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C

// trying to get the size of FILE datatype.


printf("Size of FILE Structure: %d bytes",
sizeof(FILE));

return 0;
}
Output
Size of FILE Structure: 216 bytes

28) How File Pointer Works in 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:

✓ 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.

ERROR HANDLING IN FILE OPERATIONS

31) What is Error Handling in file pointers?


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.

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 and Output Stream

Input and Output Stream

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.

Figure 6.1: Input and Output Stream

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).

Figure 6.2: Buffer in file

UNIT-6 7
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C

Structure of files

The Structure of files are given below.(Refer Figure 6.3).

Figure 6.3: File Structure


• Field: Single unit in the file.
• Record: It is logical group of data fields that comprise a single row of
information, which describes the characteristics of an item.
• Directory: It is a collection of related files.

Example

Standard streams available in C language


• Standard input (stdin) - Standard input stream from which program receives
its data.
• Standard output (stdout) - Standard output stream where a program writes its
output data.
• Standard error (stderr) - Standard error an output stream used by programs
to report error messages.

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

(i) Declaring a file pointer variable


• In order to access a particular file, we must specify the name of the file that has
to be used. This is performed by using a file pointer variable that points to a
structure FILE (defined in stdio.h).
• The file pointer will then be used in all subsequent operations in the file.
Syntax:

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:

FILE *fopen(const char *file_name, const char *mode);


• The file whose pathname is the string pointed to by file_name is opened in
the mode specified.
• If successful, fopen() returns a pointer-to-structure FILE and if it fails, it returns
NULL.
• Opening a file returns a pointer to a FILE structure
Example:

f=fopen(“[Link]”, “w”) // Creating new file


f=fopen(“[Link]”,”r”) //Opening an existing file

UNIT-6 9
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C

File Opening Mode [AU-DEC 2023]

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

a Append to a text file. if the file does not exist, it is created.

Open a binary file for reading. B indicates binary. By default this will
rb
be a sequential file in Media 4 format

wb Open a binary file for writing

ab Append to a binary file

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.

r+b/ rb+ Open a binary file for read/write

w+b/wb+ Create a binary file for read/write

a+b/ab+ Append a binary file for read/write

Condition fopen( ) gets failed:


The fopen() can fail to open the specified file under certain conditions that are listed
below:
• Opening a file that is not ready for usage
• Opening a file that is specified to be on a non-existent directory/drive
• Opening a non-existent file for reading
• Opening a file to which access is not permitted

(iii) Processing a file


There are two ways are available to processing a file, they are given below
a) Reading
b) Writing

(a) Reading content from a file


The fscanf() is used to read formatted data from the stream i.e text file.

Syntax:

int fscanf(FILE *stream, const char *format,…);

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

(b) Writing the Content to file using fprintf( ):


The fpritnt() is used to write formatted output to stream.

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

fprintf(fptr, "Age = %d\n", age);


printf("Enter the salary \n");
scanf("%f", &salary);
fprintf(fptr, "Salary = %.2f\n", salary);
fclose(fptr);
}

Output:
Enter the name
raj
Enter the age
30
Enter the salary
50000

(iv) Closing a File:


• To close an open file, the fclose() function is used which disconnects a file pointer
from a file.
• The fclose() function not only closes the file but also clears all the buffers that are
maintained for that file
• If file is not closed after using it, the system closes it automatically when the
program exits.
Syntax:

int fclose(FILE *fp);


Description:
• Here, fp is a file pointer which points to the file that has to be closed.
• The function returns an integer value which indicates whether the
fclose() was successful or not. A zero is returned if the function was
successful; and a non-zero value is returned if an error occurred.
Example:
fclose(f);

3) Briefly explain the input and output operation on file.


In the above table we have discussed about various file I/O functions to perform
reading and writing on file.(Refer Figure 6.4).

Input and Output

fscanf() fprintf()
fgets() fputs()
fgetc() fputc()
fread() fwrite()

Figure 6.4: I/O types

Reading data from file


• fscanf()
• fgets()

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

(iv) fread( ) [AU-DEC 2023]


• Reads data from a stream. Mostly used in binary file.
• fread( ) reads n items of data each of length size bytes from the given
input stream into a block pointed to by ptr.
• The total number of bytes read is (n * size).
• In case of success, fread return the number of bytes otherwise a lesser
number of bytes are returned (possibly 0)
Example:
#include <stdio.h>
main()
{
FILE *f;

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);
}
}

Writing data to a file


C provides the following set of functions to write data to a file.
• fprintf()
• fputs()
• fputc()
• fwrite()

(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:

int fputs( const char *str, FILE *stream );


Example:
FILE *fp;
char feedback[100];
fp = fopen("[Link]", "w");
gets(feedback);
fputs(feedback, fp);

(iii) fputc()
• The fputc() is used to write a character to the stream.
Syntax:

int fputc(int c, FILE *stream);

• 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);

(iv) fwrite( ) [AU-DEC 2023]


• Writes data to a stream.
• fwrite appends n items of data each of length size bytes to the given output file.
• The data written begins at ptr.
• The total number of bytes written is (n * size).
• ptr in the declarations is a pointer to any object.
• In case of success, fwrite return the number of bytes actually write to the stream
opened by fopen function.
• In case of failure, a lesser number of bytes are returned (possibly 0)

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.

Example For binary file read and writes


#include<stdio.h>

struct student
{
char name[50];
int height;
}

main()
{

UNIT-6 15
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C

struct student a[3],b[3];


int i;
FILE *ptr;

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.

5) Briefly explain the concept of file management functions.


In the file, there are three functions are available to manage or manipulate the
file, they are given below.
➢ fseek()
➢ ftell()
➢ rewind()
➢ fgetpos()
➢ fsetpos()
➢ remove()

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:

int fseek(FILE *stream, long offset, int whence);

• 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.

Values for whence:

SEEK_SET Seeks from beginning of file


SEEK_CUR Seeks from current position
SEEK_END Seeks from end of file

▪ If success, this function returns 0, otherwise it returns -1.

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

printf("The file pointer is at byte %ld\n", ftell(stream));


fclose(stream);
return 0;
}
Output:
The file pointer is at byte 14
Explanation:
The ftell( ) function returns current position of the file.
rewind() - It moves thecontrol to beginning of the file.

(iii) rewind() Function


The rewind() function can be used in sequential or random access C file
programming, and simply tells the file system to position the file pointer at the start of the
file. Any error flags will also be cleared, and no value is returned.
It sets the position to the beginning of the file. It also takes a file pointer and
reset the position to the start of the file.

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:

int fgetpos(FILE *stream, fpos_t *pos);

(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:

int fsetpos( FILE *stream, const fops_t pos);

(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:

int remove(const char *filename);


• The remove() will erase the file specified by filename. On success, the function
will return zero and in case of error, it will return a non-zero value.

UNIT-6 18
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C

6) List out some inbuilt functions for file handling in C language.


C programming language offers many inbuilt functions for handling files. They are
given below.
File Description
handling functions
fopen () fopen () function creates a new file or opens an existing file.
fclose () fclose () function closes an opened file.
getw () getw () function reads an integer from file.
putw () putw () functions writes an integer to file.
fgetc () fgetc () function reads a character from file.
fputc () fputc () functions write a character to file.
gets () gets () function reads line from keyboard.
puts () puts () function writes line to o/p screen.
fgets () fgets () function reads string from a file, one line at a time.
fputs () fputs () function writes string to a file.
feof () feof () function finds end of file.
fgetchar () fgetchar () function reads a character from keyboard.
fprintf () fprintf () function writes formatted data to a file.
fscanf () fscanf () function reads formatted data from a file.
fputchar () fputchar () function writes a character onto the output screen
from keyboard input.
fseek () fseek () function moves file pointer position to given location.
SEEK_SET SEEK_SET moves file pointer position to the beginning of the
SEEK_CUR file.
SEEK_CUR moves file pointer position to given location.
SEEK_END SEEK_END moves file pointer position to the end of file.
ftell () ftell () function gives current position of file pointer.
rewind () rewind () function moves file pointer position to the beginning
getc () of the()file.
getc function reads character from file.
getch () getch () function reads character from keyboard.
getche () getche () function reads character from keyboard and echoes
to o/p screen.
getchar () getchar () function reads character from keyboard.
putc () putc () function writes a character to file.
putchar () putchar () function writes a character to screen.
printf () printf () function writes formatted data to screen.
sprinf () sprinf () function writes formatted output to string.
scanf () scanf () function reads formatted data from keyboard.
sscanf () sscanf () function Reads formatted input from a string.
remove () remove () function deletes a file.
fflush () fflush () function flushes a file.

UNIT-6 19
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C

SEQUENTIAL ACCESS FILE


7) How to access random access file? Write an example program.
[AU-DEC 2024]

Figure 6.5: Sequential access file structure

• No notion of records in a file.(Refer Figure 6.5).


• Programmer must provide file structure.

Creating file:
FILE *rf;
• Creates a FILE pointer called cfPtr

cfPtr = fopen(“[Link]", “w”);


• Function fopen returns a FILE pointer to file specified
• Takes two arguments – file to open and file open mode
• If open fails, NULL returned

fprintf () 2 mark [AU-DEC 2024]


• Used to print to a file

Like printf, except first argument is a FILE pointer (pointer to the file you
want to print in)
feof( FILE pointer ) [AU-DEC 2023]
• Returns true if end-of-file indicator (no more data to process) is set for the
specified file
fclose( FILE pointer )
• Closes specified file
• Performed automatically when program ends
• Good practice to close files explicitly
handle = fopen(filename,mode);
The fopen() function requires two arguments, both strings. The first is a filename;
the second is a mode. The fopen() function returns a file handle, which is a pointer used
to reference the file. That pointer is a FILE type of variable.

Writing text to a file


Write That File demonstrates the basic process of creating a new file, writing text
to that file, and then closing file access.
#include <stdio.h>
#include <stdlib.h>
main()
{
FILE *fh;
fh=fopen("[Link]","w");
if(fh==NULL)
{
puts("Can't open that file!");

UNIT-6 20
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C

exit(1);
}
fprintf(fh,"Look what I made!n");
fclose(fh);
}

Reading a text from a file


The standard C text-reading functions are used to read text from a file just as
they read text from the keyboard. For reading text one character at a time, use the
fgetc() function.
#include <stdio.h>
#include <stdlib.h>
main()
{
FILE *fh;
int ch;
fh=fopen("[Link]","r");
if(fh==NULL)
{
puts("Can't open that file!");
exit(1);
}
while((ch=fgetc(fh))!=EOF)
putchar(ch);
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);

printf("The sum and average of the numbers is %d\t%d.\n",sum,avg);


}

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

RANDOM ACCESS FILES

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).

Figure 6.6: Random access file structure

Creating a Random-Access File


Data in random access files are
• Unformatted (stored as "raw bytes")
• All data of the same type (ints, for example) uses the same amount of memory
• All records of the same type have a fixed length
• Data is not in human readable format
Unformatted I/O functions
• fwrite()
Transfer bytes from a location in memory to a file
• fread()
Transfer bytes from a file to a location in memory
Example:
fwrite( &number, sizeof( int ), 1, myPtr );

&number – Location to transfer bytes from


sizeof( int ) – Number of bytes to transfer
1 – For arrays, number of elements to transfer, In this case, "one
element" of an array is being transferred
myPtr – File to transfer to or from
There is no need to read each record sequentially, if we want to access a particular
record.C supports these functions for random access file processing.
➢ fseek()
➢ ftell()
➢ rewind()

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)

printf("file cannot be opened");

else

printf("Enter value of n to read last ‘n’ characters");

scanf("%d",&n);

fseek(fp,-n,2);

while((ch=fgetc(fp))!=EOF)

printf("%c\t",ch);

fclose(fp);

9) Write a c program for transaction processing using random access files.

#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

printf( "%s", "Enter account number\n " );


scanf( "%d", &[Link] );
}
fclose( cfPtr );
}
}

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

10) Give brief notes a file pointers in c.


A file pointer is a variable that is used to refer to an opened file in a C program.
The file pointer is actually a structure that stores the file data such as the file name, its
location, mode, and the current position in the file. It is used in almost all the file
operations in C such as opening, closing, reading, writing, etc.

Syntax

FILE *ptr;

Here, FILE is the typedef name of the predefined file pointer structure and ptr is
a pointer variable of type FILE.

Example of File Pointer

#include <stdio.h>

int main()

// declaring file pointer

FILE* fptr;

// trying to get the size of FILE datatype.

printf("Size of FILE Structure: %d bytes",

sizeof(FILE));

return 0;

Output:

Size of FILE Structure: 216 bytes

UNIT-6 25
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C

File Pointer Works in 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:

1. In Read Mode ( "r" )

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.

2. In Write Mode ( "w" )

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.

• Read operations like fgetc() or fgets() cannot be performed on file pointer


pointing to these files.

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

• filePointer: The file pointer we want to modify.

• 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:

o SEEK_SET: Beginning of the file.

o SEEK_CUR: Current position of the file pointer.

o SEEK_END: End of the file.

11. Write short notes an Error handling in file operations.

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

Error Handling Techniques

Below are some standard error handling techniques:

(i) File Not Found Error

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() {

// Try to open file in

// read mode

FILE *file = fopen("[Link]", "r");

// Check if the file

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

Error: No such file or directory

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.

(ii) Handle Permission Denied Error

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.

FILE *file = fopen("/restricted/[Link]", "w");

if (file == NULL) {

perror("Permission denied");

(iii) Handle Disk Full Error

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() {

FILE *fptr = fopen("[Link]", "w");

if (fptr == NULL) {

perror("Error opening file");

return 1;

fprintf(fptr, "Writing to file");

// Check error after performing

UNIT-6 28
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C

// write operation

if (ferror(fptr)) {

perror("Error writing to file");

fclose(fptr);

return 0;

Output

Error writing to file: Permission Denied

(iv) Handle File Already Exists

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;

// Try to open the file in

// write mode

fptr = fopen("[Link]", "wx");

if (fptr == NULL) {

// Check if the error is

// due to file already existing

if (errno == EEXIST)

printf("File already exist");

// If we reach here, the file

// was created successfully

fprintf(fptr, "This is a new file.");

UNIT-6 29
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C

fclose(fptr);

return 0;

Output

File already exist

(v) Handle Invalid File Pointer

Always verify that the file pointer is not NULL before performing operations like
reading or writing. FILE *file = NULL;

if (file == NULL) {

printf("Invalid file pointer. File operations cannot proceed.\n");

(vi) Handle End-of-File (EOF)

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() {

FILE *file = fopen("[Link]", "r");

// Check for eof while reading

char ch;

while ((ch = fgetc(file)) != EOF)

putchar(ch);

// Use feof() to make sure

// EOF occurred or not

if (feof(file))

printf("End of file reached.");

else if (ferror(file))

printf("Error reading the file.");

fclose(file);

return 0;

Output

End of file reached.

UNIT-6 30
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C

(vii) Handle File Not Open

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() {

FILE *file = fopen("[Link]", "r");

if (file == NULL) {

printf("File could not be opened.\n");

} else {

printf("File opened successfully.\n");

fclose(file);

return 0;

Output

File could not be opened.

(viii) File Closing Error

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() {

FILE *fptr = fopen("[Link]", "w");

fprintf(fptr, "Writing to file");

// Check file close properly

if(fclose(fptr) == -1)

printf("File closing error");

else

printf("File closed");

return 0;

Output

File closing error

UNIT-6 31
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C

Program 2: Largest of three numbers

#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");
}
}

11) Write a c program to create a text file ‘[Link]’.


[AU-DEC 2020]
#include<stdio.h>
main( )
{
FILE *fp;
int rno , i;
float avg;
char name[20];
fopen(“[Link]”,"w");
for(i=1;i<=3;i++)
{
printf("Enter rno,name,average of student no%d:",i);
scanf("%d %s %f",&rno,name,&avg);
fprintf(fp,"%d %s %f\n",rno,name,avg);
}
fclose(fp);
fp=fopen (“[Link]”, "r" );
printf(“The Students details”);
for(i=1;i<=3;i++)
{
fscanf(fp,"%d %s %f",&rno,name,&avg);
printf("\n%d %s %f",rno,name,avg);
}
fclose(fp);

UNIT-6 32
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C

Output
Enter the filename:
[Link]

Enter rno,name,average of student no:1


101
ram
75
Enter rno,name,average of student no:2
102
raj
79.4
Enter rno,name,average of student no:3
103
rahul
92.3
The Students details
101 ram 75.000000
102 raj 79.400002
103 rahul 92.300003

12) Write a c program to print the contents of file in reverse order.


[AU-DEC 2020]
#include<stdio.h>
main()
{
FILE *fp;
char ch, fname[30], newch[500];
int i=0, j, COUNT=0;
printf("Enter the filename with extension: ");
gets(fname);
fp = fopen(fname, "r");
if(!fp)
{
printf("Error in opening the file...\nExiting...");
return 0;
}
printf("\nThe original content is:\n\n");
ch = getc(fp);
while(ch != EOF)
{
COUNT++;
putchar(ch);
newch[i] = ch;
i++;
ch = getc(fp);
}
printf("\n\n\n");
printf("The content in reverse order is:\n\n");
for(j=(COUNT-1); j>=0; j--)
{
ch = newch[j];

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

The content in reverse order is:

hseveD
ujaR
navagaR

13) Write a c program to implement the random access file.

#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));

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


{
putchar(getc(fp));
}
fseek(fp, 4 ,SEEK_CUR);
printf("\nText from position %d : \n\t",ftell(fp));
for(i=0; i < 6; i++)
{
putchar(getc(fp));
}
fseek(fp, - 10 , SEEK_END);
printf("\nText from position %d : \n\t",ftell(fp));

UNIT-6 34
MAILAM ENGINEERING COLLEGE CS25C01 – Computer Programming: C

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


{
putchar(getc(fp));
}
printf("\nCurrent position : %d",ftell(fp));
rewind(fp);
printf("\nText from starting : \n\t");
for(i=0;i < 8 ; i++)
{
putchar(getc(fp));
}
fclose(fp);
}

Output:
Text from position 3 :
defgh
Text from position 12 :
mnopqr
Text from position 16 :
qrstu
Current position : 21
Text from starting :
abcdefgh

14) Write a c program for handling records (structures) in a file.


#include<stdio.h>
struct player
{
char name[40];
int age;
int runs;
} p1,p2;

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

Enter name, age, runs of a player :


Dhoni
30
500
Enter name, age, runs of a player :
Virat
25
400

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

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);
}

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);
}

17) Write a C program to create a binary file in C named “[Link]” that


has the data such as citizen name, aadhar number, pan number, employment,
gender and age. Filter the application by analyzing the gender and employment
and move all the male applicants who are self-employed into another file called
“[Link]”. Assume minimum 10 candidates.
[AU-DEC 2023]
#include <stdio.h>
#include <stdlib.h>
#define MAX_CANDIDATES 10

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;

void write_applications(const char *filename, Application applications[], int


num_applications) {
FILE *file = fopen(filename, "wb");
if (file == NULL) {
printf("Error: Could not open file %s for writing.\n", filename);
exit(1);
}
fwrite(applications, sizeof(Application), num_applications, file);
fclose(file);
}

void filter_applications(const char *input_filename, const char *output_filename) {


FILE *input_file = fopen(input_filename, "rb");
if (input_file == NULL) {
printf("Error: Could not open file %s for reading.\n", input_filename);
exit(1);
}

Application applications[MAX_CANDIDATES];
int num_applications = fread(applications, sizeof(Application), MAX_CANDIDATES,
input_file);
fclose(input_file);

FILE *output_file = fopen(output_filename, "wb");


if (output_file == NULL) {
printf("Error: Could not open file %s for writing.\n", output_filename);
exit(1);
}

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

// Populate the applications array with data

write_applications("[Link]", applications, MAX_CANDIDATES);


filter_applications("[Link]", "[Link]");

return 0;
}

18) Write a C program to copy content of one file to another file.


#include <stdio.h> [AU-DEC 2024]
#include <stdlib.h>

void copyFile(const char *source, const char *destination) {


FILE *srcFile, *destFile;
char ch;

// Open source file in read mode


srcFile = fopen(source, "r");
if (srcFile == NULL) {
printf("Error: Cannot open source file %s\n", source);
exit(1);
}

// Open destination file in write mode


destFile = fopen(destination, "w");
if (destFile == NULL) {
printf("Error: Cannot open destination file %s\n", destination);
fclose(srcFile);
exit(1);
}

// Copy content character by character


while ((ch = fgetc(srcFile)) != EOF) {
fputc(ch, destFile);
}

printf("File copied successfully from %s to %s\n", source, destination);

// Close both files


fclose(srcFile);
fclose(destFile);
}

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

19) If questions ask in Part – C, it may be from Unit – 5 (Case studies /


Assignment).

IMPORTANT TOPICS:

1) About Files [AU-MAY 2022]


2) Files Operations [AU MAY 2018, DEC 2023]
3) Sequential File access [AU- MAY 2018 & MAY 2022, DEC 2024]
4) Random access file [AU- MAY 2018 & MAY 22, DEC 23, 24]
5) File pointers

ALL THE VERY BEST

UNIT-6 40
MAILAM ENGINEERING COLLEGE UNIT 7

Approved by AICTE, New Delhi, Affiliated to Anna University, Chennai,


Accredited by National Board of Accreditation (NBA), Accredited by NAAC with “A” Grade &
Accredited by TATA Consultancy Services (TCS), Chennai)

CS25C01 – COMPUTER PROGRAMMING: C


UNIT VII – STANDARD LIBRARIES & HEADER FILES

Using standard libraries like stdio.h, stdlib.h, string.h, math.h,


Creating and using user-defined header files and libraries.

PART A
Using standard libraries like stdio.h, stdlib.h, string.h,
math.h,

1. What is the C Standard Library?

 The C Standard Library is a collection of pre-defined functions,


macros, and variables that come with a C compiler.

 It provides common functionalities for tasks like input/output (using


stdio.h), string manipulation (using string.h), memory
management (using stdlib.h), and mathematical calculations
(using math.h).

 Including the relevant header file in a program gives access to these


features.

PREPARED BY: [Link], AP/AI&DS 1


MAILAM ENGINEERING COLLEGE UNIT 7

2. What is the purpose of the <stdio.h> header file in C?

 <stdio.h> stands for Standard Input Output Header.


 It provides functions for input and output operations like printf(),
scanf(), getchar(), putchar(), fopen(), etc.

3. Define scanf() function:

 Scanf() function is used to read the value from the input device.

4. Define printf() function:

 Printf() function is used to display data on the monitor.

5. Mention two functions provided by <stdio.h> for character I/O.

 getchar() and
 putchar().

6. What are stdin, stdout, and stderr?

 They are standard file pointers representing input, output, and error
streams respectively.

7. Mention one function from <stdio.h> used to detect end of file.

 feof(FILE* stream) detects the end of a file.

8. What is the format specifier to print a float value in C?

 %f is used to print a float.

9. What is getchar()?

 Getchar() function is used to read one character at a time from the


standard input device.

10. Define putchar().

a. Single character can be displayed using the function putchar().

b. The function putchar() stands for “putchar” and uses an argument.

PREPARED BY: [Link], AP/AI&DS 2


MAILAM ENGINEERING COLLEGE UNIT 7

11. Define string handling functions and its meaning.

a. The C library has a large number of string handling functions.

b. These functions are used to carry out many of the string manipulations.

12. What is the use of feof() in C?

 feof() checks whether the end-of-file (EOF) is reached in file handling.

13. What is the use of malloc()?

 malloc() dynamically allocates memory at runtime and returns a void


pointer to the first byte of allocated memory.

14. What is the difference between malloc() and calloc()?

 malloc() allocates uninitialized memory, while calloc() allocates


memory and initializes it to zero.

15. What is the purpose of <string.h>?

 It provides functions for string manipulation like strlen(), strcpy(),


strcmp(), strcat(), etc.

16. What are string operations defined in C?

Various string operations defined in C are,

a. strlen(): For Finding out length of string.

b. strcpy(): For copying the one string to another.

c. strcat(): For concatenating two strings.

d. strcmp(): For comparing two strings.

e. strrev(): For reversing two strings.

PREPARED BY: [Link], AP/AI&DS 3


MAILAM ENGINEERING COLLEGE UNIT 7

17. Write a C program to get a paragraph of text as input. [AU:


Dec.-19]

#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;
}

17. State the advantages of user defined functions over pre-


defined functions.

 A user defined function allows the programmer to define the exact


function of the module as per requirement. This may not be the case
with predefined function. It may or may not serve the desired purpose
completely.
 A user defined function gives flexibility to the programmer to use
optimal programming instructions, which is not possible in predefined
function.

18. What is the purpose of <math.h> in C?

 It provides mathematical functions like sqrt(), pow(), sin(), cos(),


log(), fabs(), etc.

19. List any five library functions.

 ceil(x)
 sqrt(x)
 log(x)
 pow(x,y)
 sin(x)

20. List the header files in ‘C’ language.

a. <stdio.h> - It contains standard I/O functions.


b. <ctype.h> - It contains character handling functions.
c. <stdlib.h> - It contains general utility functions.
d. <string.h> - It contains string manipulation functions.
e. <math.h> - It contains mathematical functions.
f. <time.h> - It contains time manipulation functions.

PREPARED BY: [Link], AP/AI&DS 4


MAILAM ENGINEERING COLLEGE UNIT 7

Creating and using user-defined header files and libraries.

21. What is a user-defined header file in C?

A user-defined header file is a custom file (with .h extension) created by


the programmer that contains function declarations, macros, or constants to
be reused in multiple C programs.

22. How do you include a user-defined header file in a program?

 Use double quotes in the #include directive.

Example:
#include "myheader.h"

23. What is the file extension of a user-defined header file?

 The standard extension is .h.

Example: mathutils.h.

24. What is the purpose of using user-defined header files?

 They promote code reusability, modularity, and maintainability


by separating function declarations or macros from the main code.

25. Write the steps to create and use a user-defined header file.

Step1: Create a .h file (e.g., functions.h) with function declarations or


macros.

Step2: Create a .c file (e.g., functions.c) with function definitions.

Step3: Include the header in your main program using #include


"functions.h".

26. Can functions in a user-defined header file be used in


multiple C programs?

 Yes, as long as both the .h and corresponding .c files are included


during compilation.

27. List out various Input & output statements in C.

 The input & output statements are classified into formatted &
unformatted I/O.

i. Formatted I/O: User can able to design/format the output.

PREPARED BY: [Link], AP/AI&DS 5


MAILAM ENGINEERING COLLEGE UNIT 7

ii. Unformatted I/O: doesn‘t allow the users to design the


output.

28. List out any 4 math functions.

1. pow(x,y) : used to find power of value of x^y. Returns a double


value log10(x)

: used to find natural logarithmic value of x.

2. sqrt(x) : used to find square root value of x


3. sin(x) : returns sin value of x

29. List any five library functions related to mathematical


functions.

a. ceil(x)

b. sqrt(x)

c. log(x)

d. pow(x,y)

e. sin(x)

30. What is a header file in C?

a. A header file in C is a file with a .h extension that contains declarations for


functions, data types, and macros.

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.

PREPARED BY: [Link], AP/AI&DS 6


MAILAM ENGINEERING COLLEGE UNIT 7

31. What is the difference between <filename.h> and


"filename.h" when including a header file?

• The difference lies in the search path the preprocessor uses to find the file:

 Angle Brackets (<>):

 It Used for standard library headers. (e.g.,


#include<stdio.h>).
 The preprocessor searches in system directories.

 Double Quotes (""):

 Used for user-defined header files. (e.g., #include


“myheader.h”).
 The preprocessor first searches in the current directory before
checking system directories.

32. What is the purpose of the stdio.h header file in C?

a. The stdio.h (Standard Input/Output) header file is used to perform input


and output operations in C.

b. It contains declarations for essential functions such as printf() for


printing formatted output to the screen and scanf() for reading formatted
input from the user.

33. What is the difference between a header file and a library?

Header File (.h):

• A text file containing function declarations (prototypes), macro


definitions, and data types.

• The #include preprocessor directive copies its contents into the source
code.

Library (.lib, .a, .dll):

• A collection of pre-compiled object code for the actual function


implementations.

• The linker resolves the function calls made in your code with the definitions
in the library file.

PREPARED BY: [Link], AP/AI&DS 7


MAILAM ENGINEERING COLLEGE UNIT 7

34. How does the #include directive work?

a. The #include directive is a preprocessor command that tells the


preprocessor to replace the line with the entire text of the specified file.

b. This inclusion happens before the compiler begins compilation, effectively


pasting the contents of the header file directly into the source file.

35. What happens if you forget to include the necessary header


file for a standard library function?

 The compiler will be unaware of the function's prototype.


 This will lead to a "function undefined" or similar error during
compilation.

36. How do you create a simple user-defined header 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.

37. What is a user-defined library, and why is it used?

 A user-defined library is a collection of compiled object code (.o or .obj


files) from your source code that provides functionality for other
programs.
 It is used to package and reuse code without distributing the source
code, promoting modularity and simplifying project compilation and
linking.

38. Give two examples of standard header files and mention


their purpose.

 <stdio.h>: Standard input/output header, declares functions like


printf() and scanf().
 <math.h>: Contains declarations for mathematical functions like
sqrt() and pow().
 <string.h>: Functions for manipulating character strings like strcpy()
and strlen().
 <stdlib.h>: Functions for general-purpose utilities including malloc(),
process control, and conversion.

PREPARED BY: [Link], AP/AI&DS 8


MAILAM ENGINEERING COLLEGE UNIT 7

39. What is the main purpose of a user-defined header file?

 To organize and modularize code.


 It separates function and class declarations from their definitions,
allowing for code reusability and making large projects more
manageable.

40. What are the key advantages of using user-defined libraries?

 Modularity: Code is organized into separate, manageable modules.


 Reusability: Functions can be used in multiple programs without
rewriting code.
 Maintainability: Changes or updates to the library do not require
recompilation of programs using it (in dynamic libraries).
 Reduced code duplication: Avoids copy-pasting code across
different source files.

PREPARED BY: [Link], AP/AI&DS 9


MAILAM ENGINEERING COLLEGE UNIT 7

PART-B
Standard libraries like stdio.h, stdlib.h, string.h, math.h.

1. Briefly explain about Standard Libraries and Using


standard libraries like stdio.h, stdlib.h, string.h, math.h.

Synopsis:

 Standard libraries

 Header files with standard functions.

 Standard ‘c’ library functions

Standard libraries

 The standard functions are built-in functions.


 In C programming language, the standard functions are declared in
header files and defined in .dll files.
 In simple words, the standard functions can be defined as "the
readymade functions defined by the system to make coding more easy".
 The standard functions are also called as library function sorpre-
defined functions.
 The Standard Function Library in C is a huge library of sub-libraries, each
of which contains the code for several functions.
 In order to make use of the selibraries, link each library in the broader
library through the use of header files.
 The actual definitions of these functions are stored in separate library
files, and declarations in header files.
 In order to use these functions, we have to include the header file in the
program.
 For example, the function printf() is defined in header file stdio.h
(Standard Input Output header file). When we use printf() in our
program, we must include stdio.h header file using #include
statement.

PREPARED BY: [Link], AP/AI&DS 10


MAILAM ENGINEERING COLLEGE UNIT 7

Header files with standard functions


C Programming Language provides the following header files with standard
functions. (Refer Table 7.1& 7.2).

TABLE 7.1

PREPARED BY: [Link], AP/AI&DS 11


MAILAM ENGINEERING COLLEGE UNIT 7

TABLE 7.2

PREPARED BY: [Link], AP/AI&DS 12


MAILAM ENGINEERING COLLEGE UNIT 7

Standard ‘c’ library functions


1. stdio.h
2. stdlib.h
3. string.h
4. math.h

1: STANDARD I/O LIBRARY FUNCTIONS<STDIO.H>(Refertable7.3)

TABLE 7.3

PREPARED BY: [Link], AP/AI&DS 13


MAILAM ENGINEERING COLLEGE UNIT 7

2: STANDARD LIBRARY FUNCTIONS<STDLIB.H>(Refertable7.4)

Table 7.4

3: STRING LIBRARY FUNCTIONS<STRING.H>(Refertable7.5)

Table 7.5

PREPARED BY: [Link], AP/AI&DS 14


MAILAM ENGINEERING COLLEGE UNIT 7

4: MATH LIBRARY FUNCTIONS<MATH.H>(Refertable7.6)

Table 7.6

2. Difference between Header file and Library.

Table 7.7

PREPARED BY: [Link], AP/AI&DS 15


MAILAM ENGINEERING COLLEGE UNIT 7

Creating and Using user defined header files

3. How to Create and implementation of the basic libraries with a


C program.

Synopsis:

 stdio.h

 string.h

 math.h
 stdlib.h

1. stdio.h:

Definition:

 The stdio.h header defines three variable types, several macros,and


various function for performing input and output.

 The stdio.h header file stands for Standard Input Output and provides
functions for input and output operations.

 It includes functions to input/perform tasks like reading from and writing


to the console, handling files, and managing formatted output.

Below is the C program to implement the above approach:

#include<stdio.h>int
main()
{
printf("GEEKSFORGEEKS");
return0;
}

Output

GEEKS FOR GEEKS

Note: If printf() function is used without including the header file<stdio.h>,an


error will be displayed.

PREPARED BY: [Link], AP/AI&DS 16


MAILAM ENGINEERING COLLEGE UNIT 7

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():

 The strcat() functions are used to concatenate(join)two strings.

 This function concatenates the destination string and the


source string,and the result is stored in the destination
string.
Syntax-

char*strcat(char*destination, constchar*source)

Below is the C program to implement strcat():

#include<stdio.h>#include<strin
g.h>
{
charstr1[100]="Geeks",

str2[100]="ForGeeks";
strcat(str1,str2);
puts(str1);
return 0;
}

Output

Geeks For Geeks

PREPARED BY: [Link], AP/AI&DS 17


MAILAM ENGINEERING COLLEGE UNIT 7

Example 2-strlen():

The strlen() function calculates the length of the given string.

Syntax:

intstrlen(chara[]);

Below is the C program to implement strlen():

#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

Length of string b=15

3. math.h:

Definition:

 The math.h header defines various mathematical functions and onemacro.

 All the Functions in this library take double as an argument and return
double as the result.

 To perform any operation related to mathematics,it is necessary to include


math.h header file.

PREPARED BY: [Link], AP/AI&DS 18


MAILAM ENGINEERING COLLEGE UNIT 7

Syntax-

doublesqrt(doublex)

Example1: sqrt()

Below is the C program to calculate the square root of any number:

#include<math.h>

#include <stdio.h>

int main()

doublenumber,squareRoot;

number = 12.5;

square Root = sqrt(number);

printf("Squarerootof%.2lf=%.2lf",

number,squareRoot); return

0;

Output:

Square root of 12.50=3.54

stdlib.h

 It Provides functions for memory allocation,process control,random


number generation, and conversion between data types.

 Includes functions like malloc(),free(),exit(),atoi(),andrand().

 Deals with system-level utilities, memory management, and other


miscellaneous operations.

 stdlib.h is only use when we need to allocate memory in our program.

PREPARED BY: [Link], AP/AI&DS 19


MAILAM ENGINEERING COLLEGE UNIT 7

4. How to write your own header file in C?

 As we all know that files with extension are called header files in C.

 These header files generally contain function declarations which we can be


used in our main C program, like for e.g. there is need to include stdio.h in
our C program to use function printf() in the program.

 Soth equestion arises,is it possible to create your own header file?

 The answer to the above is yes.

 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

Example of creating your own header file:

 Creating myhead.h.

 Including [Link] in other program.

 Using the created header file.

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.

PREPARED BY: [Link], AP/AI&DS 20


MAILAM ENGINEERING COLLEGE UNIT 7

2. Including the .hfile in other program:

 Now as we need to include stdio.h as #include in order to use printf()


function.

 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.

3. Using the created 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.

PREPARED BY: [Link], AP/AI&DS 21


MAILAM ENGINEERING COLLEGE UNIT 7

5. Difference between User-Defined Function and Library Function.

[Link]. User-Defined Functions Library Functions

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.

User-defined functions are not Library Functions are stored in a


3. Stored in library files. Special library file.

There is no such kind of requirement If the user wants to use a particular


4. to add a particular library. library function then the user has to
add the particular library of that
function in the header file of the
program.
Execution of the program begins from Execution of the program does not
5. the user-define function. begin from the library
function.

6. Example: sum(),fact(),...etc. Example: printf(),scanf(),


sqrt(),...etc.

PREPARED BY: [Link], AP/AI&DS 22

You might also like