You are on page 1of 74

faizi_+918137088810

C Programming

MODULE I

Topics:

Introduction to computer programming; Various I/O functions; Data types; Constants and
Variables; Escape Sequences; Type Casting; Preprocessor Directive; Storage Classes; Scope of
Variables; Mathematical Operators; Relational Operators; Branching Instructions; Logical
Operators; Conditional Operator; Precedence of Operators; Loops – for, while and do-
while, break and continue instructions, Nested Loops; Switch statement; Evaluation of ex
,sin(x), cos(x) ,Numerical Integration using Trapezoidal and Simpson’s rules.

Various I/O functions:

 Input statements
 getchar()
 gets()
 scanf()
 Output statements
 putchar()
 puts()
 printf()
getchar () – single character input function:
 getchar () is used to get or read a single character from the keyboard.
 The function does not require any arguments, through a pair of empty parenthesis must
follow the word getchar.
Syntax:
Character variable = getchar ();
char ch;
ch = getchar ();

putchar () - single character output function:


 putchar () is used to get write a single character to a standard output device.
 It must be expressed as an argument to the function, enclosed in parentheses, following the
word putchar
Syntax:
putchar (character variable);
char ch;
ch = getchar ();
putchar (ch);
scanf () – Entering input data:
 Input data can be entered into the computer by the function scanf()

Page 1 of 74
faizi_+918137088810
C Programming

scanf (“control string”, &arg1, &arg2……&argn);


 The control string consists of individual groups of characters, with one character group for
each input data item.
 Each character group must begin with a percent sign (%).
 In its simplest form, a single character group will consist of the percent sign, followed by a
conversion character which indicates the type of the corresponding data item.
 Within the control string, multiple character groups can be separated by whitespace character.
 Each variable name must be preceded by an ampersand (&) that represent the memory
address.
Conversion constants

d integer
f float
c char
s string
ld Long int
lf double

int a;
float b;
scanf (“%d %f”,&a,&b);

printf () – writing output data:


 Output data can be written from the computer onto a standard output device using the library
function printf()
printf (“control string”, arg1, arg2……argn);

int a;
float b;
scanf (“%d %f”, &a, &b);
printf (“%d %d”, a,b);
gets () and puts () functions

 The gets () and puts () functions, which facilitate the transfer of strings between the
computer and the standard input-output devices.
 Each of these functions accepts a single argument.
 The argument must be a data item that represents a string. The string may include
whitespace characters.

char s [10];

Page 2 of 74
faizi_+918137088810
C Programming

gets(s);
puts(s);

Data types:

'Data types’ means type of data, which are used to define a variable before its use. The
definition of a variable will assign storage for the variable and define the type of data that will
be held in the location.
C supports three classes of data types

Data Types

Primary Data Type Derived Data Type User defined


 int array enum
 float function typedef
 double
 char
 void

Integer type (int)


 Whole numbers, both positive and negative including zero within a specific range is included
in this type.
 The size of the integer value is limited to the range -32768 to 32768.
 In programs, integer type is represented by the keyword ‘int’.
 Most versions of C take 2 bytes of memory to store an integer.
 There are two other variations of integers.
 long int
 short int

 The usual memory requirement for short and long are 1 byte and 4 bytes respectively.
Floating-point type (float)
 The floating point data type is used to represent real numbers.
 The keyword float is used to declare floating point variables in programs.
 Floating point numbers are stored in 4 bytes (32 bits) with 6 digits of precision

Double

Page 3 of 74
faizi_+918137088810
C Programming

 When the accuracy provided by a float number is not sufficient, the type double can be used
to define the number.
 A double data type number uses 64 bits giving a precision of 14 digits.
 Double type represents the same data type that float represents, but with a great precision. To
extend the precision further, we may use long double which uses 80 bits.

float 4 bytes

8 bytes
double
long double
10 bytes

Character types (char)


 A single character can be defined as a character type data.
 Characters are usually stored in 1 byte (8 bits)
 The keyword char is used to declare character variables in programs.
Void type
 Void type has no values.
 This is usually used to specify the type of function.
 The type of a function is said to be void, when it does not return any value to the calling
function.
Constants
Constants in C refer to fixed values that do not change during the execution of a program.

Constants

Numeric Constants Character Constants

Integer Constants floating point Constants Single Character String Constant

Integer Constants
 Integer constant is an integer valued number
4

Page 4 of 74
faizi_+918137088810
C Programming

 It consists of a sequence of digits


There are three types of integers
 Decimal integer
 Octal integer
 Hexadecimal integer
Decimal integer
 It consists of a set of digits, 0 through 9.
 If the constant contains two or more digits, the first digit must be something other zero.
 Spaces, commas and nondigit characters are not permitted between digits.
Examples: 0, 1, 734,-321
Octal integer
 An Octal integer consists of any combinations of digits taken from the set 0 through 7.
 The first digit must be 0, in order to identify the constant as an octal number.
Examples: 0, 01, 0743, 07777
Hexadecimal integer
 A Hexadecimal integer constant must begin with 0x or 0X.
 It can be followed by any combination of digits taken from the sets 0 through 9 and A
through F
Examples: oX7FFF, 0xabcd
Floating-Point Constants:
 A floating point constant is a base 10 number that contains either a decimal point or an
exponent or both.
Examples: 0.2, 12.3
Single Character Constants
 A Single Character Constant contains a single character enclosed within a pair of single
quotation marks.
 Character constants have integer values known as ASCII (American Standard Code for
Information Interchange) values.
Examples: ‘5’, ‘X’, ‘ ’
String Constant
 A String Constant is a sequence of characters enclosed in double quotes.
 The characters may be letters, numbers, special characters and blank space.
 A character constant is not equivalent to the string constant.
 String constant does not have an equivalent integer value while a character constant has an
integer value.
Examples: “Hello”, “1987”
Variables:
A variable is a data name that may be used to store a data value. A variable name can be chosen
by the programmer in a meaningful way as to reflect its function or nature in the program.
Rules for Variable Name

Page 5 of 74
faizi_+918137088810
C Programming

 Should not be a keyword


 Must begin with a letter
 Can contain letters, numbers or underscore.
 Length should not be more than 8 characters, since only the first 8 characters are significant
 No other special characters are allowed including space
 Variable names are case sensitive
 A and a are different.

Variable Declaration
• Any variable must be declared (defined) before it can be used in the program.
Declaration does two things
 It tells the compiler what the variable name is
 It specifies what type of data the variable will hold
Syntax:
datatype variable_ name;

• Variables of the same type can be defined in one declaration:


datatype var_name1, var_name2, … , var_namen;

Examples: int a;
float b;
int a,b,c;

Assigning Values to Variables


 Values can be assigned to variables using the assignment operator ‘=’ as follows
Variable_name = value;
Count = 3;
 C permits multiple assignments in one line
Sum = 10; avg = 15;
 It is also possible to assign a value to a variable at the time the variable is declared.
int a =10;

Declaring a variable as constants:


const datatype variable_name = value;
const int count = 10;
 Const is a new datatype qualifier. This tells the compiler that the value of the int variable
count must not be modified by the program.

Escape Sequences (Back slash character constants)

Page 6 of 74
faizi_+918137088810
C Programming

 C supports some special back slash character constants that are used in output functions.
 It beginning with a back ward slash and is followed by one or more special characters.
\b back space
\n new line
\t horizontal tab
\v vertical tab
\0 null

Type Casting:
Type casting is a way to convert a variable from one data type to another data type.
Syntax:
(type_name) expression
Example:
Without type casting Type casting
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int a=5,b=2; int a=5,b=2;
float c; float c;
c= a/b; c= (float)a/(float)b;
printf("C =%f",c); printf("C =%f",c);
getch(); getch();
} }
Output Output
C = 2.000000 C = 2.500000

Preprocessor Directive:
The C pre-processor is a collection of statements, called directives that are executed at the
beginning of the compilation process. All preprocessor directives begin with #.
Example: #include, #define
Storage Classes:
There are four storage classes in C.
1. Automatic
2. Register
3. Static
4. External

Page 7 of 74
faizi_+918137088810
C Programming

Automatic
The keyword for this storage class is auto
Storage Memory
Default initial value Garbage value
Scope Local to the block in which the variable is defined
Life Till the control remains within the block in which the
variable is defined.

