All Units With Question
All Units With Question
Disadvantage:
❖ Complex problem cannot be solved
❖ Less efficient and less productive
❖ Parallel programming is not possible
Examples of Imperative programming paradigm:
❖ C : developed by Dennis Ritchie and Ken Thompson
❖ Fortan : developed by John Backus for IBM
❖ Basic : developed by John G Kemeny and Thomas E Kurtz
Imperative programming is divided into three broad categories:
a) Procedural
b) OOP and
c) parallel processing.
These paradigms are as follows:
A) Procedural programming paradigm
➢ This paradigm emphasizes on procedure in terms of under lying machine model.
➢ There is no difference in between procedural and imperative approach.
➢ It has the ability to reuse the code and it was boon at that time when it was in use because
of its reusability.
Examples of Procedural programming paradigm:
➢ C : developed by Dennis Ritchie and Ken Thompson
➢ C++ : developed by Bjarne Stroustrup
➢ Java : developed by James Gosling at Sun Microsystems
➢ ColdFusion : developed by J J Allaire
➢ Pascal : developed by Niklaus Wirth
B) Object oriented programming
➢ The program is written as a collection of classes and object which are meant for
communication.
➢ The smallest and basic entity is object and all kind of computation is performed on the
objects only. More emphasis is on data rather procedure.
➢ It can handle almost all kind of real life problems which are today in scenario.
Advantages:
❖ Data security
❖ Inheritance
❖ Code reusability
❖ Flexible and abstraction is also present
Examples of Object Oriented programming paradigm:
➢ Simula : first OOP language
➢ Java : developed by James Gosling at Sun Microsystems
➢ C++ : developed by Bjarne Stroustrup
➢ Objective-C : designed by Brad Cox
Preprocessor section
Function section
main ( )
{
Declaration part
Executable part
}
i) Documentation Section:
Comments are non executable statements. Comments are very helpful in identifying the
program features and underlying logic of the program.
✓ The multi line comment begins with ‘/*’ and end with ‘*/’.
✓ Single line comment statement start with double slash sign ‘//’.
Example:
• /* Matrix Addition Program */
• // Author : Joshna
Example
/*Addition of two numbers*/ Documentation Section
#include<stdio.h> Pre-processor directives
#include<conio.h>
#define A 10 Definition Section
int a=10; Global declarations
void main() Main() function
{
int b=20;
int c;
c=a+b; Execution Part
printf(“\n SUM=%d”,c);
getch();
}
Basic data type Derived data type User defined data type
char array typedef
int Structure enumeration
float function
double pointer
void
c) Pointers
The pointer variable holds the memory address of another variable. It provides a
way of accessing a variable.
Example:
int x;
int *ptr = &x;
d) Structure
A structure is a collection of related data elements of different data type under a
single name.
Example:
struct student
{
int reg_no;
char name[20];
};
1.4.3 User defined Data types:
(a) typedef:
It allows the users to define an alternate (or) alias name for an existing data type,
and this can be used to declare variables.
Example:
typedef int Marks;
Marks M1, M2;
(b) Enumerated data type:
The C language provides another user defined data type called enumerated data type.
Syntax
enum identifier{value1, value 2….value );
Example
enum Day { Mon, Tue, Wed, Thu, Fri, Sat, Sun};
enum Day D1, D2;
D1 = Wed;
D2 = Sun;
1.5 CONSTANTS
A constant is an entity whose value can‟t be changed during the execution of a program.
Constants are classified as:
1. Literal constants
2. Qualified constants
3. Symbolic constants
1.5.1 Literal constants
Literal constant or just literal denotes a fixed value, which may be an integer, floating
point number, character or a string.
enclosed within single quotes form a Printable character literal constant. Ex:
’A‟ ,’#’
Non-Printable character literal constant.
Non-Printable character literal constants are represented with the help of
escape sequences. An escape sequence consists of a backward slash (i.e. \)
followed by a character and both enclosed within single quotes.
Example:
enum Day{ Monday, Tuesday, Wednesday, Thursday};
Monday=0
Tuesday=1
Wendesday=2
Thursday=3
Program:
#include <stdio.h>
#include<conio.h>
void main()
{
enum Day{ Monday =1, Tuesday, Wednesday, Thursday};
enum No{ A= 3, B };
printf("Wednesday = %d", Wednesday);
printf("B = %d ", B);
}
Output:
Wednesday=3
B=4
1.7 KEYWORDS
Keywords are reserved words, they have standard and predefined meaning.Keywords
cannot be used as normal identifiers. They must be written in lower case letter. There are 32
keywords available in C. The following table shows the keywords in C.
✓ Logical NOT is a unary operator that negates the logical value of its single operand.
✓ Logical NOT convert a 1 to 0, and 0 to 1.
✓ Logical AND produces 1 if both operands are 1, otherwise produce 0.
✓ Logical OR produces 0 if both operands are 0, otherwise it produces 1.
iv) Assignment Operator:
Assignment operator ‘=’ is used to assign a constant or a value of an expression or a
value of a variable to other variable.
Syntax
Variable = expression (or) value
Operators Example Explanation
+= sum+=10 sum=sum+10
-= sum-=10 sum = sum-10
Compound assignment *= sum*=10 sum = sum*10
operators /+ sum/=10 sum = sum/10
%= sum%=10 sum = sum%10
&= sum&=10 sum = sum&10
Table 1.6: Assignment Operator
v) Increment and Decrement Operators (unary):
• increment (++) - Adds one to the variables
• decrement (--) - Subtract one from the variable
Operator Meaning
++ x Pre increment
(Increment then display)
-- x Pre decrement
(decrement then display)
x ++ Post increment
(display then increment)
x -- Post decrement
(display then decrement)
Table 1.7: Increment and Decrement Operators
Example:
a=10;
++a =11
a++ =10
--a =9
a-- =10
Bitwise OR ( | )
This operator compare the operands in corresponding bits position and produces 0 if both
operand bits are 0, otherwise produces 1.
Bitwise XOR (^ )
This operator compare the operands in corresponding bits position and produces 1 if both
operand bits are same, otherwise produces 0.
viii) Special Operators: (Miscellanous Operator)
C language supports some of the special operators.
Operators Meaning
, Comma operator
Associativity of operators
The associativity rule is applied when two or more operators are having same precedence
in the sub expression.
• An operator can be left-to-right associative or right-to-left associative.
• All operators with same precedence have same associativity
Low +-
1.10 EXPRESSIONS
An expression is a sequence of operators and operands that specifies the computation. An
operand can be a variable, constant or a function call. An operator is a symbol that is used to
write a mathematical, logical or relational expression.
Simple Expression
An expression that has only one operator is known as simple expression.
Example:
X=a+b;
X=++a;
Compound Expression
An expression that has more than one operator is known as compound expression.
Example:
X=a+b*c/f;
Arithmetic Expression
An expression consisting of arithmetic operators is known as arithmetic expression.
Example:
X=a+b;
Logical Expression
An expression consisting of logical operators is known as Logical expression.
Example:
X=a>b;
Program
#include<stdio.h>
#include<conio.h>
void main()
{
Result= 6+4/ 2;
printf(“Result=%d”,Result);
getch();
}
Output
Result= 8
Syntax
putchar (variable);
Program :
# include<stdio.h>
#include<conio.h>
void main ( )
{
char ch;
printf (“Enter any one character : ”);
ch = getchar ( );
printf (“The character you typed is ”);
putchar(ch);
}
Output :
Enter any one character : S
The character you typed is S
c) gets()
This function is used to accept a string from standard input device until ENTER key is
pressed.
Syntax
String_variable = gets();
d) puts()
This function is used to display a string to the standard output device.
Syntax
puts (String_variable)
Program :
# include<stdio.h>
#include<conio.h>
void main ( )
{
char name[20];
printf (“Enter your name : ”);
name = gets( );
printf (“Your name is : ”);
puts(name);
}
Output :
Enter your name : Anand
Your name is : Anand
e) getc()
The getc ( ) is an input function that reads a single character from the standard input
device ( keyboard ).
Syntax:
char variable;
variable = getc ( );
Example:
char ch;
ch = getchar ( );
f) putc()
The putc( ) is an output function that writes a single character on the standard output
device ( monitor ).
Syntax
putc(variable);
Program :
# include<stdio.h>
#include<conio.h>
void main ( )
{
char ch;
printf (“Enter any one character : ”);
ch = getc( );
printf (“The character you typed is ”);
putc(ch);
}
Output :
Enter any one character : S
The character you typed is S
Formatted I/O Statements
In unformatted I/O statements, we need to specify the type & size of the data. It arranges
the data in particular format.
(a) scanf ()
Input data can be read from standard input device (keyboard) using scanf ( ) function.
Syntax
scanf (“Control String”, &var1, &var2, . . .);
Example
scanf (“%d %d”, &a, &b);
Control String:
Control string specifies the type of data to be read and its size. The following list
represents the possible control strings.
Output:
Enter values of A and B : 4 3
Sum is 7
(c) fscanf
This function is used in file processing to read data from a file.
(d) fprintf
This function is used in file processing to write data into a file.
The fscanf() & fprintf() are similar to scanf and printf except that they are used in file
processing.
False
conditi
on
True
statements
void main ( )
{
int a;
printf (“\n Enter a number : ”);
scanf (“%d”, &a);
if ( a > 0)
printf (“The given number is positive number”);
getch();
}
Output
Enter a number :7
The given number is positive number
b) if - else Statement
It is a two way branching statement. If the condition is true then the True part statement
will be executed.If the condition is false then the False part statement will be executed.
Flowchart:
True False
if
conditi
Syntax:
if ( condition)
{
True part Statement
}
else
{
False part Statement
}
Program: Check Whether the Number Is Odd Or Even
# include<stdio.h>
#include<conio.h>
void main ( )
{
int n, r;
printf (“\n Enter a Number:”);
scanf (“%d”, &n);
r = n % 2;
if ( r == 0 )
printf (“Given Number is Even”);
else
printf (“Given Number is Odd”);
getch();
}
Output:
Enter a Number: 6
Given Number is Even
c) Nested if Statement
The if statement within another if statement is called as nested if statement.
Syntax:
if ( condition1 )
{
if ( condition2)
{
Inner if True part Statement
}
else
{
Inner if False part Statement
}
}
else
{
Outer if False part Statement
}
It checks the condition1 and if it is true it check the inner if condition2. This type of
nested if is useful when a series of decisions are involved.
Program :
# include<stdio.h>
#include<conio.h>
void main ( )
{
int Mark;
printf (“Give your Mark”);
scanf (“%d”, &Mark);
if ( Mark < 50 )
printf(“Failed”);
else
{
if ( Mark < 60 )
printf(“Second Class”);
else
printf (“First Class”);
}
getch();
}
Output
Give your mark : 68
First class
d) if-else if- else statement
If the else part of if statement contain another if statement, then the else and the if
statement can be combined. It is called else if ladder.
Syntax :
if ( condition1 )
Statement block 1
else if ( condition2)
Statement block 2
else if ( condition3 )
Statement block 3
else
Statement block 4
If the condition1 evaluated is true, the statement block1 is executed. If the condition2 is true,
then statement block2 is executed and so on. If none of the conditions are true, then the statement
block4 is executed.
Flowchart:
False
Conditio
n
True
True
False
Statement 1 Conditio
n
True False
Statement 2 Conditio
n
else if (b > c)
printf(“Biggest Number is %d”, b);
else
printf (“Biggest Number is %d”, c);
getch();
}
Output :
Enter three numbers : 40 -50 35
Biggest Number is 40
e) switch Statement
It is a multi way branching statement. It first evaluates the expression in switch statement.
That result is compared with each case value one by one. Whenever a match found, it execute the
statements given in the corresponding case statement.If none of the case value matches with the
result it executes the default section.
Switch( Expression)
Value
1?
Statement Block 1
Value
2?
Statement Block 2
…
..
Value
N?
Statement Block N
Statement Block D
Syntax:
switch (Expression)
{
case value 1:
Statement block 1
break;
case value 2:
Statement block 2
break;
...
case value n:
Statement block n
break;
default:
Default Statement block }
Rules for Writing Switch Statement
✓ The expression used in switch statement must be an integer or a character data.
✓ The case labels must be character or integer constant.
✓ Each case block must be terminated by break statement. Otherwise, all statements
that are followed by matched cases are executed.
✓ The default clause is optional & usually placed at the end.
✓ The case keyword must terminate with colon ( : )
✓ No two case constants are identical.
Program : Perform Arithmetic Operation Using Switch statement
# include<stdio.h>
#include<conio.h>
void main ( )
{
float value1, value2;
char operator;
printf (“Type your expression : ”);
scanf (“%f %c %f”, &value1, &operator, &value2);
switch(operator)
{
case ‘+’ :
printf (“%f”, value1 + value2);
break;
case ‘-’ :
printf (“%f”, value1 - value2);
break;
case ‘*’ :
printf (“%f”, value1 * value2);
break;
case ‘/’ :
printf (“%f”, value1 / value2);
break;
default :
printf (“unknown operator”);
}
getch();
}
Output
Type your expression: 10 + 5
15
1.12.2 Unconditional Branching Statement
In an unconditional branching, program control is transfer from one point to another
without checking the condition. Following are the unconditional branching statements.
i) goto
ii) break
iii) continue
iv) return
i) goto Statement
✓ ‘C’ provides the goto statement to transfer control unconditionally from one place to
another place in the program.
✓ The goto statement can move the program control almost anywhere in the program.
✓ The goto statement requires a label.
Syntax:
goto label; label:
………. ……..
………. ……..
label: goto label;
Program : Check Whether the Given Number is Prime or Not Using goto & return.
# include<stdio.h>
# include<conio.h>
void main ( )
{
int No, i;
printf (“Give the number : ”);
scanf (“%d” , &No);
Output:
1 2 3 4 6 7 8 9 10
break continue
Break statement takes the control to the Continue statement takes the control to
outside of the loop the beginning of the loop.
It is used in loop & switch statements This can be used only in loop statements
Condition:
The condition represents a test expression.
Incrementing / decrementing:
After completing every iteration, the counter variable must be increased or
decreased. Otherwise it may leads to an infinite loop.
Flowchart
False
Conditio
n
Body of for
statements
b) while Loop
while loop is a pre testing loop. The conditional expression is tested before the body
is executed. If the condition is true the loop will be repeated otherwise stop the
iteration. If the very first time itself the condition failed the loop will not be executed
at least one time.
Syntax:
while (condition)
{
Body of the loop
}
Flowchart:
Conditio
n
Body of while
statements
{
sum = sum+ i;
i++;
}
printf (“ Sum = %d”, sum);
getch();
}
Output
Enter the number of terms 5
Sum=15
c) do…while Loop
It is an exit checking loop. In do...while loop the test condition is given at the end of the
loop. Therefore the body of the loop will be executed at least once. If the test condition is
true, then repeat the body of the loop otherwise exit from loop.
Syntax:
do
{
Body of loop statements
} while (test expression);
Flowchart:
Body of Loop
Conditio
n
int i, sum = 0, n;
printf (“Enter the number of terms”);
scanf (“%d”, &n);
i=1;
do
{
sum = sum+ i;
i++;
} while( i <= n);
printf (“ Sum = %d”, sum);
getch();
}
Output
Enter the number of terms 5
Sum=15
Difference Between while and do . . . while
while do….while
Condition is tested at the beginning of Condition is tested at the end of the
the loop loop
Some time the loop will not be Loop will be executed at least once
executed at least once. even though the condition is false.
Table 1.14: Difference Between while and do . . . while
1.15 PRE-PROCESSOR DIRECTIVES
It is used to link system library files, for defining the macros and for defining the
conditional inclusion. It starts with symbol (#). There is no termination symbol semicolon. The
preprocessor directives can appear anywhere in a program but are generally placed at the
beginning of a program before the function main.
Example:
• #include <stdio.h>
• #define A 10
• # ifdef
• #endif
a) #include Preprocessor Directive
It inserts a particular header from another file. For example, if we include a #include
<stdio.h> directive, it replaces the directive with the contents of the stdio.h header file. It has
two forms
• #include <filename>
– For standard library header files
– Searches predesignated directories
• #include "filename"
– Searches in current directory
– Normally used for programmer-defined files
A Simple C Program:
#include<stdio.h>
#include<conio.h>
void main ( )
{
printf(“Hello”);
}
Output
Hello
Every C program must contain a function called main. All C program starts execution
from main function. Every program may have zero or more user defined function.
Example
a=10;
main()
{
b=30;
printf(“a and b=%d%d”,a,b);
}
a is the global variable and b is the local variable
17. Differentiate break and continue statement.
Break Continue
Terminate loop Skip iteration & continue with next iteration.
Takes the control to outside of the loop. Takes control to the beginning of the loop.
It used in both looping and switch It is used only in looping statement
statements.
18. What are the different data types available in C?
There are five basic data types:
(i) Character - char
(ii) Integer - int
(iii) Single-Precision floating point - float
(iv) Double Precision floating point - double
(v) No value available - void
19. Distinguish between while and do...while statement in C.
while do...while
(i) Some time the loop will not be (i) Loop is executed at least once.
executed minimum one time.
(ii) The condition is checked at the (ii) The condition is checked at the end
beginning of the loop of the loop
20. Mention the various Decisions making statement available in C.
The conditional branching statements are:
if ,if-else , Nested if, if else if else, switch Statement
The unconditional branching statements are.
Goto, break, continue, return
21. What is the use of sizeof operator in C?
The sizeof operator is used to return the size/ number of bytes of an variable or data type..
Example : sizeof(a), If a is an integer then it will return 4
22. What are the types of looping statements available in C?
C language has the following looping statements.
1. for loop
2. while loop
3. do...while loop
ADDITIONAL PROGRAMS
1. Find the Area and Circumference of a Circle
# include <stdio.h>
# include <conio.h>
void main()
{
float r, area, circum;
clrscr();
printf("Enter the value of radius : ");
scanf("%f", &r);
area = 3.14 * r * r;
circum = 2 * 3.14 * r;
printf("Area of a given Circle : %f\n ", area);
printf("Circumference of a given Circle : %f", circum);
getch();
}
Output:
Enter the value of radius : 5
Area of a given Circle : 78.5
Circumference of a given Circle : 31.4
2. Find the Biggest of Two Numbers
# include<stdio.h>
# include<conio.h>
void main()
{
int a, b;
clrscr();
printf("Enter two values\n");
scanf("%d %d", &a, &b);
if ( a > b)
printf("a is the Biggest data ");
else
printf("b is the Biggest data");
getch();
}
Output:
Enter two values
8
5
a is the Biggest data
5
6
7
Area of triangle=14.696939
5. Convert Fahrenheit To Celsius
# include<stdio.h>
# include<conio.h>
void main()
{
float cel, fahr;
clrscr();
printf("Enter the Fahrenheit value\n");
scanf("%f", &fahr);
cel = ( fahr - 32 ) / 1.8;
printf("Celcious value = %f", cel);
getch();
}
Output:
Enter the Fahrenheit value
68
Celsius value = 20
6. Convert Celsius To Fahrenheit
# include<stdio.h>
# include<conio.h>
void main()
{
float cel, fahr;
clrscr();
printf("Enter the Celsius value\n");
scanf("%f", &cel);
fahr = ( ( 1.8 * cel ) + 32 );
printf("Fahrenheit value = %f", fahr);
getch();
}
Output:
Enter the Celsius value
20
Fahrenheit value = 68
7. Check Whether the Given Year is a Leap Year or Not
# include<stdio.h>
# include<conio.h>
void main()
{
int year;
clrscr();
printf("Enter a Year\n");
scanf("%d", &year);
if ( year % 4 == 0 )
{
printf("Given Year is a Leap Year");
}
else
{
printf("Given Year is not a Leap Year");
}
getch();
}
Output:
Enter a Year
2000
Given Year is a Leap Year
8. Check Whether the Given Number is Odd or Even
# include<stdio.h>
# include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter a Number\n");
scanf("%d", &n);
if ( n % 2 == 0)
{
printf("%d is an Even Number", n);
}
else
{
printf("%d is an Odd Number", n);
}
getch();
}
Output:
Enter a Number
8
8 is an Even Number
9. Generate Fibonacci Series.
# include <stdio.h>
# include <conio.h>
void main()
{
int f1, f2, f3, i, n;
clrscr();
f1 = 0;
f2 = 1;
printf("\n Enter how many time generate Fibonacci Series");
scanf("%d", &n);
printf("\n Fibonacci Series\n");
printf("\t %d \t %d", f1, f2);
for ( i = 3 ; i <= n ; i++ )
{
f3 = f1 + f2;
f1 = f2;
f2 = f3;
printf("\t %d" ,f3);
}
getch();
}
Output:
Enter how many time generate Fibonacci Series
6
Fibonacci Series
0 1 1 2 3 5
10. Check Whether the Given Number is Prime or Not
# include<stdio.h>
# include<conio.h>
void main()
{
int num, i, count = 0;
clrscr();
printf("Enter a Number: ");
scanf("%d", &num);
Enter a Number
153
153 is an Armstrong Number
12. Reverse a Number
#include<stdio.h>
#include<conio.h>
void main()
{
int num, digit, reverse = 0;
clrscr();
printf ("Enter any Positive Number : ");
scanf("%d", &num);
while ( num > 0 )
{
digit = num % 10;
reverse = reverse * 10 + digit;
num = num / 10;
}
printf("Reversed of the given Number : %d", reverse);
getch();
}
Output:
Enter any Positive Number : 127
Reversed of the given Number : 721
13. Check Whether the Given Number is Palindrome or Not
#include<stdio.h>
#include<conio.h>
void main()
{
int num, digit, reverse = 0;
int original;
clrscr();
printf ("Enter any Number : ");
scanf("%d", &num);
original = num;
while ( num > 0 )
{
digit = num % 10;
reverse = reverse * 10 + digit;
num = num / 10;
}
if (reverse == original)
printf("\n The Number is Palindrome \n");
else
printf("\n The Number is not a Palindrome\n ");
getch();
}
Output:
Enter any number
525
The Number is Palindrome
14. Find the Sum of Digits of a Positive Number
#include<stdio.h>
#include<conio.h>
void main()
{
int num, sum = 0, digit;
clrscr();
printf("Enter a Positive Number: ");
scanf("%d", &num);
while ( num != 0)
{
digit = num % 10;
num = num / 10;
sum = sum + digit;
}
printf("Sum of digits of number: %d",sum);
getch();
}
Output:
Enter a Positive Number: 123
Sum of digits of number: 6
15. Count the Number of Digits in a Number
#include<stdio.h>
#include<conio.h>
void main()
{
int num, count = 0;
printf("Enter a Number: ");
scanf("%d", &num);
while(num != 0)
{
num = num / 10;
count++;
}
printf("Total Number of Digits is : %d", count);
getch();
}
Output:
Enter a Number: 823
Total Number of Digits is : 3
16. Find the Factorial of a Given Number
#include<stdio.h>
#include<conio.h>
void main()
{
int fact = 1, i, num;
clrscr();
printf("Enter a Number : ");
scanf("%d", &num);
for ( i = 1 ; i <= num ; i++)
{
fact = fact * i;
}
printf("Factorial of %d = %d", num, fact);
getch();
}
Output:
Enter a Number :4
Factorial of 3 = 24
17. Swapping of Numbers
#include <stdio.h>
#include<conio.h>
void main()
{
int x, y, temp;
clrscr();
printf("Enter the value of x and y \n");
scanf("%d%d", &x, &y);
Definition:
An array is a data structure that is used to store data of the same type. The position of
an element is specified with an integer value known as index or subscript.
Features of Array
✓ An array is a derived data type. It is used to represent a collection of elements of the
same data type.
✓ Array elements are counted from 0 to size-1.
✓ The elements can be accessed with array name and the index. The index specifies the
position of the element.
✓ The elements in an array 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.
Advantage of Array
1) Code Optimization: Less code to the access the data.
2) Easy to traverse data: By using the for loop, we can retrieve the elements of an
array easily.
3) Easy to sort data: To sort the elements of array, we need a few lines of code
only.
4) Random Access: We can access any element randomly using the array
Types of array:
1. Single dimensional array
2. Multi-dimensional array
2.2 DECLARATIONS OF ARRAYS
Array has to be declared before using it in C Program. Declaring Array means
specifying three things.
Example:
int a[2];
scanf(“%d%d”,&a[0],&a[1]);
Program: Calculate the average marks of the student
# include<stdio.h>
#include<conio.h>
void main()
{
int m[5],i,sum=0,n;
float avg;
printf(“enter number of subject \n”);
scanf(“%d”,&n);
printf(“enter marks \n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&m[i]);
}
for(i=0;i<n;i++)
sum=sum+m[i];
avg=(float)sum/n;
printf(“average=%f”,avg);
getch()
}
Output:
Enter number of subject
5
Enter marks of students
55
60
78
85
90
Average=73.6
2.5 TWO DIMENSIONAL ARRAYS
If the array has two subscripts then it is called two dimensional array or matrix. Two
dimensional arrays are used in situation where a table of values needs to be stored. A 2D array is
an array of 1-D arrays and can be visualized as a plane that has rows and columns.
2.5.1 Declaration
Two dimensional arrays must be declared before they are used so that the compiler can
allocate space for them in memory.
2 6 7 8 9
10 -50 3 5 6
2 4 6 8 20
scanf(“%d%d”,&a[0][0],&a[0][1],&a[1][0],&a[1][1]);
Program: Find the addition of two matrix
#include<stdio.h>
#include<conio.h>
void main()
{
int a[25][25],b[25][25], c[25][25], i, j m, n;
clrscr();
printf(“\n Enter the rows and columns of two matrices… “);
scanf(“%d %d “, &m, &n)
printf(“\n Enter the elements of A matrix…”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
printf(“\n Enter the elements of B matrix…”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”, &b[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j] + b[i][j];
printf(“\n The addition of two matrices”);
for(i=0;i<m;i++)
{
printf(“\n”);
for(j=0;j<n;j++)
{
printf(“\t %d”,c[i][j]);
}
}
getch();
}
Output:
Enter the rows and columns of two matrices…. 3 3
Enter the elements of A matrix
1 2 3
4 5 6
7 8 9
Enter the elements of B matrix
1 2 3
4 5 6
7 8 9
The addition of two matrixes
2 4 6
8 10 12
14 16 18
2.6 STRING OPERATIONS (LENGTH, COMPARE, CONCATENATE, COPY)
String is a collection of characters. In C language array of characters are called string. It
is enclosed within double quotes. E.g. “INDIA” is a string. Each character of string occupies 1
byte of memory. The last character is always ‘\0’.
Declaration of a String
Strings can be declared like a one dimensional array.
Syntax:
char string_name[size];
Example:
char name[30];
char dept[20];
String Initialization
The string can be initialized as follows:
char dept[10] = “CSE”;
OR
char dept[] = {‘C’, ‘S’, ‘E’,’\0’};
In the above example, ‘\0’ is a null character and specifies end of the string. Here string is
assigned character by character.
String Handling / Manipulation Function:
For string handling, we must include <string.h> header file in program
Function Purpose
Example
s= “hai”;
strlen(s)-> returns 3.
Program:
# include<stdio.h>
#include<conio.h>
# include <string.h>
void main()
{
char name[10];
printf(“Enter string:”);
scanf(“%s”,name);
int length;
length = strlen(name);
printf(“\n String length of %s is %d”, name, length);
getch();
}
Output:
Enter string: APPLE
String length of APPLE is 5
2.6.2 String Copy
It copies the source string to the destination string or used to copy the contents of one
string to another string variable
Syntax
strcpy(destination,source);
Example
s1=“hai”;
s2= “welcome”;
strcpy(s1,s2); // s2 is copied to s1. i.e. s1=welcome.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char source[10];
printf(“Enter string:”);
scanf(“%s”,source);
char target[10];
strcpy(target, source);
printf(“\n Source string is %s”, source);
printf(“Target string is %s, target);
getch();
}
Output:
Enter string : COMPUTER
Source string is COMPUTER
Target string is COMPUTER
2.6.3 String concatenation
strcat() is used to concatenate or combine two strings together.
Syntax:
strcat (string1, string2);
String2 is concatenated at the end of string1 and the result is stored in string1.
Example
s1=“hai ”;
s2= “welcome”;
strcat(s1,s2); // s2 is joined with s1. Now s1 is hai welcome.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char source[10];
printf(“Enter string1:”);
scanf(“%s”,source);
char target[10];
printf(“Enter string 2:”);
scanf(“%s”,target);
strcat(source, target);
printf(“After concatenation source string is : %s”, source);
getch();
}
Output:
Enter string1 : Computer
Enter string2 : Programming
After concatenation source string is: Computer Programming
2.6.4 String Compare
strcmp() function compares two strings to check whether they are same or different. The
two strings are compared character by character until end of one string is reached or a mismatch
character found.
• If two strings are identical, strcmp() returns a value zero
• If they are not equal it returns the numeric difference between the first non-
matching characters.
• if the strcmp() returns positive then string1 is greater and negative means string2
is greater.
Syntax:
strcmp(string1, string2);
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char source[10];
printf(“Enter string1:”);
scanf(“%s”,source);
char target[10];
printf(“Enter string 2:”);
scanf(“%s”,target);
int diff;
diff = strcmp (source, target);
if (diff == 0 )
printf(“Both strings are identical”);
else
printf(“Both strings are not identical”);
getch();
}
Output:
Enter String 1: Computer
Enter String 2: Programming
Both strings are not identical
2.7 SORTING
Sorting is the process of arranging elements either in ascending or in descending order.
Some of the sorting Methods are,
• Selection Sort
• Bubble Sort
• Merge sort
• Quick sort
2.7.1 Selection Sort
It finds the smallest element in the list & swaps it with the element present at the head of
the list. It is a very simple and natural way of sorting a list.
Steps:
• In selection sort the first element is compared with the remaining elements.
• If the first element is larger than the other elements, it should be interchanged.
• In the second iteration, the second element is compared with the following elements
and interchange if not in order.
• This step is continued for various iterations, until the elements are sorted in an order.
Example : (44, 33, 55, 22, 11)
Iteration 1: First compare first element with all other element.
44, 33, 55, 22, 11 Compare 44 & 33. Not in order. So swap.
33, 44, 55, 22, 11 Compare 33 & 55. It is in order. So don't swap.
33, 44, 55, 22, 11 Compare 33 & 22. Not in order. So swap.
22, 44, 55, 33, 11 Compare 22 & 11. Not in order. So swap.
11, 44, 55, 33, 22 Now first element is in correct order.
Iteration 2: Now compare second element with all other element.
11, 44, 55, 33, 22 Compare 44 & 55. It is in order . So don't swap.
11, 44, 55, 33, 22 Compare 44 & 33. Not in order . So swap.
11, 33, 55, 44, 22 Compare 33 & 22. Not in order . So swap.
11, 22, 55, 44, 33 Now first two elements are in correct order.
Iteration 3: Now compare third element with all other element.
11, 22, 55, 44, 33 Compare 55 & 44. Not in order . So swap.
11, 22, 44, 55, 33 Compare 44 & 33. Not in order . So swap.
11, 22, 33, 55, 44 Now first three elements are in correct order.
Iteration 4: Now compare fourth element with all other element.
11, 22, 33, 55, 44 Compare 55 & 44. Not in order . So swap.
11, 22, 33. 44, 55 Now first 4 elements are in correct order.
Balance only one element is there. So sorting is over.
Program:
#include <stdio.h>
#include<conio.h>
void main()
{
int i, j, temp, n, a[10];
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; i++)
printf("%d\n", a[i]);
printf("The numbers arranged in descending order are given below \n");
for(i=n-1;i>=0;i--)
printf("%d\n",a[i]);
getch();
}
Output:
Enter the value of N
4
Enter the numbers
10 2 5 3
The numbers arranged in ascending order are given below
2
3
5
10
The numbers arranged in descending order are given below
10
5
3
2
2.8 SEARCHING
Searching is to find a particular element in a list of elements. Following are some of the
searching methods.
1. Linear Search
2. Binary Search
2.8.1 Linear Search (or) Sequential Search:
This is the simplest method of searching a data in an array. This can be applied in an
unsorted array. Its time complexity is O ( n ).
Steps:
• In Linear search, we start the search from first location.
• If data found we stop otherwise search continues with next location.
• The above step is repeated until we reach the last location.
• Whenever we reach end of the list, the data is not found.
Example 1:
Consider the array elements: 3, 15, 12, 13, 8 and
Element to be searched = 13
Steps:
First we compare 13 with first element 3 - No match
Then compare 13 with second element 15 – No match
Then compare 13 with third element 12 – No match
Then compare 13 with fourth element 13 – Match.
Thus, the data found at location 4.
Example 2:
Consider the array elements: 3, 15, 12, 13, 8 and
Element to be searched (key) = 7
Steps:
First we compare 7 with first element 3 - No match
Then compare 7 with second element 15 – No match
Then compare 7 with third element 12 – No match
Then compare 7 with fourth element 13 – No match.
Then compare 7 with fifth element 8 – No match.
Now we reached the end of the list. So we say that “data not found”.
Program: Linear Search
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,m,c=0;
printf("Enter the size of an array: ");
scanf("%d",&n);
Output:
Enter the size of an array: 4
Enter the elements of the array: 4 3 5 1
Enter the number to be search: 5
Element is in the position 3
2.8.2 Binary Search:
Binary search can be applied only on sorted data. It is faster than linear search. Its time
complexity is O(log n)
Steps:
• First check the search element at the middle of the list
• If the middle element is the search key, then the data found. Stop the searching.
• If the key to be searched is smaller than the middle element then continue with the
bottom half of the list.
• If the key to be searched is greater than the middle element then continue with the top
half of the list
• Repeat the above steps till the sub array not possible further divide.
Example:
Consider the array elements
10, 15, 17, 23, 45, 60, 75
And the search element key = 15
1st Iteration:
High = 7, Low =1
Mid = (low + high) / 2 = (1 + 7) / 2 = 8/2 = 4
Array [mid] = Array[4] = 23
Here 15 < 23 search continues on the left side of the array
Therefore new High = mid -1 = 4 – 1 = 3
The sub list = 10, 15, 17
2nd iteration:
High = 3, Low = 1
Mid = (low + high) / 2 = (1 + 3) / 2 = 4 / 2 = 2
Array[mid] = Array[2] = 15
Here Array[mid] = key. i.e., 15 = 15
Thus data found at mid. i.e., at location 2.
Program : Binary Search
#include<stdio.h>
#include<conio.h>
void main()
{
int A[10], i, n, key,c=0;
int mid, low, high;
printf(“Enter the size of an array:”);
scanf(“%d”, &n);
printf(“Enter the elements in ascending order :”);
for( i = 1; i <= n; i++)
scanf(“%d”, &A[i]);
low = 1; high = n;
printf(“Enter the number to be searched:”);
scanf(“%d”, &key);
while ( low <= high)
{
mid = (low + high) / 2;
if ( A[mid] == key)
c=1;
break;
else if ( A[mid] < Key )
low = mid+ 1;
else
high = mid – 1;
}
if(c==0)
Output:
Enter String 1: Computer
Enter String 2: Programming
Both strings are not identical
3. List out the features of Arrays.
• An array is a derived data type. It is used to represent a collection of elements of the same
data type.
• The elements can be accessed with array name and the index. The index specifies the
position of the element.
• The elements in an array 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.
4. Define a float array of size 5 and assign 5 values to it.
void main( )
{
float a[5] = {26.9, 32.4, 84.2, 20.0, 78.1};
}
5. Identify the main elements of an array declaration.
Arrays must be declared before they are used so that the compiler can allocate space for them
in memory.
Syntax :
datatype arrayname[size]; [OR]
datatype arrayname[array_size]={list_of_values};
Example
int marks[6]={3,7,8,9,5,4};
6. How to create a two dimensional array?
If the array has two subscripts then it is called two dimensional array or matrix.
Syntax
datatype array_name [row size] [col size];= {value 0, value 1, . . . , value n};
• The data type specifies the array elements data type.
• rowsize indicates the size of row
• colsize indicates the size of column
Example:
int matrix[3][5] = { {2, 6, 7,8,9} , {10, -50, 3,5,6},{2,4,6,8,20} };
7. What are the different ways of initializing array?
Values can be assigned to an array by normal declaration otherwise they hold garbage
values. Arrays can be initialized in following two ways :
i. At compile time
ii. At Run time
Syntax:
datatype array_name [size] = {value 0, value 1, . . . , value n-1};
The initialized values are specified within curly braces separated by commas.
Example:
int Marks [3] = {70, 80, 90};
8. What is the use of ‘\0’ and ‘%s’?
• ‘\0’ is the escape sequence for null character it is automatically added at the end of the
string.
• ‘%s’ is a format specifier for string. It is used in scanf( ) and printf( ) functions to get the
string input or to print string output.
9. Define string.
String is a collection of characters. In C language array of characters are called string. It
is enclosed within double quotes. E.g. “INDIA” is a string. Each character of string occupies 1
byte of memory. The last character is always ‘\0’.
Syntax:
char string_name[size];
Example
char name[30];
10. Write a C program to find the length of given string.
# include<stdio.h>
#include<conio.h>
# include <string.h>
void main()
{
char name[10];
printf(“Enter string:”);
scanf(“%s”,name);
int length;
length = strlen(name);
printf(“\n String length of %s is %d”, name, length);
getch();
}
Output:
Enter string: APPLE
String length of APPLE is 5
11. Name library functions used for string handling.
Function Purpose
Array Pointer
4.Size of(array name) gives the number 4.Sezeof(pointer name) returns the number of
of bytes occupied by the array. bytes used to store the pointer variable.
16. What are the types of Arrays?
1. One-Dimensional Array
2. Two-Dimensional Array
ADDITIONAL PROGRAMS
1. C program to calculate mean for an array of elements.
#include <stdio.h>
#include<conio.h>
void main()
{
int m[5],i,sum=0,n;
float mean;
printf(“enter number of students \n”);
scanf(“%d”,&n);
printf(“enter marks of students \n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&m[i]);
}
for(i=0;i<n;i++)
sum=sum+m[i];
mean=sum/n;
printf(“Mean=%f”,mean);
}
Output:
Enter number of students
5
Enter marks of students
55
60
78
85
90
Mean=73.6
2. Computing Median:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,temp,n,a[20],sum=0;
float median;
printf("Enter n:");
scanf("%d",&n);
printf(“Enter numbers”);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[j]<a[i])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
if(n%2==0)
{
median=((a[n/2]+a[n/2 -1])/2.0);
}
else
{
median=a[n/2];
}
printf("\n the median value is %f",median);
getch();
}
Output:
Enter n:5
Enter numbers: 10 20 30 40 50
The median value is 30
3. Computing Mode:
#include<stdio.h>
#include<conio.h>
void main()
{
int maxvalue = 0, maxCount = 0, i, j,a[20],n,count=0;
printf("Enter N:");
scanf("%d",&n);
printf(“Enter numbers”);
return;
}
printf{“\n Enter the elements of A matrix…”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
printf{“\n Enter the elements of B matrix…”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”, &b[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
for(k=0; k<n; k++)
c[i][j] =c[i][j]+ a[i][k] * b[k][j];
printf(“\n The multiplication of two matrices”);
for(i=0;i<m;i++)
{
printf(“\n”);
for(j=0;j<n;j++)
{
printf(“\t %d”,c[i][j]);
}
}
getch();
}
Output
Enter order of matrix A : 2 2
Enter order of matrix B : 2 2
Enter matrix A elements
2 3
4 1
Enter matrix B elements
1 2
3 2
The multiplication of two matrices
11 10
7 10
5. Matrix Scaling
#include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int graphdriver=DETECT,graphmode,errorcode;
int i;
int x2,y2,x1,y1,x,y;
printf("Enter the 2 line end points:");
printf("x1,y1,x2,y2");
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
initgraph(&graphdriver,&graphmode,"c:\\tc\\bgi");
line(x1,y1,x2,y2);
printf("Enter scaling co-ordinates ");
printf("x,y");
scanf("%d%d",&x,&y);
x1=(x1*x);
y1=(y1*y);
x2=(x2*x);
y2=(y2*y);
printf("Line after scaling");
line(x1,y1,x2,y2);
getch();
closegraph();
}
Output:
a b
A=
c d
|A| = ad - bc
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2],i,j;
long determinant;
printf("Enter the 4 elements of matrix: ");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
|A| = a(ei-fh)-b(di-gf)+c(dh-eg)
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j;
long determinant;
printf("Enter the 9 elements of matrix: ");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("\nThe matrix is\n");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",a[i][j]);
}
determinant = a[0][0]*((a[1][1]*a[2][2]) - (a[2][1]*a[1][2])) -a[0][1]* (a[1][0] *
a[2][2] - a[2][0]*a[1][2]) + a[0][2]*(a[1][0]*a[2][1] - a[2][0]*a[1][1]);
printf("\n Determinant of 3X3 matrix: %ld", determinant);
getch();
}
Output:
Enter the 9 elements of matrix: 1 2 3 4 5 6 7 8 9
1 2 3
4 5 6
7 8 9
Determinant of 3X3 matrix:0
8. Matrix Transpose
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],i,j,m,n;
printf("How many rows");
scanf("%d",&m);
printf("How many columns");
scanf("%d",&n);
printf("\nEnter the matrix:\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf("%d",a[i][j]);
printf("\nTranspose of given matrix:\n");
for(i=0;i<m;++i)
for(j=0;j<n;++j)
printf("%d ",a[j][i]);
getch();
}
Output:
How many rows 2
How many columns 2
Enter the matrix: 1 2 3 4
1 2
3 4
Transpose of given matrix:
1 3
2 4
9. Check Whether the Given String is Palindrome or Not
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[15], b[15];
int i, j, length;
printf(“\n Enter the String : ”);
scanf(“%s”, a);
length = strlen(a);
j=0;
for ( i = length-1 ; i >= 0 ; i--)
{
b[j] = a[i];
j++;
}
b[j] = ’\0’;
if ( strcmp(a,b) == 0 )
}
else if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&& str[i]<='Z'))
{
consonants++;
}
else if(str[i]>='0' && str[i]<='9')
{
digits++;
}
else if (str[i]==' ')
{
spaces++;
}
else
{
specialCharacters++;
}
}
printf("\nVowels = %d",vowels);
printf("\nConsonants = %d",consonants);
printf("\nDigits = %d",digits);
printf("\nWhite spaces = %d",spaces);
printf("\nSpecial characters = %d",specialCharacters);
getch();
}
Output
Enter a string: geeks for geeks121
Vowels = 5
Consonant = 8
Digit =3
White spaces =2
Special Characters =0
12. Find the Largest and Smallest Number in the Given Array
#include <stdio.h>
#include<conio.h>
void main()
{
int i, j, temp, n, a[10];
printf("Enter the value of N \n");
scanf("%d", &n);
Some programs might have thousands or millions of lines and to manage such programs
it becomes quite difficult as there might be too many of syntax errors or logical errors present in
the program, so to manage such type of programs concept of modular programming approached.
FUNCTIONS
Function is defined as the block of organized, reusable code that is used to perform the
specific action. A function is a subprogram of one or more statements that performs a specific
task when called.
Advantages of Functions:
1. Code reusability
2. Better readability
3. Reduction in code redundancy
4. Easy to debug & test.
Classification of functions:
a) Based on who develops the function
b) Based on the function prototype
a) Based on the function prototype
Function prototype is a declaration statement that identify function with function name,
data type, a list of a arguments
b) Based on who develops the function
There are two types.
• Library functions
• User-defined functions
• Return type – data type of return value. It can be int, float, double, char, void etc.
• Function name – name of the function
• Parameter type list –It is a comma separated list of parameter types.
Example:
int add(int a, int b);
Function declaration must be terminated with a semicolon(;).
Types of function prototypes:
1. Function with no arguments and no return values
2. Function with arguments and no return values
3. Function with arguments and one return values
4. Function with no arguments and with return values
Prototype 1: Function with no arguments and no return values
• This function doesn’t accept any input and doesn’t return any result.
• These are not flexible.
Program
#include<stdio.h>
#include<conio.h>
void show(); //function prototype
void main()
{
{
int r;
float area;
printf(“Enter the radius \n”);
scanf(“%d”,&r);
area=circlearea(r);
printf(“Area of a circle =%d\n”, area);
getch();
}
int circlearea(int r1)
{
return 3.14 * r1 * r1;
}
Output:
Enter the radius
2
Area of circle = 12.000
Prototype 4: Function with no arguments and with return values
• This function doesn’t accept any input and doesn’t return any result.
• The result is returned back to the calling function.
Program
#include<stdio.h>
#include<conio.h>
float circlearea();
void main()
{
float area;
area=circlearea();
printf(“Area of a circle =%d\n”, area);
getch();
}
int circlearea()
{
int r=2;
return 3.14 * r * r;
}
Output:
Enter the radius 2
Area of circle = 12.000
Where,
• Return type – data type of return value. It can be int, float, double, char, void etc.
• Function name – name of the function
• Parameter type list –It is a comma separated list of parameter types.
b) Body of the function
• It consists of a set of statements enclosed within curly braces.
• The return statement is used to return the result of the called function to the
calling function.
Program:
#include<stdio.h>
#include<conio.h>
float circlearea(int); //function prototype
void main()
{
int r;
float area;
printf(“Enter the radius \n”);
scanf(“%d”,&r);
area=circlearea(r); //function call
printf(“Area of circle =%f\n”, area);
getch();
}
float circlearea(int r1)
{
return 3.14 * r1 * r1; //function definition
}
Output:
Enter the radius
2
Area of circle = 12.000
17 double sqrt(double x)
Returns the square root of x.
18 double ceil(double x)
Returns the smallest integer value greater than or equal to x.
19 double fabs(double x)
Returns the absolute value of x.
20 double floor(double x)
Returns the largest integer value less than or equal to x.
Output:
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
3.5.2 STRING FUNCTIONS
Library of String functions:
Header file:string.h
Example:
Functions Descriptions
String operations (length, compare, concatenate, copy) Refer Section 2.4 in pageno: 81.
strlwr() function
It converts all the uppercase characters in that string to lowercase characters.
Syntax
strlwr(string_name);
Example.
str[10]= “HELLO”;
strlwr(str);
puts(str);
Output:
hello
strupr() function
It converts all the lowercase characters in that string to uppercase characters.
Syntax
strupr(string_name);
Example
str[10]= “HEllo”;
strupr(str);
puts(str);
Output:
HELLO
strrev() function
It is used to reverse the string.
Syntax
strrev(string_name);
Example
str[10]= “HELLO”;
strrev(str);
puts(str);
Output:
OLLEH
Program for string reverse:
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main ()
{
char str[20] = “Computer”;
printf(“Given string = %s\n”, str);
printf (“The reverse string = %s”, strrev(str));
getch();
}
Output:
Given string = Computer
The reverse string = retupmoC
3.6 RECURSION
Recursion is defined as the function that calls itself repeatedly until condition is reached.
But while using recursion, programmers need to be careful to define an exit condition from the
function; otherwise it will go into an infinite loop.
Syntax:
Function1()
{
Function1();
}
Example:
Calculating the factorial of a number
Fact (n)= n*fact(n-1);
6! = 6*fact(n);
6! = 6 *5*fact(4)
6! = 6 * 5 * 4 *fact(3)
6! = 6 * 5 * 4 * 3 *fact(2)
6! =6 *5 * 4 * 3 *2 * fact(1)
6! = 6 *5 * 4 * 3 *2 * 1
6!=120
Advantage of recursion
• Recursion makes program elegant and cleaner.
• All algorithms can be defined recursively which makes it easier to visualize and
prove.
• Reduce unnecessary calling of function
• Easy to solve complex problems
Direct Recursion:
A function is directly recursive if it calls itself.
A( )
{
….
A( ); // call to itself
….
}
Indirect Recursion:
Function calls another function, which in turn calls the original function.
A( )
{
…
B( );
…
}
B( )
{
…
A( );// function B calls A
…
}
Linear Recursion - It makes only one recursive call.
Binary Recursion - It calls itself twice.
N-ary recursion - It calls itself n times.
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
return fib(n – 1) + fib (n– 2);
}
Output
Enter the number: 6
Fibonacci sequence : 0 1 1 2 3 5
Program 3 : Find the GCD of Two Positive Integer Numbers
#include<stdio.h>
#include<conio.h>
int gcd (int a, int b)
void main ()
{
int a, b;
printf(“\n Enter the two numbers:”);
scanf (“%d%d”, &a, &b);
printf(“\n The GCD of %d and %d is = %d”, a, b, gcd (a,b));
}
➢ Binary search is also known by these names, logarithmic search, binary chop, half
interval search.
Working
The binary search algorithm works by comparing the element to be searched by the
middle element of the array and based on this comparison follows the required procedure.
Case 2 − element > middle, search for the element in the sub-array starting from middle+1 index
to n.
Case 3 − element < middle, search for element in the sub-array starting from 0 index to middle -
1.
Program:
int mid;
if (low > high)
return -1;
mid = (low + high) / 2;
if (x == a[mid])
{
return (mid);
}
else if (x < a[mid])
{
binsearch(a, x, low, mid - 1);
}
else
{
binsearch(a, x, mid + 1, high);
}
}
OUTPUT:
Enter the total number of elements 7
Enter the elements of list 10 21 32 43 54 65 76
Enter element to be searched 32
Number present at 3
3.8 POINTERS
Pointer is a variable that stores the address of a variable or a function. Pointer is a
derived data type. It is declared same as other variables but prior to variable name an asterisk ‘*’
operator is used.
Benefits of Pointers
• Reduce the length of the program.
• Support dynamic memory management.
• Pointers save memory space.
• More efficient in handling arrays.
• Execution speed increased.
• Used to return multiple values from a function.
Declaring a Pointer
The pointer variable is declared by using * operator.
syntax
datatype * pointervariable;
Example:
char *ptr;
float *P1;
Pointer Initialization
The process of assigning the address of a variable to a pointer variable is known as
initialization. This is done through (&) ampersand operator.
Syntax:
Pointer variable = & variablename;
Example:
int n, *p;
p = &n;
Dereferencing Operator
* OR Gives Value stored at Particular address
indirection operator
Referencing Operator
& OR Gives Address of Variable
address of (&) operator
Table 3.3: Pointer Operators
Referencing operator: (&)
& operator is a unary operator that returns the memory address of its operand. It is used
to find the address of variable For example, if var is an integer variable, then &var is its
address. Reference operator is also known as address of (&) operator.
Eg) float a=12.5;
float *p;
p=&a;
a 12.5
1000
P 1000
2000
Fig. 3.1: Pointer P Referencing the variable a
Dereferencing operator
The second operator is indirection Operator *, and it is the complement of &. It is a unary
operator that returns the value of the variable located at the address specified by its operand. This
operator is also known as indirection operator or value- at-operator
Example
int b;
12 int a=12;
a int *p;
1000 p=&a;
b=*p; \\value pointed by p(or)value
1000 at 1000=12,
p so b=12
2000
Fig. 3.2: Pointer P Dereferencing the variable a
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int Mark = 73,
int *Ptr;
Ptr = &Mark;
printf(“The value of the variable Mark = %d \n”, *Ptr);
printf(“The address of the variable Mark = %d \n”, Ptr);
getch();
}
Output:
The value of the variable Mark = 73
The address of the variable Mark = 4082
For every execution time the compiler may allot the different memory. So, the address of
the variable may be different when we execute the program next time.
NULL Pointer
The pointer variable that is assigned NULL value is called Null pointer. NULL pointer is
a special pointer that does not point anywhere. It does not hold the address of any object or
function. It has numeric value 0
Example: for Null Pointer
int *ptr = 0;
( or )
int *ptr = NULL;
Use of null pointer:
• As an error value
• As a sentinel value
• To stop indirection in a recursive strucure
3.10 POINTER ARITHMETIC
Pointer is a variable that stores the address of a variable or a function.
Valid operation
• Pointer can be added with a constant
• Pointer can be subtracted with a Constant
• Pointer can be Incremented or Decremented
Not Valid operation
• Two pointers cannot be added
• Two pointers cannot be subtracted
• Two pointers cannot be multiplied
• Two pointers cannot be divided
Example:
int a=10
int *p=&a;
p=p+1;
• The pointer holds the address 2000. This value is added with 1.
• The data type size of the constant is added with the address. p= 2000+(2*1)=2002
The following table shows the pointer arithmetic.
S.no Operator Type of Type of Result Example Initial Final Description
operand 1 operand 2 type value value
1 Addition (+) Pointer to int Pointer Result =
type T to type initial value
T of ptr +int
operand *
sizeof (T)
Pre-
increment
Result =
initial value
of pointer +
sizeof (T)
Eg. post float* - float* ftr=p++ ftr=? ftr=2000
increment p=2000 p=2004 Value of ptr =
Value of ptr
+sizeof(T)
3 Subtraction Pointer to int Pointer Result =
- type T to type initial value
T of ptr - int
operand *
sizeof (T)
E.g. float* int float* p=p-1 p=2000 1996 2000 – 1 * 4
= 2000-
4=1996
4 decrement Pointer to Pointer Post
type T - to type decrement
T Result =
initial value
of pointer
Pre-
decrement
Result =
initial value
of pointer –
sizeof(T)
int a[3]={10,15,20};
printf(“First element of array is at %u\n”, a);
printf(“2nd element of array is at %u\n”, a+1);
printf(“3nd element of array is at %u\n”, a+2); 1000 1002 1004
}
Output 10 15 20
First element of array is at 1000
2nd element of array is at 1002
3nd element of array is at 1004
ii) Operation in array done by using pointers in c language.
Any operation that involves array subscripting is done by using pointers in c language.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3]={10,15,20};
printf(“Elements are %d %d %d\n”, a[0],a[1],a[2]);
printf(“Elements are %d %d %d\n”, *(a+0),*(a+1),*(a+2);
getch();
}
Output:
Elements are 10 15 20
Elements are 10 15 20
Program
#include <stdio.h>
#include<conio.h>
void main()
{
int num = 10;
int score = 12;
int run = 123;
int goal = 3;
int *ptr[4];
ptr[0] = #
ptr[1] = &score;
ptr[2] = &run;
ptr[3] = &goal;
printf("num: %d\n", *ptr[0]);
printf("score: %d\n", *ptr[1]);
printf("run: %d\n", *ptr[2]);
printf("goal: %d\n", *ptr[3]);
getch();
}
Output
num: 10
score: 12
run: 123
goal: 3
Values of actual arguments are passed to formal Address of actual arguments is passed to formal
arguments. arguments.
Actual & formal parameters refer different location Actual & formal parameters refer same location
Changes made in formal parameters not reflected Changes made in formal parameters reflected
back to the calling function back to the calling function
While calling a function, the values of actual parameters are passed to the formal
parameters. Therefore the called function works on the copy and not on original values of actual
parameters.
When arguments are passed by value, C allocates separate memory for formal arguments
and copy the actual argument value in that location. Therefore the changes made on formal
parameters will not affect the actual parameter.
Syntax for call by value:
functionname(arguments list);
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int ,int);
a=10;
b=20;
printf("\n Before swapping: a = %d and b = %d",a,b);
swap(a, b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf(“\n In Swap, x=%d and y=%d”, x,y);
}
Output:
Before swapping: a =10 and b =20
In Swap, x=20 and y=10
After swapping: a =10 and b = 20
Explanation:
In the above program, before calling the swap function, the value of a is 10 and the value
of b is 20. During the function call, the values of a and b are passed to x and y. In the swap
function, the values of x and y are swapped. Now, x has the value 20 and y has the value 10. But
this change does not get reflected in the value of a and b.
Main function
a b
10 20
1000 1002
Swap function
x 20 y
10
2000 2002
After swap function
x y
20 10
2000 2002
Fig 3.4 : Call by Value - example program
3.13.2 Call by Reference (Pass by Reference)
In this method, the address of the actual argument, in the calling function are copied into
the formal arguments of the called function. That is the actual & formal arguments refer same
memory location. Therefore the changes made on formal parameters will affect the actual
parameter of the calling function.
Example:
#include<stdio.h>
#include<conio.h>
void swap(int *, int *)
void main()
{
int a = 10, b = 20;
printf(“Before swap a = %d, b = %d \n”, a,b);
swap (&a, &b);
printf(“After swap a = %d, b = %d”, a, b);
getch();
}
void swap (int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
printf(“\n In Swap, x=%d and y=%d”, *x,*y);
}
Output:
Before swap a = 10, b = 20
In Swap, x=20 and y=10
After swap a = 20, b = 10
Explanation:
In the above program, before calling the swap function, the value of a is 10 and the value
of b is 20. During the function call, the references of a and b are passed to x and y. In the swap
function, the values of x and y are swapped. Now, x has the value 20 and y has the value 10. This
change gets reflected in the value of a and b.
Main function
a b
10 20
1000 1002
Swap function
x 20 y
10
1000 1002
After swap function
20 x y10
1000 1002
Fig 3.5 : Call by Reference - example program
1. double cos(double x)
Returns the cosine of a radian angle x.
2. double sin(double x)
Returns the sine of a radian angle x.
3. double exp(double x)
4. double log(double x)
Returns the natural logarithm (base-e logarithm) of x.
6. double sqrt(double x)
Returns the square root of x.
10. What is a function prototype?
Function prototype is a declaration statement that identifies function with function name,
data type, a list of a arguments. All the function need to be declared before they are used. (i.e.
called).
Syntax:
returntype functionname (parameter list);
a) Return type – data type of return value. It can be int, float, double, char, void etc.
b) Function name – name of the function
c) Parameter type list –It is a comma separated list of parameter types.
Example:
int add(int a, int b);
11. Differentiate call by value and call by reference.
In C language, there are two methods for parameter passing. They are,
Call by Value or Pass by Value
Call by Reference or Pass by Reference
Call by Value Call by Reference
Values of actual arguments are passed to formal Address of actual arguments is passed to
arguments. formal arguments.
Actual & formal parameters refer different Actual & formal parameters refer same
location location
Changes made in formal parameters not Changes made in formal parameters
reflected back to the calling function reflected back to the calling function
statements;
return (value);
ADDITIONAL PROGRAMS
1. Computation of sine series:
#include<stdio.h>
#include<conio.h>
void main()
{
int i, n;
float x, sum, t;
printf(" Enter the value for x : ");
scanf("%f",&x);
printf(" Enter the value for n : ");
scanf("%d",&n);
x=x*3.14159/180;
t=x;
sum=x;
/* Loop to calculate the value of Sine */
for(i=1;i<=n;i++)
{
t=(t*(-1)*x*x)/(2*i*(2*i+1));
sum=sum+t;
}
printf(" The value of Sin(%f) = %.4f",x,sum);
getch();
}
Output:
Enter the value for x :45
Enter the value for n: 5
The value of Sin(0.7853980 = 0.7071
2. Scientific calculator using built-in functions:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int choice, i, a, b;
float x, y, result;
do
{
printf(“\nSelect your operation (0 to exit):\n”);
printf(“1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n”);
result = x / y;
printf(“\nResult: %f”, result);
break;
case 5:
printf(“Enter X: “);
scanf(“%f”, &x);
result = sqrt(x);
printf(“\nResult: %f”, result);
break;
case 6:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = pow(x, y);
printf(“\nResult: %f”, result);
break;
case 7:
printf(“Enter X: “);
scanf(“%f”, &x);
result = pow(x, 2);
printf(“\nResult: %f”, result);
break;
case 8:
printf(“Enter X: “);
scanf(“%f”, &x);
result = pow(x, 3);
printf(“\nResult: %f”, result);
break;
case 9:
printf(“Enter X: “);
scanf(“%f”, &x);
result = pow(x, -1);
printf(“\nResult: %f”, result);
break;
case 10:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
case 16:
printf(“Enter X: “);
scanf(“%d”, &a);
printf(“\nEnter Y: “);
scanf(“%d”, &b);
result = a % b;
printf(“\nResult: %d”, result);
break;
case 17:
printf(“Enter X: “);
scanf(“%f”, &x);
result = sin(x * 3.14159 / 180);
printf(“\nResult: %.2f”, result);
break;
case 18:
printf(“Enter X: “);
scanf(“%f”, &x);
result = cos(x * 3.14159 / 180);
printf(“\nResult: %.2f”, result);
break;
case 19:
printf(“Enter X: “);
scanf(“%f”, &x);
result = tan(x * 3.14159 / 180);
printf(“\nResult: %.2f”, result);
break;
case 20:
printf(“Enter X: “);
scanf(“%f”, &x);
result = 1 / (sin(x * 3.14159 / 180));
printf(“\nResult: %.2f”, result);
break;
case 21:
printf(“Enter X: “);
scanf(“%f”, &x);
result = 1 / tan(x * 3.14159 / 180);
printf(“\nResult: %.2f”, result);
break;
case 22:
printf(“Enter X: “);
scanf(“%f”, &x);
result = 1 / cos(x * 3.14159 / 180);
printf(“\nResult: %.2f”, result);
break;
default:
printf(“\nInvalid Choice!”);
}
} while(choice);
getch();
}
Output
Select your operation (0 to exit):\n”);
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square root
6. X ^ Y
7. X ^ 2
8. X ^ 3
9. 1 / X
10. X ^ (1 / Y)
11. X ^ (1 / 3)
12. 10 ^ X
13. X!
14. %
15. log10(x)
16. Modulus
17. Sin(X)
18. Cos(X)
19. Tan(X)
20. Cosec(X)
21. Cot(X)
22. Sec(X)
Enter your Choice: 3
Enter x: 4
Enter y: 5
Result= 20
}
else
{
printf("\nElement %d Found at Position %d\n", element, position + 1);
}
getch();
}
Output:
Enter the Limit of Elements in Array: 5
Enter 5 Elements in Array:
1 2 3 4 5
Enter Element To Search:3
Element 3 Found at Position 3
4. Sorting of names
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include<conio.h>
static int myCompare (const void * a, const void * b)
{
return strcmp (*(const char **) a, *(const char **) b);
}
void sort(const char *arr[], int n)
{
qsort (arr, n, sizeof (const char *), myCompare);
}
void main ()
{
const char *arr[] = {"computer", "science", "Language"};
int n = sizeof(arr)/sizeof(arr[0]);
int i;
printf("Given array is\n");
for (i = 0; i < n; i++)
printf("%d: %s \n", i, arr[i]);
sort(arr, n);
printf("\nSorted array is\n");
for (i = 0; i < n; i++)
printf("%d: %s \n", i, arr[i]);
getch();
}
Output
Given array is
0: computer
1: science
2: Language
Sorted array is
0: computer
1: Language
2: Language
5. Changing the value of a variable using pass by reference
#include<stdio.h>
#include<conio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int *,int *);
a=10;
b=20;
printf("\n Before swapping: a= %d and b= %d",a,b);
swap(&a,&b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
void swap(int *a1,int *b1)
{
int t;
t = *a1;
*a1 = *b1;
*b1 = t;
}
Output:
Before swapping: a = 10 and b = 20
After swapping: a = 20 and b = 10
6. Check a given string is palindrome or not
# include<stdio.h>
#include<string.h>
#include<conio.h>
void main ()
{
int diff;
char input[20], copy[20];
printf (“Enter input string :”);
scanf (“%s”, input);
strupr(input); // convert into upper case letter
strcpy(copy, input); // take a copy of the input string
strrev(copy); // reverse the input string
diff = strcmp(input, copy); //compare input & reverse copy
if(diff == 0)
printf (“Given String is a palindrome”);
else
printf(“Given string is not a palindrome”);
getch();
}
Output:
`Enter input string: malayalam
Given string is a palindrome
7. Sum of Natural Numbers Using Recursion
#include <stdio.h>
#include<conio.h>
int addNumbers(int n);
void main()
{
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
printf("Sum = %d",addNumbers(num));
getch();
}
int addNumbers(int n)
{
if(n != 0)
return n + addNumbers(n-1);
else
return n;
}
Output:
Enter a positive integer: 20
Sum = 210
UNIT IV
STRUCTURES AND UNION
Structure - Nested structures – Pointer and Structures – Array of structures – Self referential
structures – Dynamic memory allocation - Singly linked list – typedef – Union - Storage classes
and Visibility.
4.1 STRUCTURE
Structure is a user defined data type that allows you to hold different data type of
elements. Each element in the structure is called as member. It is used to store student
information, employee information, product information, book information etc.
Defining structure
struct employee
{
int id;
char name[50];
float salary;
};
void main
{
struct employee e1, e2;
}
Method2:
Declare the variable of the structure at the time of defining the structure.
struct employee
{
int id;
char name[50];
float salary;
}e1,e2;
Which approach is good
• If no. of variable are not fixed, use method1. It provides you flexibility to declare the
structure variable many times.
• If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in
main() fuction.
Accessing members of structure
There are two ways to access structure members:
1. By using . (member or dot operator)
2. By using -> (structure pointer operator)
Syntax:
structurevariable.membername
structurevariable→membername
Example:
S1.name
S1→name
4.1.2 Initialization of Structure
Like normal variables, the structure variables can also be initialized. A structure is
initialized by assigning some constants to the members of the structure. By default, the members
of type int and float are initialized to zero and the members of type char and string are initialized
to ‘\0’
Method 1
struct student
{
int Reg_No;
char name[20];
}S1 = {4001, “Joshna”};
Method 2
struct student
{
int Reg_No;
char name[20];
};
void main()
{
struct student S1 = {4001, “Joshna”};
}
Program: Store student Information and Display it Using Structure
#include <stdio.h>
#include<conio.h>
struct student
{
char name[50];
int roll;
float marks;
} s;
void main()
{
printf("Enter student information:\n");
printf("Enter student name: ");
scanf("%s", s.name);
printf("Enter roll number: ");
scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);
printf("Displaying Information:\n");
printf("Name: %s\n”,s.name);
printf("Roll number: %d\n",s.roll);
printf("Marks: %f\n", s.marks);
getch();
}
Department of CSE Page 137
CS3251 PROGRAMMING IN C 2023
Output
Enter information:
Enter name: Jack
Enter roll number: 23
Enter marks: 34.5
Displaying Information:
Name: Jack
Roll number: 23
Marks: 34.5
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
b) Embedded structure
We can define structure within the structure also. It requires less code than previous way.
But it can't be used in many structures.
Syntax:
struct structure1
{
---
---
struct structure2
{
---
---
---
} v1;
}v2;
Example
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp;
Accessing Nested Structure
We can access the member of nested structure by Outer Structure. Nested Structure
members are accessed using dot operator.
Here, Date‘ structure is nested within Employee Structure. Members of the ‘Date‘ can be
accessed using ’employee’. emp1 & doj are two structure names (Variables)
• Accessing Month Field : emp1.doj.month
• Accessing day Field : emp1.doj.day
Department of CSE Page 139
CS3251 PROGRAMMING IN C 2023
Program:
#include <stdio.h>
#include <conio.h>
struct student
{
char name[50];
int roll;
float marks;
}s;
void main()
{
struct student *ptr;
ptr = &s;
structures in C can be defined as the collection of multiple structures variables where each
variable contains information about different entities.
Syntax
struct structname
{ Datatype member1;
Datatype member2;
. . .
Datatype member n;
}arrayname[ size];
struct structurename
{ Datatype member1;
Datatype member2;
. . .
Datatype member n;
};
void main()
{
struct structurename arrayname[size];
}
Example
struct student
{ int rollno;
float marks;
}s[2];
s[1] s[2]
void main()
{
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++)
{
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
getch();
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonu
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Raja
Student Information List:
Rollno:1, Name:Sonu
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Raja
10 20 30 40 X
ob1 ob2
Fig 4.2: Self Referential Structure with Single Link
Program
#include <stdio.h>
#include<conio.h>
struct node
{
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob1; // Node1
// Intialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
struct node ob2; // Node2
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
// Linking ob1 and ob2
ob1.link = &ob2;
// Accessing data members of ob2 using ob1
printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
getch();
}
Output:
30
40
Self Referential Structure with Multiple Links:
Self referential structures with multiple links can have more than one self-pointers. Many
complicated data structures can be easily constructed using these structures. Such structures can
easily connect to more than one nodes at a time. The following example shows one such
structure with more than one links.
X 10 20
30
ob1 ob2 ob3
Fig 4.3: Self Referential Structure with Multiple Links
Applications:
Self referential structures are very useful in creation of other complex data structures like:
• Linked Lists
• Stacks
• Queues
• Trees
• Graphs etc
Example
p = (int *) malloc(100 * sizeof(int));
A memory space equivalent to 100 times the size of an int bytes is reserved. The
address of the first byte of the allocated memory is assigned to the pointer p of type int.
free(ptr);
getch();
}
Output:
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
4.6.2 calloc( )
Allocates space for an array of elements, initializes them to zero and then returns a
pointer to the memory.
Synatx:
ptr=(cast-type*)calloc(number, byte-size)
Example:
int *ptr = calloc(10, sizeof (int));
Program:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
Department of CSE Page 149
CS3251 PROGRAMMING IN C 2023
getch();
}
Output:
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
Diffrence between malloc() and calloc()
calloc() malloc()
calloc() initializes the allocated memory with 0 malloc() initializes the allocated memory with
value. garbage values.
Number of arguments is 2 Number of argument is 1
Syntax : Syntax :
ptr=(cast-type*)calloc(number, byte-size) p = (type *) malloc (byte_size);
4.6.3 realloc()
It modifies the size of previously allocated space. If memory is not sufficient for malloc()
or calloc(), we can reallocate the memory by realloc() function. It changes the memory size.
Synatx:
ptr=realloc(ptr, new-size)
Program
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void main ()
{
char *str;
str = (char *) malloc(15);
strcpy(str, "computer programming");
printf("String = %s”, str);
/* Reallocating memory */
str = (char *) realloc(str, 25);
strcpy(str, "computer programming and c programming");
printf("String = %s”,str);
free(str);
getch();
}
Output
String = computer programming
String = computer programming and c programming
4.6.4 free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed
on their own. We must explicitly use free() to release the space.
Syntax
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
}
4.7.2 Traverse a linked list
Displaying the contents of a linked list is very simple. We keep moving the temp node to
the next one and display its contents.
struct node *temp = head;
printf("\n\nList elements are - \n");
while(temp != NULL)
{
printf("%d --->",temp->data);
temp = temp->next;
}
4.7.3 Insert elements to linked list
We can insert elements to either beginning, middle or end of linked list.
Insert at beginning
• Allocate memory for new node
• Store data
• Change next of new node to point to head
• Change head to point to recently created node
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
newNode->next = head;
head = newNode;
Insert at end
• Allocate memory for new node
• Store data
• Traverse to last node
• Change next of last node to recently created node
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
newNode->next = NULL;
struct node *temp = head;
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
Insert to middle
• Allocate memory and store data for new node
#include<conio.h>
struct node
{
int data;
struct node *next;
};
void display(struct node* head)
{
struct node *temp = head;
printf("\n\nList elements are - \n");
while(temp != NULL)
{
printf("%d --->",temp->data);
temp = temp->next;
}
}
void insertAtMiddle(struct node *head, int position, int value)
{
struct node *temp = head;
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = value;
int i;
for(i=2; inext != NULL)
{
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
}
void insertAtFront(struct node** headRef, int value)
{
struct node* head = *headRef;
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = value;
newNode->next = head;
head = newNode;
*headRef = head;
}
Department of CSE Page 154
CS3251 PROGRAMMING IN C 2023
Output
List elements are -
1 --->2 --->3 --->
List elements are -
4 --->1 --->2 --->3 --->
List elements are -
1 --->2 --->3 --->
List elements are -
1 --->2 --->3 --->5 --->
List elements are -
1 --->2 --->3 --->
4. 8 TYPEDEF
The typedef keyword allows us to create a new data type name from an existing data type. It
does not create a new data type but introduces a new name for existing type. A typedef
declaration does not reserve storage. We cannot use the typedef specifier inside a function
definition.
Syntax
typedef dataype newdatatype;
Example:
typedef int INTEGER;
INTEGER num=29;
Here, INTEGER is the new name of data type int.
Program
#include<stdio.h>
#include<conio.h>
typedef char uchar;
void main()
{
uchar ch = 'a';
printf("ch: %c\n", ch);
getch();
}
Output
ch : a
typedef in structure
We can use typedef with a structure. If the typedef keyword is given before the keyword
struct, then the struct becomes a new type. For example,
typedef struct student
{
int regno;
char name[20];
};
Now, student is the new data type. The variables of the structure student can be declared
as follows:
student stud;
Program
#include <stdio.h>
#include <string.h>
typedef struct student
{
int id;
char name[20];
float percentage;
} status;
void main()
{
status record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
getch();
}
Output
Id is: 1
Name is: Raju
Percentage is: 86.500000
4.9 UNION
Union is an user defined datatype in C programming language. It is a collection of
variables of different datatypes in the same memory location. We can define a union with many
members, but at a given point of time only one member can contain a value.
Syntax:
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition.
Example:
union Data
Department of CSE Page 158
CS3251 PROGRAMMING IN C 2023
{
int i;
float f;
char str[20];
} data;
Same memory location can be used to store multiple types of data.
Example: Program to display total memory size occupied by the union:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
Output:
Memory size occupied by data : 20
4.9.1 Accessing Union Members
To access any member of a union, use the member access operator (.). The member
access operator is coded as a period between the union variable name and the union member.
You would use union keyword to define variables of union type.
Example
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
Department of CSE Page 159
CS3251 PROGRAMMING IN C 2023
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
Output :
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
4.9.2 Difference between structure and union
#include<conio.h>
extern int a; // global variable
void main()
{
…..
}
Example
#include<stdio.h>
#include<conio.h>
void main()
{
register int a;
register int b;
…..
}
Summary of storage classes
Example
#include <stdio.h>
int main() {
int scope; // outer scope variable
scope = 10;
// inner block of code
{
float scope; // inner scope
scope = 2.98;
printf("Inner block scope : %f\n", scope);
}
printf("Outer block scope : %d\n", scope);
return 0;
Department of CSE Page 163
CS3251 PROGRAMMING IN C 2023
}
Output
Arrays Structures
An array is a collection of data items of A structure is a collection of data items of
same data type. different data types.
Arrays can only be declared. Structures can be declared and defined.
4. Define Structure in C
Structure is a user defined data type that allows you to hold different data type of
elements. Each element in the structure is called as member. A structure is declared by using the
keyword ‘struct’ followed by an structure name followed by the body of the structure.
Syntax:
struct structurename
{
Datatype member1;
Dat type member2;
. . .
Datatype member n;
} structurevariable1, structurevariable2, . . . structurevariablen;
Example:
struct student
{
int RegNo;
char name[20], dept[10];
}S1, S2;
5. What is dynamic memory allocation?
The process of allocating memory at the time of execution or at the runtime is called
dynamic memory allocation. It means dynamically allocate only the amount of memory needed.
The dynamic memory allocation functions in C are malloc( ), calloc( ), free( ) and realloc( ).
{
printf("\nSize of Structure : %d",sizeof(b1));
return(0);
}
Output:
Size of Structure : 26
14. Mention any two application of singly linked list
• It can be used to implement Stacks , Queues.
• It can also be used to implement Graphs in Adjacency list representation.
• It can be used to implement Hash Tables.
malloc calloc
The name malloc stands for memory The name calloc stands for contiguous
allocation. allocation.
Does not initialize the memory allocated Initializes the allocated memory to ZERO
malloc() takes one argument - number calloc() take two arguments- number of
of bytes. blocks and size of each block.
Syntax: Syntax:
malloc is faster than calloc. calloc takes little longer than malloc
because of the extra step of initializing the
allocated memory by zero.
The basic thing is to create a node. It can be done by using the malloc function.
start = (node*) malloc(sizeof(node))
This statement creates the starting node of list. A block of memory whose size is equal to
the sizeof(node) is allocated to the node pointer start. Typecasting is used because otherwise
malloc will return pointer to character
3. Write a C program to read the details of book name, author name and price of 200 books in a
library and display the total cost of the books.
4. Illustrate a C program to store the employee information using structure and search a
particular employee details.
5. Define a structure called student that would contain name, regno and marks of five subjects
and percentage. Write a C program to read the details of name, regno and marks of five subjects
for 30 students and calculate the percentage and display the name, regno, marks of 30 subjects
and percentage of each student.
6. Write a C program to print the Employee Salary Details Using Structure.
7. Explain singly linked list and write C Program to Implement Singly Linked List using
Dynamic Memory Allocation.
ADDITIONAL PROGRAMS
1. Student Grade(Mark Details) Using Structure
#include <stdio.h>
#include <conio.h>
struct Student
{
int rollno;
char name[30];
int mark1, mark2, mark3, total;
float Avg;
char grade;
} S[25];
void main()
{
int i, n;
clrscr();
printf(“ Enter the Number of Students : ”);
Department of CSE Page 170
CS3251 PROGRAMMING IN C 2023
scanf(“%d”, &n);
for ( i = 0 ; i < n ; i++)
{
printf(“ \n\n Enter the student %d details:”, i+1);
printf(“\n Rollno : ”);
scanf(“%d”, &S[i].rollno);
printf(“\n Name : ”);
scanf(“%s”, S[i].name);
printf(“\n Give 3 Subjects Mark”);
scanf(“%d %d %d”, &S[i].mark1, &S[i].mark2, &S[i].mark3);
S[i].total = S[i].mark1 + S[i].mark2 + S[i].mark3;
S[i].Avg = S[i].total / 3;
if ( S[i].Avg < 40 )
S[i].grade =’D’;
else if ( S[i].Avg < 60 )
S[i].grade=’C’;
else if ( S[i].Avg < 80 )
S[i].grade=’B’;
else
S[i].grade=’A’;
}
printf(“\t\t Student Mark List \n”);
printf(“\n Rollno Name \t Mark1 \t Mark2 \t Mark3 \t Total Average Grade ”);
for ( i = 0 ; i < n ; i++)
{
printf(“\n %d \t %s”, S[i].rollno, S[i].name);
printf(“\t %d \t %d \t %d \n”, S[i].mark1, S[i].mark2, S[i].mark3);
printf(“\t %d %4.2f \t %c”, S[i].total, S[i].avg, S[i].grade);
}
getch();
}
Output:
Enter the Number of Students : 2
Enter the student 1 details:
Rollno :100
Name : Sujith
Give 3 Subjects Mark : 60 75 45
Enter the students 2 details:
Rollno : 101
Name : Joshna
Give 3 Subjects Mark : 78 80 85
Student Mark List
Rollno Name Mark1 Mark2 Mark3 Total Average Grade
100 Sujith 60 75 45 180 60.00 B
101 Joshna 78 80 85 243 81.00 A
2. Employee Salary Details Using Structure
include <stdio.h>
#include <conio.h>
struct emp
{
int emp_code;
char emp_name[30];
float basic_pay, hra, da;
float tax, gross_pay, net_pay;
};
void main()
{
int i, n;
struct emp E[50];
Department of CSE Page 172
CS3251 PROGRAMMING IN C 2023
}
Output:
Enter the number of employee:2
Enter the employee 1 details:
Employee Code : 100
Employee Name : Venthan
Give Basic_pay, HRA & DA :
8000
600
6000
Give Tax : 400
Enter the employee 2 details:
Employee Code : 101
Employee Name : Venkat
Give Basic_pay, HRA & DA :
7000
300
5000
Give Tax : 300
Employee Salary List
------------------------------------------------------------------------------------------------------
Emp_No Employee_Name Basic_pay HRA DA Gross_Pay Tax Net_Pay
------------------------------------------------------------------------------------------------------
100 Venthan 8000 600 6000 14600 400 14200
101 Venkat 7000 300 5000 12300 300 12000
------------------------------------------------------------------------------------------------------
3. Book Details Using Structure
#include <stdio.h>
#include<conio.h>
Department of CSE Page 174
CS3251 PROGRAMMING IN C 2023
struct Book
{
char bname[20];
int pages;
int price;
}book[3];
void main()
{
int i;
for(i=0;i<3;i++)
{
printf("\nEnter the Name of Book : ");
scanf(&book[i].bname);
printf("\nEnter the Number of Pages : ");
scanf("%d",&book[i].pages);
printf("\nEnter the Price of Book : ");
scanf("%f",&book[i].price);
}
printf("\n--------- Book Details ------------ ");
for(i=0;i<3;i++)
{
printf("\nName of Book : %s",book[i].bname);
printf("\nNumber of Pages : %d",book[i].pages);
printf("\nPrice of Book : %f",book[i].price);
}
getch();
}
Output
Enter the Name of Book : ABC
Enter the Number of Pages : 100
Enter the Price of Book : 200
Enter the Name of Book : EFG
int i, n, No;
struct emp E[50];
clrscr();
include <stdio.h>
#include <conio.h>
struct
{
char name[20], author[20];
int price;
} book[200] ;
void main()
{
int i, Total = 0;
clrscr();
for ( i = 0 ; i < 200 ; i++)
{
printf(“Enter book detail %d \n”, i);
printf(“ Enter the book name & author : “);
scanf(“%s %s”, book[i].name, book[i].author);
printf(“\n Enter book price : ”);
scanf(“%d”, &book[i].price);
}
printf(“\t\t\t Book list whose price above 500 \n”);
printf(“Book Name Author Price \n”);
for ( i = 0 ; i < 200 ; i++)
{
Total = Total + book[i].price;
#include <stdio.h>
#include <string.h>
struct student_college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;
int main()
{
struct student_detail stu_data = {1, " Roja", 90.5, 71145,"Anna University"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", stu_data.percentage);
printf(" College Id is: %d \n", stu_data.clg_data.college_id);
printf(" College Name is: %s \n",stu_data.clg_data.college_name);
return 0;
}
Output:
Id is: 1
Name is: Roja
Percentage is: 90.500000
College Id is: 71145
College Name is: Anna University
Department of CSE Page 181
CS3251 PROGRAMMING IN C 2023
8. Program to find Sum of All Array Elements using Dynamic Memory Allocation
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *arr;
int limit,i;
int sum=0;
printf("Enter total number of elements: ");
scanf("%d",&limit);
/*allocate memory for limit elements dynamically*/
arr=(int*)malloc(limit*sizeof(int));
if(arr==NULL)
{
printf("Insufficient Memory, Exiting... \n");
return 0;
}
printf("Enter %d elements:\n",limit);
for(i=0; i<limit; i++)
{
printf("Enter element %3d: ",i+1);
scanf("%d",(arr+i));
/*calculate sum*/
sum=sum + *(arr+i);
}
printf("Array elements are:");
for(i=0; i<limit; i++)
printf("%3d ",*(arr+i));
printf("\nSum of all elements: %d\n",sum);
return 0; }
Output:
Department of CSE Page 182
CS3251 PROGRAMMING IN C 2023
UNIT V
FILE PROCESSING
Files – Types of file processing: Sequential access, Random access – Sequential access file -
Random access file - Command line arguments.
5.1 FILES
A file represents a sequence of bytes on the disk where a group of related data is
stored. File is created for permanent storage of data. It is a readymade structure.
5.1.1 Streams in C
Stream is a logical interface to a file. In C, there are three standard streams. They are:
a) Standard input (stdin)
b) Standard output (stdout)
c) Standard error (stderr)
Display
stderr stdout
Program
stdin
Keyboard
b) Binary Files
A binary file may contain any type of data that is encoded in binary form. It can be
processed either sequentially or randomly. Binary files require less space than the text files to
store the same piece of data. Binary file also ends with a EOF marker.
Binary files are mostly the .bin files in your computer. Instead of storing data in
plain text, they store it in the binary form (0's and 1's). They can hold higher amount of
data, are not readable easily and provides a better security than text files.
5.1.4 FILE OPERATIONS
The various operations involved in using files in C are
1. Declaring the file pointer variable
2. Opening the file
3. Reading data from file
4. Writing data to the file
5. Closing the file
1. Declaring the file pointer variable
A file pointer variable has to be declared in order to access a particular file.
Syntax:
FILE *file_pointer_name;
Example:
FILE *fp;
Here, fp is the file pointer variable.
2. Opening the file
A file must be opened before read/write operation. The function fopen() is used to
open a file and associate it with a stream. It returns a pointer to FILE structure if the file is
opened successfully, otherwise a NULL is returned.
Syntax:
FILE *fopen(const char *file_name, const char *mode);
Here, file_name - Every file has a file name. In fopen(), the file name is specified
along with the path of the file in the disk.
Example:
E:\\CSE\\Student.DAT (To represent a backslash in C, another backslash is
used.)
mode - Mode represents the type of processing that can be done with the file. The
following table shows the different modes of processing the file.
Mode Description
r Open a text file for reading
w Open a text file for writing
a Append to a text file.
• fputs()
• fputc()
• fwrite()
Function Description
fprintf() Used to write formatted data to the stream.
Syntax:
int fprintf(FILE *stream, const char *format, ...);
fputs() Used to write a line to the stream.
Syntax:
int fputs(const char *str, FILE *stream);
fputc() Used to write a character to the stream.
Syntax:
int fputc(int char, FILE *stream);
fwrite() Used to write number of elements specified by num of size specified by
size to the stream.
Syntax:
fwrite(const void *str, size_t size, size_t num, FILE *stream);
Table: 5.3 Functions to Write Data to File
5. Closing a File
The file (both text and binary) should be closed after reading/writing. The function
fclose() is used to close an already opened file. It disconnects the file pointer and flushes out
all the buffers associated with the file.
Syntax:
int fclose(FILE *fp);
Here fp is the file pointer of the file that has to be closed. The function returns zero
for successful completion and a non-zero value otherwise.
The function fcloseall() closes all the streams except the standard streams(stdin,
stdout, stderr) and flushes out the stream buffers.
Syntax:
int fcloseall(void);
6.Detecting the End-Of-File(EOF)
EOF is a symbolic constant defined in the library function stdio.h with a value -1.
There are two ways to detect an EOF.
• Compare the characters that has been read with the value of EOF (ie.,-1).
• Use the standard library function feof() defined in stdio.h. It returns one if EOF
has been reached and zero otherwise.
Syntax:
int feof(FILE *fp);
Program: Program To Open, Write And Close A File
# include <stdio.h>
# include <string.h>
int main( )
{
FILE *fp ;
char data[50];
printf( "Opening the file sample.c in write mode" ) ;
fp = fopen("sample.c", "w") ; // opening an existing
file
if ( fp == NULL )
{
printf( "Could not open file sample.c" ) ;
return 1;
}
printf( "\n Enter some text from keyboard” ); // getting input from user
while ( strlen ( gets( data ) ) > 0 )
{ // writing in the file
fputs(data, fp) ;
fputs("\n", fp) ;
}
printf("Closing the file sample.c") ;
fclose(fp) ; // closing the file
return 0; }
Output:
Opening the file sample.c in write mode
Enter some text from keyboard
Hai, How are you?
Closing the file sample.c
… …
1 2 3 4 5 6 7 8
1 3 7 2 8 6 4 5
EXAMPLE PROGRAM:
Finding average of numbers stored in sequential access file
#include <stdio.h>
#include <math.h>
// Read the numbers and return average
float average(FILE *input)
{
float term,sum;
int n;
sum = 0.0;
n = 0;
while(!feof(input))
{
fscanf(input,"%f",&term);
sum = sum + term;
n = n + 1;
}
return sum/n;
}
int main ()
{
FILE *input;
float avg;
input = fopen("data.txt","r");
avg = average(input);
fclose(input);
printf("The average of the numbers is %f.\n",avg);
return 0;
}
Output:
/* Data in data.txt
10 11 12 13 14 15. */
The average of the numbers is 12.5
Syntax:
long ftell(FILE *fp);
Here, fp – file pointer.
5.4.3 rewind()
This function is used to move the file pointer to the beginning of the file. This
function is useful when we open file for update.
Syntax:
void rewind(FILE *fp);
Here, fp – file pointer.
It is impossible to determine if rewind() was successful or not.
5.4.4 fgetpos()
The fgetpos() is used to determine the current position of the stream. The fgetpos
function stores the current position of stream into the object pointed to by pos. The fgetpos
function returns zero if successful. If an error occurs, it will return a nonzero value.
Syntax:
int fgetpos(FILE *stream, fpos_t *pos);
Here,
stream - The stream whose current position is to be determined.
pos - The current position of stream to be stored.
5.4.5 fsetpos()
The fsetpos() function moves the file position indicator to the location specified by
the 'pos' returned by the fgetpos() function. If fsetpos() function successful, it return zero
otherwise returns nonzero value.
Syntax:
int fsetpos(FILE *stream, const fpos_t *pos);
Here,
stream − This is the pointer to a FILE object that identifies the stream.
pos − This is the pointer to a fpos_t object containing a position previously
obtained with fgetpos.
5.4.6 Difference Between Sequential Access Files And Random Access Files
Sequential Access Files Random Access Files
Sequential Access to a data file means that Random Access to a file means that the
the computer system reads or writes computer system can read or write
information to the file sequentially, starting information anywhere in the data file.
from the beginning of the file and proceeding
step by step.
When you access information in the same In a random access file, you can search
order all the time, sequential access is faster through it and find the data you need more
than random access. easily.
To read the last record of the file, we have to To read the last record of the file, we can
read all the records from the beginning. read the last record directly.
Example: Tape drives Example: Hard drives
EXAMPLE PROGRAM: Transaction Processing Using Random Access Files
struct clientData
{
unsigned int acctNum;
char lastName[ 15 ];
char firstName[ 10 ];
double balance;
};
unsigned int enterChoice( void );
void textFile( FILE *readPtr );
void updateRecord( FILE *fPtr );
void newRecord( FILE *fPtr );
void deleteRecord( FILE *fPtr );
int main( void )
{
FILE *cfPtr;
unsigned int choice;
if ( ( cfPtr = fopen( "credit.dat", "rb+" ) ) == NULL )
{
puts( "File could not be opened." );
}
else
{
while ( ( choice = enterChoice() ) != 5 )
{
switch ( choice )
{
// create text file from record file
case 1:
textFile( cfPtr );
break;
// update record
case 2:
updateRecord( cfPtr );
break;
// create record
case 3:
newRecord( cfPtr );
break;
// delete existing record
case 4:
deleteRecord( cfPtr );
break;
default:
puts( "Incorrect choice" );
break;
}
}
fclose( cfPtr );
}
}
void textFile( FILE *readPtr )
{
FILE *writePtr;
int result;
struct clientData client = { 0, "", "", 0.0 };
if ( ( writePtr = fopen( "accounts.txt", "w" ) ) == NULL )
{
puts( "File could not be opened." );
}
else
{
rewind( readPtr ); // sets pointer to beginning of file
fprintf( writePtr, "%-6s%-16s%-11s%10s\n", "Acct", "Last Name",
"First
Name","Balance" );
while ( !feof( readPtr ) )
{
result = fread(&client, sizeof( struct clientData ), 1, readPtr);
// write single record to text file
if ( result != 0 && client.acctNum != 0 )
{
fprintf( writePtr, "%-6d%-16s%-11s%10.2f\n",
client.acctNum,client.lastName,client.firstName,
client.balance);
}
}
fclose( writePtr );
}
}
void updateRecord( FILE *fPtr )
{
unsigned int account;
double transaction;
struct clientData client = { 0, "", "", 0.0 };
printf( "%s", "Enter account to update ( 1 - 100 ): " );
scanf( "%d", &account );
fseek( fPtr, ( account - 1 ) * sizeof( struct clientData ),SEEK_SET );
fread( &client, sizeof( struct clientData ), 1, fPtr );
if ( client.acctNum == 0 )
{
printf( "Account #%d has no information.\n", account );
}
else
{
printf( "%-6d%-16s%-11s%10.2f\n\n",client.acctNum,
client.lastName, client.firstName, client.balance );
printf( "%s", "Enter charge ( + ) or payment ( - ): " );
scanf( "%lf", &transaction );
client.balance += transaction;
printf( "%-6d%-16s%-11s%10.2f\n",client.acctNum, client.lastName,
client.firstName, client.balance );
fseek( fPtr, ( account - 1 ) * sizeof( struct clientData ),SEEK_SET );
// write updated record over old record in file
fwrite( &client, sizeof( struct clientData ), 1, fPtr );
}
}
void deleteRecord( FILE *fPtr )
{
struct clientData client;
struct clientData blankClient = { 0, "", "", 0 };
unsigned int accountNum;
printf( "%s", "Enter account number to delete ( 1 - 100 ): " );
scanf( "%d", &accountNum );
fseek( fPtr, ( accountNum - 1 ) * sizeof( struct clientData ),SEEK_SET );
fread( &client, sizeof( struct clientData ), 1, fPtr );
if ( client.acctNum == 0 )
{
printf( "Account %d does not exist.\n", accountNum );
}
else
{
fseek( fPtr, ( accountNum - 1 ) * sizeof( struct
clientData ),SEEK_SET );
// replace existing record with blank record
fwrite( &blankClient,sizeof( struct clientData ), 1, fPtr );
}
}
void newRecord( FILE *fPtr )
{
struct clientData client = { 0, "", "", 0.0 };
unsigned int accountNum;
printf( "%s", "Enter new account number ( 1 - 100 ): " );
scanf( "%d", &accountNum );
fseek( fPtr, ( accountNum - 1 ) * sizeof( struct clientData ),SEEK_SET );
fread( &client, sizeof( struct clientData ), 1, fPtr );
if ( client.acctNum != 0 )
{
printf( "Account #%d already contains
information.\n",client.acctNum );
}
else
{
printf( "%s", "Enter lastname, firstname, balance\n? " );
scanf( "%14s%9s%lf", &client.lastName, &client.firstName,
&client.balance );
client.acctNum = accountNum;
fseek( fPtr, ( client.acctNum - 1 ) *sizeof( struct clientData ),
SEEK_SET );
fwrite( &client,sizeof( struct clientData ), 1, fPtr );
}
}
unsigned int enterChoice( void )
{
unsigned int menuChoice;
printf( "%s", "\nEnter your choice\n"
"1 - Display a formatted text file of accounts\n"
"2 - update an account\n"
"3 - add a new account\n"
int i;
clrscr();
printf("Total number of arguments: %d",argc);
for(i=0;i< argc;i++)
{
printf("\n %d argument: %s",i,argv[i]);
getch();
}
}
Output:
C:/TC/BIN>TCC mycmd.c
C:/TC/BIN>mycmd 10 20
Number of Arguments: 3
0 arguments c:/tc/bin/mycmd.exe
1 arguments: 10
2 arguments: 20
interpret. Text files can be processed sequentially, while binary files can be processed either
sequentially or randomly.
4. What is the advantage of a random access file?
When the data stored in a file is very large, random access can be used to search
through it quickly. A random access file let's you to jump directly to the location where the
required data is present.
5. What is a sequential access file?
The data items in a sequential access file are arranged one after another in a sequence.
Each data item can be accessed in the same order in which they have been stored. It is only
possible to read a sequential file from the beginning. To access a particular data within the
sequential access file, data has to be read one data at a time, until the required data is reached.
6. What is a file?
File is a collection of data stored on secondary storage device such as Hard Disk. It is
used to store the data permanently. A file is used when the real life application involves large
amount of data.
7. What are the basic operations of a file?
The basic operations in files are,
• Creation of a new file
• Opening an existing file
• Reading data from a file
• Writing data to a file
• Closing a file
8. Give the syntax to open a file.
The function fopen() is used to open a file.
Syntax:
FILE *fopen(const char *file_name, const char *mode);
Where file_name represents the name of the file to be opened along with it's
path,
mode represents the type of processing that can be done with the file.
9. What is meant by command line arguments?
Any input value passed through command prompt at the time of running of program is
known as command line argument. It is used when you want to control your C program from
outside.
Syntax:
int main(int argc, char *argv[])
Here, argc holds the number of arguments on the command-line and argv is an array
of string pointers.
10. What is the use of ftell() function?
ftell () function gives current position of file pointer. It is at the position at which the
next input or output operation will be performed.
Syntax:
long ftell(FILE *stream);
Here, stream points to the file whose file position has to be determined.
11. What is the use of rewind() function?
The rewind function is used to move file pointer position to the beginning of the file.
Syntax:
void rewind (FILE *fp);
Here, fp is the file pointer.
12. How to close an open file?
The fclose() function is used to close an open file. It disconnects the file pointer from
the file and flushes all the buffers associated with it.
Syntax:
int fclose(FILE *fp);
Here fp is the file pointer of the file that has to be closed.
13. Define the term stream.
Stream is a logical interface to a file. In C, there are three standard streams. They are:
1. Standard input (stdin)
2. Standard output (stdout)
3. Standard error (stderr)
14. What are different modes in which a file can be opened?
Mode Description
r Open a text file for reading
w Open a text file for writing
a Append to a text file.
rb Open a binary file for reading
wb Open a binary file for writing
i.fscanf()
ii.fprintf()
iii.fseek()
iv.ftell()
PART C (Possible Questions)
1. Write a C Program to write all the members of an array of structures to a file using
fwrite(). Read the array from the file and display on the screen.(5) (APRIL/MAY 2018)
2. Write the case study of "How sequential access file is different from random access file".
(10) (APRIL/MAY 2018)
3. Write a C Program to calculate the factorial of a number by using the command line
argument.
4. Write a C Program to read content of a File and display it.
5. Write a C Program to print the contents of a File in reverse.
6. Write a C program to insert, update, delete and append telephone details into a telephone
directory using random access file.
7. Write a C program to count the number of account holders whose balance is less than the
minimum balance using sequential access file.
ADDITIONAL PROGRAMS
1. Program To Read A File And Store Into An Array
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LSIZ 128
#define RSIZ 10
int main(void)
{
char line[RSIZ][LSIZ];
char fname[20];
FILE *fptr = NULL;
int i = 0;
int tot = 0;
printf("\n\n Read the file and store the lines into an array :\n");
printf("------------------------------------------------------\n");
printf(" Input the filename to be opened : ");
scanf("%s",fname);
fptr = fopen(fname, "r");
while(fgets(line[i], LSIZ, fptr))
{
line[i][strlen(line[i]) - 1] = '\0';
i++;
}
tot = i;
printf("\n The content of the file %s are : \n",fname);
for(i = 0; i < tot; ++i)
{
printf(" %s\n", line[i]);
}
printf("\n");
return 0;
}
Output:
Read the file and store the lines into an array :
------------------------------------------------------
Input the filename to be opened : test.txt
The content of the file test.txt are :
Dalton
Stigi
Johan
Jayden
2. Program to copy a file into another
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr1, *fptr2;
char ch, fname1[20], fname2[20];
printf("\n\n Copy a file in another name :\n");
printf("----------------------------------\n");
printf(" Input the source file name : ");
scanf("%s",fname1);
fptr1=fopen(fname1, "r");
if(fptr1==NULL)
{
printf(" File does not found or error in opening.!!");
exit(1);
}
printf(" Input the new file name : ");
scanf("%s",fname2);
fptr2=fopen(fname2, "w");
if(fptr2==NULL)
{
printf(" File does not found or error in opening.!!");
fclose(fptr1);
exit(2);
}
while(1)
{
ch=fgetc(fptr1);
if(ch==EOF)
break;
else
fputc(ch, fptr2);
}
printf(" The file %s copied successfully in the file %s. \n\n",fname1,fname2);
fclose(fptr1);
fclose(fptr2);
getchar(); }
Output:
Copy a file in another name :
----------------------------------
Input the source file name : test.txt
Input the new file name : test1.txt
The file test.txt copied successfully in the file test1.txt.
3. Program to Count No. of Words and Characters in a File
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr;
char ch;
int wrd=1,charctr=1;
char fname[20];
printf("\n\n Count the number of words and characters in a file :\n");
printf("---------------------------------------------------------\n");
printf(" Input the filename to be opened : ");
scanf("%s",fname);
fptr=fopen(fname,"r");
if(fptr==NULL)
printf(" File does not exist or can not be opened.");
else
{
ch=fgetc(fptr);
printf(" The content of the file %s are : ",fname);
while(ch!=EOF)
{
printf("%c",ch);
if(ch==' '||ch=='\n')
wrd++;
else
charctr++;
ch=fgetc(fptr);
}
printf("\n The number of words in the file %s are : %d\n",fname,wrd-
2);
printf(" The number of characters in the file %s are : %d\n\n", fname,
charctr-1);
}
fclose(fptr);
}
Output:
Count the number of words and characters in a file :
---------------------------------------------------------
Input the filename to be opened : test.txt
The content of the file test.txt are :
Dalton
Stigi
Johan
Jayden
The number of words in the file test.txt are : 4
{
int i, n, ch;
printf("1] Create a Record\n");
printf("2] Display Records\n");
printf("3] Update Records\n");
printf("4] Exit");
while (1)
{
printf("\nEnter your choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
fp = fopen(argv[1], "a");
create();
break;
case 2:
fp1 = fopen(argv[1],"rb");
display();
break;
case 3:
fp1 = fopen(argv[1], "r+");
update();
break;
case 4:
exit(0);
}
}
}
void create()
{
int i;
char *p;
if (fp1 == NULL)
{
printf("File cant be opened");
return;
}
printf("Enter employee id to update : ");
scanf("%d", &id);
emp3 = (struct emp *)malloc(1*sizeof(struct emp));
emp3->name=(char *)malloc(size*sizeof(char));
while(i<=count)
{
fread(&emp3->id, sizeof(emp3->id), 1, fp1);
fread(emp3->name,size,1,fp1);
if (id == emp3->id)
{
printf("Enter new name of emplyee to update : ");
scanf(" %[^\n]s", s);
fseek(fp1, -204L, SEEK_CUR);
fwrite(&emp3->id, sizeof(emp3->id), 1, fp1);
fwrite(s, size, 1, fp1);
flag = 1;
break;
}
i++;
}
if (flag != 1)
{
printf("No employee record found");
flag = 0;
}
fclose(fp1);
free(emp3->name);
free(emp3); }
Output:
$ a.out emprec1
1] Create a Record
2] Display Records
3] Update Records
4] Exit
Enter your choice : 1
Enter name of employee : Johan
Enter emp id : 100
Enter your choice : 1
Enter name of employee : Jayden
Enter emp id : 200
Enter your choice : 1
Enter name of employee : Dalton
Enter emp id : 300
Enter your choice : 1
Enter name of employee : Stigi
Enter emp id : 400
Enter your choice : 1
Enter name of employee : Rose
Enter emp id : 500
Enter your choice : 2
100 Johan
200 Jayden
300 Dalton
400 Stigi
500 Rose
Enter your choice : 3
Enter employee id to update : 400
Enter new name of emplyee to update : Sophia
Enter your choice : 2
100 Johan
200 Jayden
300 Dalton
400 Sophia
500 Rose
Enter your choice : 4
6. Program to Illustrate How a File Stored On the Disk Is Read
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr;
char filename[15];
char ch;
printf("Enter the filename to be opened \n");
scanf("%s", filename);
/* open the file for reading */
fptr = fopen(filename, "r");
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}
ch = fgetc(fptr);
while (ch != EOF)
{
printf ("%c", ch);
ch = fgetc(fptr);
}
fclose(fptr);
}
Output:
$ cc pgm96.c
$ a.out
Enter the filename to be opened
Hello.txt
Welcome
Be Happy always
Good luck
7. Program to Convert the Content of File to UpperCase
#include <stdio.h>
int to_upper_file(FILE *);
int main(int argc,char *argv[])
{
FILE *fp;
int status;
if (argc == 1)
{
printf("Insufficient Arguments:");
printf("No File name is provided at command line");
return;
}
if (argc > 1)
{
fp = fopen(argv[1],"r+");
status = to_upper_file(fp);
if (status == 0)
{
printf("\n The content of \"%s\" file was successfully converted
to upper case\n",argv[1]);
return;
}
if (status == -1)
{
printf("\n Failed to convert");
return;
}
}
}
int to_upper_file(FILE *fp)
{
char ch;
if (fp == NULL)
{
perror("Unable to open file");
return -1;
}
else
{
while (ch != EOF)
{
ch = fgetc(fp);
if ((ch >= 'a') && (ch <= 'z'))
{
ch = ch - 32;
fseek(fp,-1,SEEK_CUR);
fputc(ch,fp);
}
}
return 0;
}
}
Output
/*Input file : mydata
$ cat mydata
This is Johan
I like ice cream */
$ gcc file3.c
$ a.out mydata
The content of "mydata" file was successfully converted to upper case
}
fclose(fp1);
fclose(fp2);
}
long count_characters(FILE *f)
{
fseek(f, -1L, 2);
long last_pos = ftell(f); // returns the position of the last element of the file
last_pos++;
return last_pos;
}
Output
/* Data in the Input File test2
$ cat test2
Jayden is at his grandmas house. */
$ gcc file12.c
$ a.out test2 test_new
The FILE has been opened..
Number of characters to be copied 32
**File copied successfully in reverse order**
/* Data in the File test_new
$ cat test_new
.esuoh samdnarg sih ta si nedyaJ */
9. Program to Delete a File
#include<stdio.h>
main()
{
int status;
char file_name[25];
printf("Enter the name of file you wish to delete\n");
gets(file_name);
status = remove(file_name);
if( status == 0 )
{
printf("%s file deleted successfully.\n",file_name);
}
else
{
printf("Unable to delete the file\n");
perror("Error");
}
return 0;
}
Output
Enter the name of the file you wish to delete
Hello.txt
Hello.txt file deleted successfully
10. Program to write all the members of an array of structures to a file using fwrite().
Also read the array from the file and display on the screen. (APRIL/MAY 2018)
#include <stdio.h>
struct student
{
char name[50];
int mark;
};
int main()
{
struct student stud1[5], stud2[5];
FILE *fptr;
int i;
fptr = fopen("file.txt","wb");
for(i = 0; i < 5; ++i)
{
fflush(stdin);
printf("Enter name: ");
gets(stud1[i].name);
mark: 90
11. Find factorial of a number using command line arguments
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[])
{
int n=atoi(argv[1]);
int i,fact=1;
for(i=1;i<=n;i++)
fact*=i;
printf("Factorial of %d is %d", n, fact);
return 0;
}
Output
Factorial of 5 is 120
12. Insert, Update, Delete and Append Teleph
Random Access File
#include <stdio.h>
#include <conio.h>
#include <string.h>
struct person
{
char name[20];
long telno;
};
void appendData()
{
FILE *fp;
struct person obj;
clrscr();
fp=fopen("data.txt","a");
printf("*****Add Record****\n");
printf("Enter Name : ");
scanf("%s",obj.name);
printf("Enter Telephone No. : ");
scanf("%ld",&obj.telno);
fprintf(fp,"%20s %7ld",obj.name,obj.telno);
fclose(fp);
}
void showAllData()
{
FILE *fp;
struct person obj;
fp=fopen("data.txt","r");
printf("*****Display All Records*****\n");
printf("\n\n\t\tName\t\t\tTelephone No.");
printf("\n\t\t=====\t\t\t==========\n\n");
while(!feof(fp))
{
fscanf(fp,"%20s %7ld",obj.name,&obj.telno);
printf("%20s %30ld\n",obj.name,obj.telno);
}
fclose(fp);
getch();
}
void findData()
{
FILE *fp;
struct person obj;
char name[20];
int totrec=0;
fp=fopen("data.txt","r");
printf("*****Display SpecificRecords*****\n");
printf("\nEnter Name : ");
scanf("%s",&name);
while(!feof(fp))
{
fscanf(fp,"%20s %7ld",obj.name,&obj.telno);
if(strcmpi(obj.name,name)==0)
{
printf("\n\nName : %s",obj.name);
printf("\nTelephone No : %ld",obj.telno);
totrec++;
}
}
if(totrec==0)
printf("\n\n\nNo Data Found");
else
printf("\n\n===Total %d Record found===",totrec);
fclose(fp);
getch();
}
void main()
{
char choice;
while(1)
{
printf("*****TELEPHONE DIRECTORY*****\n\n");
printf("1) Append Record\n");
printf("2) Find Record\n");
printf("3) Read all record\n");
printf("4) exit\n");
printf("Enter your choice : ");
fflush(stdin);
choice = getche();
switch(choice)
{
case'1' : //call append record
appendData();
break;
case'2' : //call find record
findData();
break;
case'3' : //Read all record
showAllData();
break;
case'4' :
exit(1);
}
}
}
Output
*****TELEPHONE DIRECTORY*****
1) Append Record
2) Find Record
3) Read all record
4) exit
Enter your choice :1
*****Add Record****
Enter Name : johan
Enter Telephone No. : 9867453423
*****TELEPHONE DIRECTORY*****
1) Append Record
2) Find Record
3) Read all record
4) exit
Enter your choice :1
*****Add Record****
Enter Name : jayden
Enter Telephone No. : 8867453423
*****TELEPHONE DIRECTORY*****
1) Append Record
2) Find Record
3) Read all record
4) exit
Enter your choice :2
*****Display SpecificRecords*****
Enter Name : johan
Name : johan
Telephone No : 9867453423
===Total 1 Record found===
*****TELEPHONE DIRECTORY*****
1) Append Record
2) Find Record
3) Read all record
4) exit
Enter your choice :3
*****Display All Records*****
Name Telephone No.
===== ==========
johan 9867453423
jayden 8867453423
REFERENCES
ANNA UNIVERSITY
MODEL
QUESTION PAPERS
CS8251 – PROGRAMMING IN C
14. (a) Explain in detail about how to declare a structure and access members of a structure
with example.(13)
(OR)
(b) Explain about Nested structure with example.(13)
15. (a) Explain about command line argument with suitable example. (13)
(OR)
(b) Explain the following file operations: fscanf(), fprintf(), fseek(),ftell() with suitable
example. (13)
PART – C (1x15=15 Marks)
16. Write a C program to insert, update, delete and append telephone details into a telephone
directory using random access file. (15)
CS8251 – PROGRAMMING IN C
11. (a) (i) What are constants? Explain the various types of constants.(7)
(ii) Write short notes on Switch statements in C with example.(6)
(OR)
(b) Describe the various looping statements in C language and discuss with example.(13)
12. (a) What are the different types of string function? Write a C program to find whether the
given string is palindrome or not without using string functions. (13)
(OR)
(b) (i) Write a C program to find the determinant of the matrix. (8)
(ii) Write a C program to calculate mean for an array of elements.(5)
13. (a) (i) Write a C program to find the sum of digits using recursive function. (8)
(ii) Write a C program using pointers to read in an array of integers and print its
elements in reverse order.(5)
(OR)
(b) Write a C program for designing Scientific calculator using built-in functions. (13)
14. (a) Write a C program to create mark sheet for students using structure. (13)
(OR)
(b) Explain about the Self Referential structures with example.(13)
15. (a) Explain the read and write operations on a file with a suitable program.(13)
(OR)
(b) Write a C Program for Transaction processing using random access files.(13)
Second Semester
Computer Science and Engineering
CS8251 – PROGRAMMING IN C
11. (a) (i) Explain the different types of operators used in C with necessary program (8)
(ii) Write the C program to check the integer is palindrome or not. (5)
(OR)
(b) Describe the decision making statements and looping statements in C. (13)
12. (a) Write the C program to multiply two matrices (two-dimensional array) which will be
entered by user. The user will enter the order of a matrix and then its elements and similarly
input the second matrix. If the entered orders of 2 matrices are such that they can’t be
multiplied by each other, then an error message is displayed on the screen. (13)
(OR)
(b) (i) What are the different types of string function? Describe with their purpose. (5)
(ii) Write the C program to find the number of vowels, consonants, digits and white
space in a string. (8)
13. (a) (i) Explain the purpose of a function prototype. And specify the difference between
user defined function and built-in-function (8)
(ii) Write the program to find the value of sin(x) using series up to the given
accuracy and also print the sin(x) using library function (5)
(OR)
(b) What is the difference between pass by value and pass by reference? Write the C
coding for swapping two numbers using pass by reference (13)
14. (a) Define structure in C. Also specify the pointer and structure with example. (13)
(OR)
(b) (i) Write a C program for accessing structure member through pointer using dynamic
memory allocation. (6)
(ii) Write a short note on singly linked list and specify how the node are created in
singly linked list. (7)
15. (a) Explain the types of file processing with necessary examples.(13)
(OR)
(b) Write the C coding for finding average of numbers stored in sequential access
file.(13)
PART – C (1x15=15 Marks)
16. (i) Write the case study of "How Sequential Access File is different from Random Access
File". (10)
(ii) Write a C Program to write all the members of an array of structures to a file using
fwrite(). Read the array from the file and display on the screen.(5)
CS8251 – PROGRAMMING IN C
1. Differentiate between formatted and unformatted input statements. Give one example
for each.
2. What is the use of preprocessor directive?
3. Define an array.
4. Write a C function to compare two strings.
5. What is the need for functions?
6. What is the output of the following code fragment?
int x= 456, *p1, **p2;
pl=&x; p2=&p1;
printf (“Value of x is : %d\n”, x);
printf(“Value of *p1 is : %d\n”, p1);
printf (“Value of *p2 is : %d\n”, p2);
7. Compare and contrast a structure with an array.
8. What is the output of the following code fragment?
struct point
{
int x;
int y;
};
struct point origin, “PP;
main ()
{
pp = & origin;
Printf (" origin is (%d% d)\n", (*pp).x,pp-> y);
}
9. Why files are needed?
Department of CSE Page 236
CS3251 PROGRAMMING IN C 2023
11. (a) (i) What is the purpose of looping statements? Explain in detail the
operation of various looping statements in C with suitable examples. (12)
(ii) Write a C program to find the sum of 10 non-negative numbers entered by
the user. (4)
(OR)
(b) (i) What is a storage class? Explain the various storage classes jp C along
with suitable example. (12)
(ii) Write a C program to find the largest among 3 numbers entered by the
user. (4)
12. (a) Explain binary search procedure. Write a C program to perform binary
search and explain.
(16)
(OR)
(b) Discuss how you can evaluate the mean, median, mode for an array of
numbers. Write the C program to evaluate the mean, median and mode for an array
of numbers and explain. (16)
13. (a) What is recursion? Explain the procedure to compute sin(x) using recursive
functions. Write the C code for the same.(16)
(OR)
(b) What is pass by reference? Explain swapping of 2 values using pass by
reference in ‘C’.(16)
14. (a) What is dynamic memory allocation? Explain various C functions that are
used for the same with examples. (16)
(OR)
(b) What is a self-referential structures? Explain with suitable examples. (16)
15. (a) Explain in detail various operations that can be done on file giving suitable
examples.(16)
(OR)
(b) Explain in detail random access in files along with the functions used for the
same in C. Give suitable examples. (16)