Register
Storage CPU registers
Default initial value Garbage value
Scope Local to the block in which the variable is defined
Life Till the control remains within the block in which the variable is
defined.

Static
Storage Memory
Default initial value Zero
Scope Local to the block in which the variable is defined
Life Value of the variable persists between different function
calls

External
An external variable can be assigned a value within one function, and this value can
be used within another function. The keyword for this storage class is extern.

Storage Memory
Default initial value Zero
Scope Global
Life As long as the programs execution come to an end

Operators
 Arithmetic operators
 Unary operators
 Binary operators
 Assignment operators
 Equalities and relational operators
 Logical operators
 Conditional operator

Arithmetic operators

Page 8 of 74
faizi_+918137088810
C Programming

 There are 2 types of arithmetic operators in C:


 Unary operators - operators that require only one operand.
 Binary operators - operators that require two operands.
Binary operators

Operation Operator
Addition +
Subtraction _
Multiplication *
Division /
Modulus %

Unary operators:

C includes a class of operators that act upon a single operand to produce a new value. Such
operators are known as Unary operators:
 There are two types of unary operators
 Increment Operator
 Decrement Operator
 The increment operator causes its operand to be increased by 1
 The decrement operator causes its operand to be decreased by 1
 i++ is equivalent to i = i + 1
 i-- is equivalent to i = i-1
 The increment and decrement operators can each be utilized two different ways, depending
on whether the operator is written before or after the operand.
 If the operator precedes the operand (++ i), then it is called as pre-increment operator and
the operand will be altered in value before it is utilized for its intended purpose within the
program.
 If the operator follows the operand (i++), then it is known as post-increment operator and
the value of the operand will be altered after it is utilized.
• Consider this example:
int a = 9;
printf(“%d\n”, a++);
printf(“%d”, a);

The output would be:


9
10
But if we have:

Page 9 of 74
faizi_+918137088810
C Programming

int a = 9;
printf(“%d\n”, ++a);
printf(“%d”, a);
The output would be:
10
10
 a++ would return the current value of a and then increment the value of a
 ++a on the other hand increment the value of a before returning the value
Relational Operator

Operator Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to

Equality Operators

Operator Meaning
== Equal to
!= Not equal to

Logical Operator

 There are 3 types of logical operators


 && - Logical AND -
All the conditions must be true for the whole expression to be true.
 || - Logical OR
The truth of one condition is enough to make the whole expression true.
 ! - Logical NOT (also called logical negation)
Reverse the meaning of a condition

Assignment Operators
These are used to form assignment expressions, which assign the value of an expression to an
identifier.
 The most commonly used assignment operator is ’=’
 Assignment operator = and equality operator = = are distinctly different
Identifier = expression;
Conditional operator

10

Page 10 of 74
faizi_+918137088810
C Programming

• The conditional operator (? :) is used to simplify an if/else statement.


Syntax:
Expression1? Expression2: Expression3

When evaluating a conditional expression, expression1 is evaluated first.


 If expn1 is true, then expn2 is evaluated and this becomes the value of the conditional
expression
 If expn1 is false, then expn3 is evaluated and this becomes the value of the conditional
expression

Example:
total > 60? grade = ‘P’: grade = ‘F’;

OR
grade = total > 60? ‘P’: ‘F’;
Control statements:
Control statements control the flow of execution depending upon certain conditions is true or
false.
There are three types of control statements:
 Conditional statements/ Branching statements
 Looping statements
 Jumping statements
Control statements

Conditional Looping Jumping

if for loop goto


if-else while loop break
nested-if-else do-while continue
else-if return
switch

Conditional Statements:
 if statement – The if statement helps us to make a decision.
Syntax:
if (condition)
{

11

Page 11 of 74
faizi_+918137088810
C Programming

Statements;
}
In the ( ) of if, the expression is checked for true or false. If the value within the ( ) comes to
be true, then the statements within the if block { } is executed otherwise not.

true false
if (condition)
{

Statements
}
Statements
}

 When if statement execute a single statement, we may not use { }


Example:
#include<stdio.h>
void main ()
{
int a,b;
printf(“enter two numbers:”);;
scanf(“%d %d”, &a,&b);
if (a>b)
{
printf(“a is greater than b”)
}
if(b>a)
{
printf(“b is greater than a”);
}
if(a = =b)
{
printf(“both a & b are equal”);
}
getch();
}
 if – else statement – The if- else statement is an extension of the simple if statement
Syntax:
if (condition)
{

12

Page 12 of 74
faizi_+918137088810
C Programming

Statements;
}
else
{
Statements;
}

Example: To check the given number is even or odd

#include<stdio.h>
#include<conio.h>
void main ()
{
int num;
clrscr ();
printf (“enter a number:”);
scanf(“%d”,&num);
if (num % 2==0)
printf (“%d is even”,num);
else
printf(“%d is odd”,num);
getch ();
}
 Nested if – else
Syntax:

if (condition 1)
true {
if (condition 2)
true {
statement 1
} false
else false
{
statements 2
}
}
else
{
statement 3

13

Page 13 of 74
faizi_+918137088810
C Programming

Example: To find greatest among three numbers using nested if-else

#include<stdio.h>
#include<conio.h>
void main ()
{
int num1, num2, num3;
clrscr ();
printf(“enter three numbers:”);
scanf(“%d %d %d”,&num1,&num2,&num3);
if (num1 > num2)
{
if (num1 > num3)
{
printf(“greatest is %d”,num1);
}
else
{
printf(“greatest is %d”,num3);
}
}
else
{
if (num2 > num3)
{
printf(“greatest is %d”,num2);
}
else
{
printf (“greatest is %d”,num3) ;
}
}
}
 else – if
When we want to select one option out of one, we use “if”. When we want to select one
option out of two, we use “if- else” and if we want to select one option out of many we
use “else - if”

14

Page 14 of 74
faizi_+918137088810
C Programming

if (condition)
true { false
statement1
}
else if (condition)
true {
statement2
} false
else if (condition)
true {
statement3
}
else false
{
statement4
}

Example: Grading students based on percentage

#include<stdio.h>
#include<conio.h>
void main ()
{
float mark;
clrscr();
printf(“enter mark:”);
scanf (“%f”,&mark);
if(mark>=80 && marks<=100)
printf(“grade: a”);
else if(mark>=60 && marks<=80)
printf(“grade: b”);
else if(mark>=40 && marks<=60)
printf(“grade: c”);
else if(mark>=0 && marks<=40)
printf(“grade: d”);
else

15

Page 15 of 74
faizi_+918137088810
C Programming

printf(“marks entered are wrong”);


getch();
}
 switch statement - switch statement is used to select a choice out of many available
choices.
Syntax:

switch (expression)
{
case value1:
statements
break;
case value2:
statements
break;
case value3:
statements
break;
default:
statements

}
 The expression is an integer or character
 Value1 and value2 are constants or constant expressions and are known as case labels
 Case labels ends with a colon (:)
 When the switch is executed, the value of the expression is compared against the values
value1, value2……..if a case is found whose value matches with the value of the
expression then the block that follows the case are executed.
 The break statement at the end of each block causes an exit from the switch statement
 The default is an optional case. When present, it will be executed, if the value of the
expression does not match with any of the case values.

Example: To display day name against day number entered by user

#include<stdio.h>
#include<conio.h>
void main ()
{
int n;
clrscr();

16

Page 16 of 74
faizi_+918137088810
C Programming

printf(“enter day no: between (1-7):”);


scanf(“%d”,&n);
switch(n)
{
case 1: printf (“Sunday”);
break;
case 2: printf(“Monday”);
break;
case 3: printf(“Tuesday”);
break;
case 4: printf(“Wednesday”);
break;
case 5: printf (“Thursday”);
break;
case 6: printf(“Friday”);
break;
case 7: printf (“Saturday”);
break;
default: printf (“wrong input”);
}
getch ();
}

Looping Statements:

The loop statement instructs the system to execute the statement n number of times without
having to write the code again and again.
 Loop is divided into two segments:
 Control statement – It is given to govern the no: of times we need to repeat a set
of statements
 Body – It contain the statements that we need to repeat.
 The loop statements are categories into two parts:
 Entry controlled
 Exit controlled

17

Page 17 of 74
faizi_+918137088810
C Programming

Loop statements

Entry controlled Exit controlled


 for do-while
 while

 Entry controlled loops – By entry controlled loop we mean that the control statement of the
loop is preceded by the body of the loop
 Exit controlled loops - By exit controlled loop we mean that the control statement of the
loop comes after the body of the loop
while loop

while (condition)
{
Block of statements;
}

 The while loop is an entry –controlled loop


 The test condition is evaluated and if the condition is true, then the body of the loop is
executed.

18

Page 18 of 74
faizi_+918137088810
C Programming

 After the execution of the body, test condition is once again evaluated and if it is true, the
body is executed once again. This process of repeated execution of the body continues until
the test condition finally becomes false and the control is transferred out of the loop.

a=10;
while (a! = 0) Output: 10987654321
{
printf(“%d”,a);
a- -;
}
do- while

 “while” loop first checks the condition and then executes the statements within it. If the
condition evaluates to false on the very first time, loop will terminate.
 A “do-while” loop first executes the statements at least once and then checks the condition.

do
{
Statements;
} while (condition);

 On reaching the do- statement, the program proceeds to evaluate the body of the loop first
 At the end of the loop, the test condition in the while statement is evaluated.
 If the condition is true, the program continues to evaluate the body of the loop once again.
This process continues as long as the condition is true. When the condition becomes false,
the loop will be terminated.
 Since the test condition is evaluated at the end of the loop, the do-while statement provides
an exit controlled loop and therefore the body of the loop is always executed at least once.

19

Page 19 of 74
faizi_+918137088810
C Programming

do-while while

int a = 5; int a= 5;
do while(a>5 && a<10)
{ {
printf(“%d”,a); printf(“%d”,a);
a= a+1; a= a+1;
}while(a>5 && a<10); }

Output: Output:
56789 No result

for loop
 For loop often referred to as iterative loop
 It is an entry controlled loop
Syntax:

for (initialization; condition; increment/decrement)


{
Statements;
}
 The context inside the bracket of for loop statement is divided into three parts separated by
semi colon

20

Page 20 of 74
faizi_+918137088810
C Programming

 Initialization of the control variables is done first, using assignment statements such as i =1
and count = 0. The variables i and count are known as loop control variables
 The value of the control variable is tested using the test condition. The test condition is a
relational expression, such as i< 0 that determines when the loop will exit. If the condition is
true, the body of the loop is executed, otherwise the loop is terminated.
 When the body of the loop is executed, the control is transferred back to the for statement
after evaluating the last statement in the loop. Now, the control variable is incremented using
an assignment statement such as i=i+1 and the new value of the control variable is again
tested to see whether it satisfies the loop condition. If the condition is satisfied, the body of
the loop is again executed. This process continues till the value of the control variable fails
to satisfy the test condition.
Nested for loop
 Nested loop means a loop inside another loop
Syntax:

for (initialization; condition; increment/decrement)


{
for (initialization; condition; increment/decrement)
{

Statements;
}
}
Jumping Statements

These statements are used to transfer the execution control of a program from one statement to
another.
21

Page 21 of 74
faizi_+918137088810
C Programming

 break statement
The break keyword is used to exit from a loop based on some condition given by the
programmer.
for(condition)
{
statement 1;
if(condition)
{
statement 2;
break;
}
statement 3;
}
statement 4;

 continue statement
The continue statement skips the remaining statements in the body of the loop, and continue
with next iteration of the loop from first line.

for(condition)
{
statement 1;
statement 2;
if(condition)
{
continue;
statement 3;
statement 4;
}
break continue

int a=0; int a=0;


while(a<10) while(a<10)
{ {
a =a+1; a =a+1;
if(a%7= = 0) if(a%7= = 0)
break; continue;
printf(“%d”,a); printf(“%d”,a);
} }

22

Page 22 of 74
faizi_+918137088810
C Programming

Output Output

1 2 3 4 5 6 1 2 3 4 5 6 8 9 10

return statement
Return statement is used to exit from a function and return to the next statement of the calling
function that called the function. Unlike break statement that only exits the loop, return forces
the control to leave the function.

PROGRAMS:
Sum of two numbers:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,sum;
printf(“Enter two numbers:”);
scanf(“%d %d”,&a,&b);
sum = a+b;
printf(“Sum is %d”,s);
getch();
}

Area and circumference of circle


#include<stdio.h>
#include<conio.h>
void main()
{
int rad;
float PI=3.14,area,ci;
clrscr();
printf(" Enter radius of circle: ");
scanf("%d",&rad);

area = PI * rad * rad;


printf(" Area of circle : %f ",area);

ci = 2 * PI * rad;
printf("Circumference : %f ",ci);

getch();
}
23

Page 23 of 74
faizi_+918137088810
C Programming

Area of Square
#include<stdio.h>
#include<conio.h>
void main()
{
int side,area;
clrscr();
printf("Enter the Length of Side : ");
scanf("%d",&side);
area = side * side ;
printf(" Area of Square : %d",area);
getch();
}
Area of Right Angled Triangle
#include<stdio.h>
#include<conio.h>
void main()
{
int base,height;
float area;
clrscr();
printf(“Enter the base of Right Angle Triangle : ");
scanf("%d",&base);
printf("Enter the height of Right Angle Triangle : ");
scanf("%d",&height);
area = 0.5 * radius * radius;
printf("Area of Right Angle Triangle : %f",area);
getch();
}
Area of Rectangle
24

Page 24 of 74
faizi_+918137088810
C Programming

#include<stdio.h>
#include<conio.h>
void main()
{
int length,breadth,side;
clrscr();
printf(" Enter the Length of Rectangle : ");
scanf("%d",&length);
printf("Enter the Breadth of Rectangle : ");
scanf("%d",&breadth);
area = length * breadth;
printf("Area of Rectangle : %d",area);
getch();
}
Swapping of two numbers:

#include<stdio.h>
#include<conio.h>
void main ()
{
int a,b,c;
clrscr();
printf(“Enter two numbers:”);
scanf(“%d %d”,&a,&b);
c=a;
a=b;
b=a;
printf(“After swapping a=%d b=%d”,a,b);
getch();
}

Swapping of two numbers without using temporary variable:

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

25

Page 25 of 74
faizi_+918137088810
C Programming

{
int a,b;
clrscr();
printf(“Enter two numbers:”);
scanf(“%d %d”,&a,&b);
a=a + b;
b=a - b;
a= a - b;
printf(“After swapping a=%d b=%d”,a,b);
getch();
}

To find greatest in 3 numbers


#include<stdio.h>
#include<conio.h>

void main()
{
int a,b,c;
clrscr();
printf("\n Enter value of a, b & c: ");
scanf("%d %d %d",&a,&b,&c);
if((a>b)&&(a>c))
printf("\n a is greatest");
else if((b>c)&&(b>a))
printf("\n b is greatest");
else if((c>a)&&(c>b))
printf("\n c is greatest");
getch();
}
Calculate sum of ‘n’ numbers:

#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,num,sum =0;
clrscr();
printf(“enter the limit:”);
scanf(“%d”,&n);
printf(“enter %d numbers”,n);
for(i=1;i<=n;i++)
{
scanf(“%d”,&num);
26

Page 26 of 74
faizi_+918137088810
C Programming

sum = sum+num;
}
printf(“the sum is %d”,sum);
getch();
}

Fibonacci Series:
#include<stdio.h>
#include<conio.h>
void main ()
{
int a=0,b=1,s=0,n,i=3;
clrscr();
printf(“enter the limit:”);
scanf(“%d”,&n);
printf(“%d %d”,a,b);
while(i<=n)
{
s= a+b;
a=b;
b=s;
i++;
printf(“%d”,s);
}
getch();
}

Find Factorial of a Number


#include<stdio.h>
#include<conio.h>
void main ()
{
int i,n,factorial =1;
printf("\n Enter the number : ");
scanf("%d",&n);
for (i=1;i<=n;i++)
factorial = factorial * i;
printf ("\n Factorial of %d is %d",n,factorial );
getch ();
}
Reverse a Number

#include<stdio.h>
#include<conio.h>
27

Page 27 of 74
faizi_+918137088810
C Programming

void main()
{
int num,rem,rev=0;
clrscr();
printf("\n Enter any no to be reversed : ");
scanf("%d",&num);
while (num>=1)
{
rem = num % 10;
rev = rev * 10 + rem;
num = num / 10;
}
printf("\n Reversed Number : %d",rev);
getch();
}
Sum of digits:
#include<stdio.h>
#include<conio.h>

void main()
{
int n,r,s=0;
clrscr();
printf("\n Enter the number : ");
scanf("%d",&n);
while (n!=0)
{
r = n % 10;
n = n / 10;
s= r + s;
}
printf("\n sum=%d",s);
getch();
}
To check the given number is palindrome or not
#include<stdio.h>
#include<conio.h>

void main()
{
int num,b=0,c=0,d=0;
clrscr();
28

Page 28 of 74
faizi_+918137088810
C Programming

printf("\n Enter the number : ");


scanf("%d",&num);
b=n;
while (num>=1)
{
c = num % 10;
d = rev * 10 + c;
num = num / 10;
}
if(d= =b)
printf(“the number is %d is a palindrome”);
else
printf(“the number is %d is not palindrome”);
getch();
}
Check the given year is leap year or not

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("\n Enter the year : ");
scanf("%d",&n);
if((n%4 = =0) && (n%100!=0) !! (n%400 = =0))
{
printf(“the given year is leap year”);
}
else
{
printf(“the given year is leap year”);
}
getch();
}
Check the given number is Armstrong or not
#include<stdio.h>
#include<conio.h>
void main()
{
int num,d,dup,sum =0;
clrscr();
printf("\n Enter the number : ");
scanf("%d",&num);
dup = n;
29

Page 29 of 74
faizi_+918137088810
C Programming

while (num>=1)
{
d = num % 10;
sum = sum + d*d*d;
num = num / 10;
}
if(sum= =dup)
printf(“It is an armstrong number”);
else
printf(“It is not an armstrong number”);
getch();
}
To check whether a number is prime or not

#include<stdio.h>
#include<conio.h>
void main()
{
int n,b=2,flag=0;
printf("Enter the no:");
scanf("%d",&n);
while(flag==0 && b<=n/2)
{
if(n%b==0)
{
flag=1;
break;
}
b++;
}
if(flag==0)
printf("number is prime");
else
printf("number is not prime");
getch();
}

30

Page 30 of 74
faizi_+918137088810

MODILE II

Array:
An array is a collection of similar type of elements with same name and different index number.

Array Declaration and Definition


data type arrayname [size];
int arr [10];
 size of the array is specified within the square brackets
 An array of size ‘n’ the first elements will always have the index 0 and the last element will
have the index n-1.
Example: Find the largest number in the array
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,big;
printf(“enter the limit:”);
scanf(“%d”,&n);
printf(“enter %d elements”,n);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
big = a[0];
for(i=0;i<n;i++)
{
if(big<a[i])
big = a[i];
}
printf(“the largest number in the array is %d”, big);
getch();
}
 Binary Searching:
#include<stdio.h>
#include<conio.h>
void main ()
{
int a[10],n,i,num,st,end,mid;
clrscr();

Page 31 of 74
faizi_+918137088810

printf(“”enter the limit:);


scanf(“%d”,&n);
printf(“enter the numbers in ascending order”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“enter the element to be searched:”);
scanf(“%d”, &num);
st =0; end = n;
while (st<=end)
{
mid = (st+end)/2;
if(num = = a[mid])
{
printf(“%d present at position %d”,b,mid+1);
break;
}
else
{
if(b< a[mid])
end = mid -1;
else
st = mid+1;
}
if(st >end)
printf(“number not present”);
getch();
}
Two dimensional array
Two dimensional array will require two pairs of square brackets.
Two dimensional arrays are declared as follows:
datatype arrayname [row size] [column size];
int arr [3] [2];
This array looks like:
0 1
arr [0] [0] arr [0] [1]
0
arr [1] [0] arr [1] [1]
arr [2] [0] arr [2] [1]

Page 32 of 74
faizi_+918137088810

Programs for Matrix Processing

Addition of two matrices:

#include<stdio.h>
#include<conio.h>
void main ()
{
int a[10][10],b[10][10],c[10][10,]r,c,i,j;
printf(“enter row size and column size:”);
scanf(“%d %d”,&r,&c);
printf(“enter the first matrix:”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“enter the second matrix:”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf(“%d”, &b[i][j]);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
c[i][j] = a[i][j]+b[i][j];
}
}
printf(“The resultant matrix is: ”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf(“%d”, c[i][j]);

Page 33 of 74
faizi_+918137088810

}
printf(“\n”);
}
getch ();
}
Multiplication of two matrices:

#include <stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,r1,c1,r2,c2,k;
clrscr();
printf("Enter row & column size of 1st matrix: ");
scanf("%d %d",&r1,&c1);
printf("Enter row & column size of 2nd matrix: ");
scanf("%d %d",&r2,&c2);
if(c1!= r2)
printf("multiplication not possible");
else
{
printf("Enter elements of 1st matrix");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter elements of 2nd matrix");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d", &b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)

Page 34 of 74
faizi_+918137088810

{
c[i][j]=0;
for(k=0;k<c1;k++)
{ c[i][j]= c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("Product of the matrices");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
printf(" %d", c[i][j]);
}
printf("\n");
}
getch();
}
Transpose of a Matrix:

#include<stdio.h>
#include<conio.h>
void main ()
{
int a[10][10],r,c,i,j;
printf(“enter row size and column size:”);
scanf(“%d %d”,&r,&c);
printf(“enter the elements:”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“The matrix is ”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf(“%d \t”, a[i][j]);

Page 35 of 74
faizi_+918137088810

}
printf(“\n”);
}
printf(“Transpose of the matrix is ”);
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
printf(“%d \t”, a[j][i]);
}
printf(“\n”);
}
getch ();
}
Strings:
 Strings are collection of characters terminated by the character ‘\0’
 Strings are also defined as the array of characters
 C does not support strings as a data type. It allows us to represent strings as character
arrays

Declaring string variables:


char string_name [size];
 The size determines the number of characters in the string name.
Example: char city [10];
 When the compiler assigns a character string to a character array, it automatically supplies
a null character (\0) at the end of the string.
 The size should be equal to the maximum number of characters in the string plus one.

String Handling Functions:


The most commonly used string handling functions are
 strlen()
 strcat()
 strcmp()
 strcpy()

strlen () function
This function is used to find the length of the string
Syntax:

Page 36 of 74
faizi_+918137088810

n = strlen (string); where n is an integer variable, which receives the value of the length of
the string
Example: To find the length of the string using strlen () function

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main ()
{
char str [10];
int n;
printf (“Enter the string :”);
gets (str);
n = strlen(str);
printf(“The length of the string is %d”,n);
getch();
}
strcat () function
The strcat () is used to append one string at the end of another
Syntax:
strcat (string1, string2);
string1 and string 2 are character arrays. When the function strcat is executed, string2 is
appended to string1. It does so by removing the null character at the end of string1 and placing
string2 from there. The string at string2 remains unchanged.
Str1
0 1 2 3 4 5 6 7 8 9
V E R Y \0 \0 \0 \0 \0

Str2
0 1 2 3 4 5
G O O D \0 \0

strcat (str1, str2);

Str1
0 1 2 3 4 5 6 7 8 9
V E R Y G O O D \0

Page 37 of 74
faizi_+918137088810

Str2
0 1 2 3 4 5
G O O D \0 \0

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main ()
{
char str1[10],str2[10];
printf(“enter the first string:”);
gets(str1);
printf(“enter the second string:”);
gets(str2);
strcat(str1,str2);
printf(“The combined string is %s”,str1);
getch ();
}
strcmp() function
The strcmp () is used to compare one string with another. If both are same, the function returns
0, else it returns the numeric difference between the first nonmatching characters in the
strings.
Syntax:
strcmp(string1,string2);
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main ()
{
char str1[10],str2[10];
printf(“enter the first string:”);
gets(str1);
printf(“enter the second string:”);
gets(str2);
if(strcmp(str1,str2)= =0)
printf(“Strings are equal”);
else
printf(“Strings are not equal”);
getch();

Page 38 of 74
faizi_+918137088810

}
strcpy () function
The strcpy () is used to copy one string into another.
Syntax:
strcpy(string1,string2);

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main ()
{
char str1[10],str2[10];
int i =0;
printf(“enter the first string:”);
gets(str1);
printf (“enter the second string:”);
gets(str2);
strcpy (str1,str2);
printf (“The copied string is %s”, str1);
getch ();
}
Array of strings:
We can have multiple strings in a single array. This is two dimensional array of characters.
First dimension specifies the maximum number of strings that the array can have and second
specifies the maximum characters that a sting can have.
An array of strings can be declared as:
char a[10][20];
This array can have 10 strings with each string containing maximum 20 characters.

Initializing two-dimensional string array


char a[3][10] = {“TVM”,”EKM”,”KTM”};
a[0] = “TVM”;
a[1] = “EKM”;
a[2] = “KTM”;
Sort list of names:

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

Page 39 of 74
faizi_+918137088810

{
int i,j,n;
char a[20][20],b[20];
printf(“Enter total number of names:”);
scanf(“%d”,&n);
printf(“Enter %d names”,n);
for(i =0;i<n;i++)
{
scanf(“%s”,a[i]);
}
printf(“original array is:”);
for(i =0;i<n;i++)
{
for(j =0;j<n-i-1;j++)
{
if(strcmp(a[j],a[j+1])>0)
{
strcpy(b,a[i]);
strcpy (a[j],a[j+1]);
strcpy(a[j+1],b);
}
}
}
printf(“sorted array \n ”);
for(i=0;i<n;i++)
{
printf(“%s”,a[i]);
}
getch();
}
Structure:
Structure is a collection of different types of elements. A single structure might contain integer,
float, double and character data.

Defining a structure:
struct tag
{
data type member1;
data type member2;
.

Page 40 of 74
faizi_+918137088810

.
data type member n;
};
struct is a keyword for structure, tag is the name of structure and member 1,member 2 is the
members of structure.
Defining a Structure Variable:
struct tag
{
data type member1;
data type member2;
.
.
data type member n;
} var;
var is the structure variable
Example:
struct record
{
char name [20];
int age;
char addr [20];
} rec;

name, age, addr are the members of this structure, rec is the structure variable.
Accessing Structure Members:
 The members of a structure are processed individually, as separate entities. Therefore we
must be able to access the individual structure members.
 A structure member can be accessed by writing
variable. member
where variable refers to the name of a structure type variable and member refers to the name
of a member within the structure. The dot (.) operator separates the variable name from
member name.
Example:
struct record
{
char name [20];
int age;
char addr [20];
} person;

Page 41 of 74
faizi_+918137088810

In this example, person is a structure variable of type record. if we want to access the person’s
name, we would write
person.name
Similarly person’s age and address
person. age person.addr
The members themselves are not variables. They should be linked to the structure variables in
order to make them meaningful members.
For example the word name has no meaning, where as the phrase ‘name of person’ has a
meaning. The link between a member and a variable is established using the dot (.) operator.
Example:
struct person
{
char name [20];
int age;
char addr [20];
} rec;
void main()
{
printf(“Enter values:”);
scanf(“%s %d %s”,rec.name,&rec.age,rec.addr);
printf(“%s %d %s”,rec.name,rec.age,rec.addr);
getch();
}
Array of Structures:
We can declare the array of structures where every element of array is structure type.
struct record
{
char name [20];
int age;
char addr [20];
} person[10];

Here person is an array of 10 elements and each element of person has 3 member elements
which are name, age and addr.

Example: To create array of structure

#include<stdio.h>
#include<conio.h>
struct student

Page 42 of 74
faizi_+918137088810

{
int rollno;
char name [10];
int age;
}std[10];
void main ()
{
int n,i;
printf(“enter the limit:”);
scanf(“%d”,&n);
printf(“enter details of students \n”);
for(i=0;i<n;i++)
{
printf(“Enter rollno”);
scanf(“%s”,&std[i].rollno);
printf(“Enter name:”);
scanf(“%s”,std[i].name);
printf(“Enter age:”);
scanf(“%d”,&std[i].age);
}
printf(“Details of students \n”);
for(i=0;i<n;i++)
{
printf(“\n roll no: %d name :%s age:%d”,std[i].rollno,std[i].name,std[i].age);
}
getch();
}

1) Write a program to enter the rollno, name and marks of students and to print the details of
students who scored more than 75.

#include<stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name [10];
int mark;
}std[10];
void main ()

Page 43 of 74
faizi_+918137088810

{
int n,i;
printf(“Enter the limit:”);
scanf(“%d”,&n);
printf(“Enter details of students \n”);
for(i=0;i<n;i++)
{
printf(“Enter rollno”);
scanf(“%s”,&std[i].rollno);
printf(“Enter name:”);
scanf(“%s”,std[i].name);
printf(“Enter mark:”);
scanf(“%d”,&std[i].mark);
}
printf(“The students who have score more than 75 are \n”);
for(i=0;i<n;i++)
{
if(std[i].mark > = 75)
{
printf(“\n roll no: %d name :%s mark:%d”,std[i].rollno,std[i].name,std[i].mark);
}
}
getch();
}
2) Define the structure student with the following details rollno, name and marks. Read the
details of ‘n’ students and display this in the order of their marks
#include<stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name [10];
int mark;
}std[10];
void main ()
{
int n,i,j,trn,t;
char tn[10];
printf(“Enter the number of students:”);
scanf(“%d”,&n);

Page 44 of 74
faizi_+918137088810

printf(“Enter details of students \n”);


for(i=0;i<n;i++)
{
printf(“Enter rollno”);
scanf(“%s”,&std[i].rollno);
printf(“Enter name:”);
scanf(“%s”,std[i].name);
printf(“Enter mark:”);
scanf(“%d”,&std[i].mark);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(std[i].mark > std[j].mark)
{
t = std[i].mark;
std[i].mark = std[i].mark;
std[j].mark = std[i].mark;
trn = std[i].rollno;
std[i].rollno = std[j].rollno;
std[j].rollno = trn;
strcpy(tn, std[i].name);
strcpy(std[i].name, std[j].name);
strcpy(std[j].name, tn);
}
}
}
for(i=0;i<n;i++)
{
printf(“\n roll no: %d name :%s mark:%d”,std[i].rollno,std[i].name,std[i].mark);
}
getch();
}
3) Create a structure database with rollno, name, and age. Solve the array in ascending order
of their names.

#include<stdio.h>
#include<conio.h>
struct student

Page 45 of 74
faizi_+918137088810

{
int rollno;
char name [10];
int age;
}s[10];
void main ()
{
int n,i,j,t,temp;
char tn[10];
printf(“Enter the number of students:”);
scanf(“%d”,&n);
printf(“Enter details of students \n”);
for(i=0;i<n;i++)
{
printf(“Enter rollno”);
scanf(“%s”,&s[i].rollno);
printf(“Enter name:”);
scanf(“%s”,s[i].name);
printf(“Enter age:”);
scanf(“%d”,&s[i].mark);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(s[i].name ,s[j].name) >0)
{
strcpy(tn, s[i].name);
strcpy(s[i].name, s[j].name);
strcpy(s[j].name, tn);
t = s[i].rollno;
s[i].rollno = s[j].rollno;
s[j].rollno = t;
temp = s[i].age;
s[i].age = s[i].age;
s[j].age = temp;
}}}
for(i=0;i<n;i++)
{
printf(“\n roll no: %d name :%s mark:%d”,std[i].rollno,std[i].name,std[i].age);

Page 46 of 74
faizi_+918137088810

}
getch();
}

Union:
Union is a collection of different types of elements. Union allocates memory for variable which
variable require more memory. Only one member of union can be accessed at anytime. Thus
the union is used for saving memory.
Syntax:
union union_name
{
datatype element 1;
datatype element 2;
----------
----------
datatype element n;
}union_var;

Example:
rollno name
struct student
{
int rollno;
char name [5]; 1000 1001 1002 1003 1004 1005 1006
};
name
union student
{
int rollno;
char name [5]; rollno
1002 1003 1004 1005 1006
};
In union student both name and rollno store the same memory location.
Access Members:
We can access the union members same as structure use the dot (.) operator.
variable. member

Page 47 of 74
faizi_+918137088810

Difference between structure and union:

structure union
1. We can access all the members of 1. Only one member of union can be
structure at anytime. accessed at anytime.

2. Memory is allocated for all 2. Allocates memory for variable which


variables. variable require more memory.

3. All members of structure can be 3. Only the first member of a union can
initialized be initialized.

4. 'struct' keyword is used to declare 4. 'union' keyword is used to declare


structure. union.

struct structure_name union union_name


{ {
datatype element 1; datatype element 1;
datatype element 2; datatype element 2;
---------- ----------
---------- ----------
datatype element n; datatype element n;
}structure_var; }union_var;

Page 48 of 74
faizi_+918137088810

MODULE III
Functions:
A function is a self-contained block of program that performs a particular task.
 Every C program consists of one or more functions
 If a program contains multiple functions, their definitions may appear in any order, though
they must be independent of each other.
 We can avoid rewriting of a group of codes by defining them within a function block and
use them by simply calling the function.
 A function will process information that is passed to it from the calling portion of the
program and return a single value.

Different parts of a function:


Mainly function contains three parts:
 Function definition
 Function call
 Function declaration (function prototype)
Function Definition:
Function definition is the coding within the function block.

Different parts of a function definition:


 Function header
 Function body

 The function header of a function definition contains


 Type specification of the value returned by the function
 Function name
 Set of arguments , separated by commas and enclosed in parentheses
 Each argument is preceded by its associated type declaration.
 An empty pair of parenthesis must follow the function name if the function definition does not
include any arguments.
Syntax:

data type function_name (data type arg1, data type arg2 …)


{
Body of the function;
}
Function call:
Function call is calling function by specifying its name. A function can be called by specifying
its name, followed by a list of arguments enclosed in parentheses and separated by commas.
Syntax:
Function_name (arguments);

 If the function does not require any arguments, an empty pair of parentheses must follow the
name of the function.
Page 49 of 74
faizi_+918137088810

 If the function does not return anything, the function access appears by itself.
Example:
display (a, b);
 If the function returns a value, the function access is often written as an assignment
statement.
Example:
f = factorial (n);

Function declaration:
The calling program should declare any function that is to be used later in the program. This is
known as the function declaration or function prototype. Function declarations are usually
written at the beginning of a program.
Syntax:
data type function_name (data type arg1, data type arg2 …);

Arguments:
Information is passed to the function via special identifiers are called arguments or
parameters.
Arguments are three types
 Actual arguments
 Formal arguments
 Dummy arguments

Actual arguments:
The arguments appearing in the function call are referred to as actual arguments
Formal arguments:
The arguments appearing in the function definition are referred to as formal arguments
Dummy arguments:
The names of the arguments within the function prototype need not be declared elsewhere in the
program, since these are dummy argument names that are recognized only within the prototype.

Example: Sum of two numbers using function


#include<stdio.h>
#include<conio.h>
void sum (int p, int q); /* dummy arguments */
void main()
{
int a,b;
clrscr();
printf(“Enter two numbers:”);
scanf(“%d %d”,&a,&b);
sum(a,b); /* actual arguments */
getch();
}

Page 50 of 74
faizi_+918137088810

void sum(int x, int y) /* formal arguments */


{
int s;
s = x+y;
printf(“Sum=%d”,s);
}

Passing arrays to Functions:


An entire array can be passed to a function as an argument.
 To pass an array to a function, the array name must appear itself, without brackets, or scripts as
an actual argument within the function call.
Example:
avg = average (n, arr);
When declaring a one – dimensional array as a formal argument, the array name is written with a
pair of empty square brackets.
 The size of the array is not specified within the formal argument declaration.
Example:
float average (int a, float x [])
 When writing function prototypes that include array arguments, an empty pair of square
brackets must follow the name of each array argument, thus indicating that the argument is an
array.
Example:
float average (int a, float x []);
 If argument names are not included in a function declaration, then an empty pair of square
brackets must follow the array argument data.
Example:
float average (int , float []);

Example: One Dimensional Array passing to function

#include<stdio.h>
#include<conio.h>
void pass(int a[], int n);
void main()
{
int a[10],i,n;
printf(“Enter the limit:”);
scanf(“%d”,&n);
printf(“Enter %d elements”,n);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
pass(a,n);
printf(“Now the array elements are”);
Page 51 of 74
faizi_+918137088810

for(i=0;i<n;i++)
{
printf(“%d”,a[i]);
}
getch();
}
void pass(int a[], int n)
{
int i;
for(i=0;i<n;i++)
a[i] = a[i] *10;
}

Example: Two Dimensional Array passing to function. sort the names in alphabetical order using
function

#include<stdio.h>
#include<conio.h>
#include<string.h>
void sort (char [][25],int);
void main()
{
int i,n;
char a[100][25];
printf(“Enter total number of names:”);
scanf(“%d”,&n);
printf(“Enter %d names”,n);
for(i =0;i<n;i++)
{
scanf(“%s”,a[i]);
}
sort(a,n);
printf(“sorted array \n ”);
for(i=0;i<n;i++)
{
printf(“%s \n”,a[i]);

}
getch();
}
void sort (char [][25],int)
{
int i,j;
char x[25];

Page 52 of 74
faizi_+918137088810

for(i =0;i<n;i++)
{
for(j =0;j<n-i-1;j++)
{
if(strcmp(a[j],a[j+1])>0)
{ strcpy(x,a[i]);
strcpy
(a[j],a[j+1]);
strcpy(a[j+1],x);
}
}
}
}

Recursion:
Recursion is a process by which a function calls itself repeatedly, until some specified
condition has been satisfied.
For example consider factorial of a number, n
n! = n*(n-1)*(n-2)*...*2*1, and that 0! = 1.

factorial (3)
3 * factorial (2)
3 * 2 * factorial (1)
3 * 2 * 1 * factorial (0)
3*2*1*1
=> 6

Example: Factorial of a number using recursion

#include<stdio.h>
#include<conio.h>
int factorial(int);
void main()
{
int n,f;
clrscr();
printf("Enter no");
scanf("%d",&n);

Page 53 of 74
faizi_+918137088810

f=factorial(n);
printf("Factorial = %d",f);
getch();
}
int factorial(int k)
{
int fact=1;
if(k>1)
fact=k*factorial(k-1);
return fact;
}
Macro:
Macro is a Preprocessor directive. It is a Single line abbreviation of group of statements.
#define statements are used to define macro.
Syntax:
Definition
#define macroname text
Call
macroname (arguments);

Eg: #define PI 3.14


area = PI * radius * radius;

 Replaced by “area = 3.14 * radius * radius” by preprocessor before compilation

Difference between macro and function:


Macro Function
1. Macros are expanded by macro 1. Functions are executed by the
processor before the execution processor at the time of execution

2. When the macro call is identified by 2. When the function call is


the processor then paste the identified by the processor, the
definition in the place of macro call. control transfer to the function
definition at the time of execution.

3. It is called static binding 3. It is called dynamic binding

4. A macro cannot call itself 4. A function can call itself

5. When passing arguments to a macro 5. Function checks both number of


the number of arguments will be arguments and their data types
checked, but their data types will not

Page 54 of 74
faizi_+918137088810

Example:

#include<stdio.h>
#include<conio.h>
#define area length * breadth
void main()
{
int length, breadth;
printf (“Enter length and breadth:”);
scanf (“%d %d”,&length,&breadth);
printf (“Area = %d”, area);
getch ();
}
Quick Sort:
#include<stdio.h>
#include<conio.h>
int a [20];
void main ()
{
int i, n;
printf ("Enter the limit");
scanf ("%d", &n);
printf ("Enter the elements");
for (i=0; i<n; i++)
scanf ("%d",&a[i]);
qs (0, n-1);
printf ("Sorted array is: \n");
for (i=0; i<n; i++)
printf ("%d", a[i]);
getch ();
}
void qs (int n, int u)
{
int i;
if (u>=n)
{
i =split (n, u);
qs (n, i-1);
qs (i+1, u);
}

Page 55 of 74
faizi_+918137088810

}
int split (int n, int u)
{
int i, p, q, t;
p=n+1;
q=u;
i=a[l];
while (q>=p)
{
while (a[p] <i)
p++;
while (a[q]>i)
q--;
if (q>p)
{
t=a[p];
a[p] =a[q];
a[q] =t;
}
t=a[l];
a[l]=a[q];
a[q] =t;
}
return q;
}

Page 56 of 74
faizi_+918137088810

Module IV
Pointer:
Pointer is a variable that contains the address of another variable.

Declaration of pointer:

Data_type pointer-name;
Example:
int *p; here p is an integer type of pointer. Value at address contained in p is an integer.

a p
int a = 5;
5 1000
int *p;
p = &a;
1000 2000
a=5 &a = 1000
p = 1000 &p = 2000
*(&a) = 5 *p = 5

Parameter Passing Mechanism:


The arguments to the functions are passed in two ways.
 Call by value
 Call by reference

Call by value:
In call by value the values of the variables are passed. In this, values of variables are not
affected by changing the value of the formal parameter.
Example:
#include<stdio.h>
#include<conio.h>
void value (int, int);
void main()
{
int a= 5,b = 8;
printf(“Before calling function a & b are %d %d”,a,b);
value (a,b);
printf(“After calling function a & b are %d %d”,a,b);
getch();
}

Page 57 of 74
faizi_+918137088810

void value (int p, int q)


{
p++;
q++;
printf (“In function p & q are %d %d”,p,q);
}
Output:
Before calling function a & b are 5 8
After calling function a & b are 5 8
In function p & q 6 9

Before calling function:


a b
5 8

1000 2000
In function:
p q
5 8

4000 8000
After incrementing p and q:
P q
6 9

4000 8000
After calling function:
a b
5 8

1000 2000

Call by reference:
In call by reference, the addresses of the variables are passed. In this, values of variables are
affected by changing the value of the formal parameter.
Example:
#include<stdio.h>
#include<conio.h>
void ref (int *, int *);
void main()

Page 58 of 74
faizi_+918137088810

{
int a= 5,b = 8;
printf(“Before calling function a & b are %d %d”,a,b);
ref(&a,&b);
printf(“After calling function a & b are %d %d”,a,b);
getch();
}
void ref (int *p, int *q)
{
(*p)++;
(*q)++;
printf (“In function p & q are %d %d”,*p,*q);
}
Output:
Before calling function a & b are 5 8
After calling function a & b are 6 9
In function p & q 6 9

Before calling function:


a b
5 8

1000 2000
In function:
p q
1000 2000

4000 8000

After calling function:

P q
1000 2000

4000 8000
a b
6 9

1000 2000

Page 59 of 74
faizi_+918137088810

Example: Swapping using call by value


#include<stdio.h>
#include<conio.h>
void swap (int , int );
void main()
{
int a,b;
printf(“enter two numbers:”);
scanf(“%d %d”,&a,&b);
swap(a,b);
getch();
}
void swap (int p, int q)
{
int temp;
temp = p;
p = q;
q = temp;
printf (“a = %d b = %d”,p,q);
}
Example: Swapping using call by reference
#include<stdio.h>
#include<conio.h>
void swap (int *, int *);
void main()
{
int a,b;
printf(“enter two numbers:”);
scanf(“%d %d”,&a,&b);
swap(&a,&b);
getch();
}
void swap (int *p, int *q)
{
int temp;
temp = *p;
*p = *q;
*q = temp;
printf (“a = %d b = %d”,*p,*q);
}

Page 60 of 74
faizi_+918137088810

Array of pointers:
Every element of this array can hold address of any variable. So we can say every element of
this array is a pointer variable. It is same as array but it contains the collection of addresses.

Example:
#include<stdio.h>
#include<conio.h>
void main ()
{
int *arr [3] ;
int a =5,b = 10, c= 15,i;
arr[0] = &a;
arr[1] = &b;
arr[2] = &c;
for(i=0;i<3;i++)
{
printf(“Value = %d”,*(arr[i]));
printf(“Address = %u”,arr[i]);
}
getch ();
}
a b c
5 10 15

1000 2000 3000

arr[0] arr[1] arr[2]


1000 2000 3000

5000 5002 5004

Pointer to Pointer:
It means a pointer to be pointing to another pointer.
Let’s suppose we have a pointer ‘p2’ that points to yet another pointer ‘p1’ that point to an
integer ‘a’.
int a = 5;
int *p1 = &a;
int **p2 = &p1; (p2 is a double pointer and hence the two *s in declaration)

Page 61 of 74
faizi_+918137088810

In memory, the three variables can be visualized as:


a p1 p2
5 1000 2000

1000 2000 3000

Pointer p2 holds the address of pointer p1. Pointer p1 holds the address of integer ‘a’.

P2 is the address of ‘p1’ ie, 2000


(*p2) is the value held by p2 ie, 1000
**p2 is the value at 1000 ie, 5

Pointer to structure:
If the variable is of structure type then for accessing the starting address of the structure. We
must declare pointer for a structure variable. These pointers are called structure pointers.

struct record
{
char name [10];
int age;
int salary;
}data,*ptr;
ptr = &data;

data is a structure variable and ptr is a structure pointer that points to the starting address of
structure variable data.

data.name data.age data.salary

1000 1010 1012

ptr
1000

Page 62 of 74
faizi_+918137088810

There are two ways of accessing the member of structure through the structure pointer
 ptr -> age;
 (*ptr) .age; (parenthesis is necessary because the dot operator has higher precedence
than * operator)
#include<stdio.h>
#include<conio.h>
struct record
{
char name [10];
int age;
int salary;
}data,*ptr = &data;
void main()
{
printf(“Enter name:”);
scanf(“%s”,ptr -> name);
printf(“Enter age:”);
scanf(“%d”,&ptr ->age);
printf(“Enter salary:”);
scanf(“%d”,&ptr ->salary);
printf(“name: %s age %d salary %d”,ptr ->name,ptr ->age,ptr ->salary);
getch();
}
Find largest and smallest element in an array using pointers

#include <stdio.h>
void main()
{
int a[100],n,i,l,s;
int *p=a;
printf("Enter Limit: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter No. %d: ",i+1);
scanf("%d",&a[i]);
}
l=*p;
s=*p;

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

Page 63 of 74
faizi_+918137088810

{
if(*(p+i)>l)
{
l=*(p+i);
}
if(*(p+i)<s)
{
s=*(p+i);
}
}
printf("Largest Number : %d",l);
printf("Smallest Number: %d",s);
getch();

Self referential structure:

A structure may have a member whose is same as that of a structure itself. Such structures are
called self-referential. Self-referential Structure is used in data structure such as binary tree,
linked list, stack, Queue etc.

Syntax:

struct tag

data type member;

struct tag *ptr_variable;

};

Example: Single linked list is implemented using following data structures

struct node

int value;

struct node *next;

};

Page 64 of 74
faizi_+918137088810

Linked List:

A linked list is a linear collection of data elements, called nodes. Each node is divided into two
parts:

 The first part contains the information of the element and


 The second part contains the address of the next node in the list.

Types of Linked List

 Linear Linked List


 Doubly Linked List

 Circular Linked List

Linear Linked List:

10 2000 20 3000 30 NULL

1000 2000 3000

Doubly Linked List:

NULL 10 2000 1000 20 3000 2000 30 NULL

1000 2000 3000

Circular Linked List:

10 2000 20 3000 30 1000

1000 2000 3000

Page 65 of 74
faizi_+918137088810

Command Line Arguments:

Parentheses of main function may contain special arguments that allow parameters to be
passed to main from the operating system. Such arguments are called argc and argv.

argc – integer variable that indicate the number of parameters passed.

argv – array of strings. Each string in this array will represent a parameter that is passed to
main.

void main(int argc, char * argv[])

{…………

In order to pass one or more parameters to the program when it is executed from the operating
system, the parameters must follow the program name on the command line.

Example: Program_name parameter1, parameter2, parameter3

Example:

#include<stdio.h>

void main(int argc,char * argv[])

int i;

printf(“argc = %d”,argc);

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

printf(“argv[%d]=%s”,i,argv[i]);

10

Page 66 of 74
faizi_+918137088810

MODULE V
Files:
File is a place in the disk where a group of related data is stored. When large volumes of data
are to be handled, it is necessary that data are to be stored on disk and read whenever necessary.
Advantages of using data files:
 The data is safely kept for any future use and modification.
 When large amount of data is to be processed, data is taken from the secondary storage
and processed.
Different types of files:
There are two types of data files.
 Binary file
 Text file

Opening a file:
Opening a file consists of two steps.
 Allocating a buffer area
 Allocating a name
Allocating a buffer area:
When working with a data file, the first step is to establish a buffer area, where information is
temporarily stored while being transferred between the computer’s memory and the data file.
 The buffer area is established by writing
FILE *ptr_variable;
Where FILE is a special structure type that establishes the buffer area. Pointer variable
indicates the beginning of the buffer area. The structure type FILE is defined in stdio.h.
Example:
FILE *p;
Allocating a name:
A data file must be opened before it can be processed or created. This associates the file name
with the buffer area. It also specifies how the data file will be utilized, that is a read only file, a
write only file, or a read/write file, in which both operations are permitted.
fopen ( ) – The fopen ( ) function is used to open a file to be used. The return value of the
function is a FILE pointer that refers to the memory address of the file. A NULL value is
returned, if the file cannot be opened.
Example:
ptr = fopen (“file name”, “file type”);
where file name and file type are strings that represents the name of the data file and the
manner in which the data file will be utilized.
File type specifications:
“r” Opening an existing file for reading only.
“w” Open a new file for writing only. If a file with the specified filename
currently exists, it will be destroyed and a new file created in its place.

Page 67 of 74
faizi_+918137088810

“a” Open an existing file for appending. A new file will be created if the
file with the specified filename does not exist.
“r+” Opening an existing file for reading and writing.
“w+” Open a new file for both writing and reading
“a+” Open an existing file for reading and appending. A new file will be
created if the file with the specified filename does not exist.

Closing a data file:


A data file must be closed at the end of the program. This can be accomplished with the
library function fclose ().
fclose (ptr);
Writing to a file:
To write something to the file, first open the file in writing mode.
FILE *p;
P= fopen (“abc.dat”,”w”);
Now to write something to above opened file, we can use the following functions.
 putc()
 fputc()
 fprintf()

putc() – This function writes a single character to the file. It takes two arguments, first the
character and second the file pointer.
Syntax:
putc (variable,filepointer);
Example:
#include<stdio.h>
void main()
{
FILE *p;
char c;
p = fopen(“sample.dat”,”w”);
do
{
c=getchar();
putc(c,p);
}while(c!=’\n’);
fclose(p);
}

Page 68 of 74
faizi_+918137088810

fputc() - This function writes a single character to the buffer. The data in buffer is written to
the file if the buffer is full or writing data to the buffer is finished. It takes two arguments, first
the character and second the file pointer.
Syntax:
fputc (variable,filepointer);
Example:
#include<stdio.h>
void main()
{
FILE *p;
char c;
p = fopen(“sample.dat”,”w”);
do
{
c=getchar();
fputc(c,p);
}while(c!=’\n’);
fclose(p);
}
fprintf() – This function writes formatted data to the file.
Syntax:
fprintf (filepointer,”control string”,arg1,arg2…);
Example:
void main()
{
FILE *p;
char c[] = “This is an array”;
int value = 10;
float f=5.6;
p=fopen(“sample.txt”,”w”);
fprintf(p,”%s %d %f”,c,value,f);
fclose(p);
getch();
}
Reading from a file:
To read data from a file, we will open the file in read mode.
FILE *p;
P= fopen (“abc.dat”,”r”);
Now to read data from the above opened file, we can use the following functions.
 getc()

Page 69 of 74
faizi_+918137088810

 fgetc()
 fscanf()
getc() – This function reads one character at a time from the file. It takes one argument that is
the file pointer.
Syntax:
variable = getc(file_pointer);
Example:
#include<stdio.h>
void main()
{
FILE *p;
char c;
p = fopen(“sample.txt”,”r”);
if(p = =NULL)
{
printf(“Error: can’t open the file”);
}
else
{
do
{
c=getc(p);
putch(c);
}while(c!=EOF);
}
fclose(p);
getch();
}
fgetc() – This function reads one character at a time from the file with the help of file pointer.
It takes one argument that is the file pointer.
Syntax:
variable = fgetc(file_pointer);
Example:
#include<stdio.h>
void main()
{
FILE *p;
char c;
p = fopen(“sample.txt”,”r”);
if(p = =NULL)

Page 70 of 74
faizi_+918137088810

{
printf(“Error: can’t open the file”);
}
else
{
do
{c=fgetc(p);
putch(c);
}while(c!=EOF);
}
fclose(p);
getch();
}
fscanf() – This function reads formatted data from the file.
Syntax:
fscanf (filepointer,”control string”,&arg1,&arg2…);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *p;
char name[10];
int i,age,mark;
clrscr();
p=fopen("text1.txt","w");
for(i=1;i<=3;i++)
{
printf("Enter details:");
scanf("%s %d %d",name,&age,&mark);
fprintf(p,"%s %d %d",name,age,mark);
}
fclose(p);
p=fopen("text1.txt","r");
for(i=1;i<=3;i++)
{
fscanf(p,"%s %d %d",name,&age,&mark);
printf("%s %d %d",name,age,mark);
}
fclose(p);

Page 71 of 74
faizi_+918137088810

getch();
}
Read a line of lower case text and store in uppercase within a file
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *p;
char c;
p=fopen("sample.txt","w");
do
{
c=getchar();
putc(toupper(c),p);
}while(c!='\n');
fclose(p);
getch();
}

Merge two files into an another file


#include<stdio.h>
void main()
{
char s;
FILE *f1,*f2,*f3;
clrscr();
f1=fopen("first.dat","w");
f2=fopen("second.dat","w");

printf("Enter first data ");


while((s=getchar())!='\n')
{ putc(s,f1);
}
fclose(f1);
printf("Enter second data ");
while((s=getchar())!='\n')
{ putc(s,f2);
}
fclose(f2);
f1=fopen("first.dat","r");

Page 72 of 74
faizi_+918137088810

f2=fopen("second.dat","r");
f3=fopen("merge.dat","w");
while(!feof(f1))
{ s=getc(f1);
putc(s,f3);
}
while(!feof(f2))
{ s=getc(f2);
putc(s,f3);
}
fclose(f1);
fclose(f2);
fclose(f3);
f3=fopen("merge.dat","r");
printf("Merged data \n ");
while(!feof(f3))
{ s=getc(f3);
printf("%c",s);
}
fclose(f3);
getch();
}
Bitwise Operators:
Operators that allow bitwise operators are called bitwise operators. Bitwise operators can be
classified into three categories.
 One’s complement operator

 Logical bitwise operator

 Shift bitwise operator

One’s complement operator


The One’s complement operator (~) is a unary operator that causes the bits of its operand to be
inverted so that 1s become 0s and 0s becomes 1s.
Eg: ~0110 -> 1001

Logical bitwise operator


These are classified into three types
 Bitwise AND

 Bitwise OR

 Bitwise XOR

Page 73 of 74
faizi_+918137088810

Bitwise AND (&)


The & operates on two integer operands. They are compared on bit-by-bit basis. The result of
& operation is 1 if both the bits have a value of 1otherwise it is 0.
Eg: 11000011 & 10101010 ->10000010
Bitwise OR (!)
The OR operates on two integer operands. They are compared on bit-by-bit basis. The result
of OR operation is 1 if at least one of the bits has value of 1.
Eg: 11000011 & 10101010 ->11101011
Bitwise XOR (^)
It is also called an exclusive OR operator.XOR returns 1 only if both the operands are unequal.
Eg: 110011 ^ 101110 -> 011101
Shift bitwise operator
These are classified in to two types
 Right Shift bitwise operator

 Left Shift bitwise operator


Right Shift bitwise operator
Right Shift bitwise operator operates on a single variable. It is represented by >> and its shifts
each bit in the operand to the right.
Eg: a= 11010111
a>>2 -> 00110101
Left Shift bitwise operator
It is represented by << and its shifts each bit in the operand to the left.
Eg: a= 11010111
a<<2 -> 01011100

Page 74 of 74

You might also like