C Notes - 05.06.2021

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 111

Shah and Anchor Kutchhi Engg College, Chembur C Programming

Computer Programming-I
What is Computer ?
A computer is a machine or device that performs processes, calculations and operations based on
instructions provided by a software.

Components of Computer System:

Computer System

Hardware Software
1) Input/ Output Devices 1) System Software
2) Storage Devices 2) Application Software
3) Processing Device
Examples:
1) Input/ Output Device : Keyboard, mouse, monitor, CD, DVD, modem, printer ….
2) Storage Device : Secondary memory(HDD),Primary memory(RAM),Cache Memory
3) Processing Device : Central processing unit (CPU)
4) System Software : Operating System(DOS, Win9x,WinXP, WinVista, Win2000,Unix,Linux)
Text editor, Compiler, Interpreter, Assembler …
5) Application Software : Library Software , Hospital Management Software, Banking Software…

By Prof. Manoj Dhande 7738339960


1
Shah and Anchor Kutchhi Engg College, Chembur C Programming

What is Programming?
Language: Language can be defined as media of communication.
Ex. English, Marathi, Hindi, Guajarati,…..
Computer Programming Language: The language used to communicate with computer is called
Computer Programming Language. The type of communication is written communication. Writing
instructions using CPL is called Programming.
Program: The collection of instructions written using CPL to perform specific task is called Program.
Software: The collection of Programs to perform specific task is called Software.
Evolution of Programming Language:
1) Low Level Language( Machine Language )
2) Middle Level Language ( Assembly Language)
3) High Level Language : English like language
Ex. Pascal, Ada, C, C++, Java…..
Classification of High level Languages:
1) Procedure-Oriented languages :
The year 1960 gave birth to structured programming. This method was largely encouraged by
languages like Pascal and C. it was easy to write complex program is Pascal or C. Many tools were
provided in structured programming. The approach was known as the procedure-oriented approach. In
this approach every problem is viewed as things to be done. Every problem is divided into small sub-
problems called function or subroutines. A typical structure of procedure oriented approach is shown
in fig.

Main program

Function -1 function -2 Function -3

Function-4 Function -5 function -6

Separates program are written for each sub-problem and then they are grouped together to
provide the solution. The important data items are placed as global so that they can be accessed by all
functions while every function is allowed to have its own local data. Functions are able to
communicate with each other and they can be share data. The emphasis is on algorithms. The top-
down approach is used in the program design. The structured programming languages are a powerful
By Prof. Manoj Dhande 7738339960
2
Shah and Anchor Kutchhi Engg College, Chembur C Programming

tool and it is possible to write moderately complex programs fairly easy. But the demand for more
user friendliness goes on increasing. It increases complexity of programs.

2) Object-Based languages
3) Object-Oriented Languages :
Ex. C++, Java….

Algorithm:
An algorithm is a step procedure to solve logical and mathematical problems. A recipe is a
good example of an algorithm because it says what must be done, step by step. It takes inputs
(ingredients) and produces an output (the completed dish). ... Informally, an algorithm can be called a
"list of steps".
A finite set of steps that must be followed to solve any problem is called
an algorithm. Algorithm is generally developed before the actual coding is done. It is written using
English like language so that it is easily understandable even by non-programmers.
Example:
An algorithm to add two numbers:
1. Take two number inputs
2. Add numbers using the + operator
3. Display the result
Flowchart:
A flowchart is simply a graphical representation of steps. It shows steps in sequential order and is
widely used in presenting the flow of algorithms. Typically, a flowchart shows the steps as boxes of
various kinds, and their order by connecting them with arrows.

Different Symbols used in flowchart:

Symbol Symbol Name Used to represent


Start/Stop Start and End of Flowchart
(Terminal )
Process Operation/calculation part

Input/ Output Input and output operations

Decision A condition which will be evaluated to


True or False

Connector Joining flow lines, Merging point

Flow line Direction of flow


Predefined process Function call

By Prof. Manoj Dhande 7738339960


3
Shah and Anchor Kutchhi Engg College, Chembur C Programming

Example :
1. Flowchart for addition of two numbers

2. Flowchart to check number is even or odd

By Prof. Manoj Dhande 7738339960


4
Shah and Anchor Kutchhi Engg College, Chembur C Programming

What is the Grammar of C Language?


Character Set:
A character is an alphabet, digit or special character. It is used to represent information.
Alphabets A,B,C,D……………..Z
a, b, c, d ……………….z

Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special Characters ~ @#%^&*()_-+{}


[ ] : ; ” < > ….
Tokens:
The smallest individual units in a program are called tokens. C++ has following tokens:
1) Keywords
2) Identifiers/ Variable
3) Constants/Literals
4) Separators
5) Operators
Keywords:
Keywords are reserved words whose meaning are predefined by developer of C language and
have already been explain to the complier. The keywords cannot be used as it is as Identifier name.
The following given keyword are available in C.
auto double int switch
break else long struct
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Identifiers:
Identifier can be defined as a name given to different program units such as memory location,
function, array, class, struct…. to identify (refer). Mostly given by the programmer. The name given to
memory location is also called variable.

By Prof. Manoj Dhande 7738339960


5
Shah and Anchor Kutchhi Engg College, Chembur C Programming

Rules for writing legal identifier name:


1) Only alphabets, digits and underscores are allowed.
2) Cannot start with a digit.
3) Keyword cannot be used as an identifier.
Ex:
Abc# illegal #(special character) not allowed
1abc illegal Cannot start with digit
For illegal Keyword cannot be used
abc legal
abc_xyz legal
_abc legal

Constants:
Constant can be defined as a quantity that doesn’t change.
Ex. Z= 10 x + 20.99 y +30
Here 10, 20.99 and 30 are constants.

Classification of Constants:
Constants

Numerical Constants Non-numerical Constants

Integer Real Character Backslash Character String


12 10.55 ‘A’ const “abc”
-20 -20.99 ‘d’ “abc_sd”
22 3.1E-2 ‘4’ “12344”
Backslash Character Constants (Escape Sequences):
Backslash character constants are Escape sequences. They are not printable characters but they
are used in output function. The list of Backslash character constants is given in table.

Code Meaning Code Meaning


\b Backspace \a Alert
\n New line \’ Single quote
\t Horizontal tab \” Double quote
\\ Backslash \0 Null
\? Question mark

Separators:
Separators are special symbols used to indicate where groups of code are divided and arranged.
Ex : . ; : ? Space ( ) [ ] etc

By Prof. Manoj Dhande 7738339960


6
Shah and Anchor Kutchhi Engg College, Chembur C Programming

Operators:
An operator is a symbol that tells the computer to perform certain operation. Operators are used in
program to manipulate data. The data, on which operators are operated, are known as operands. C++
operators can be classified depends upon
1) Number of operands required by operator
a) Unary operator
Ex. – (unary minus), ++ (increment), - - (decrement)….
b) Binary operator
Ex. +, - , /, % …..
c) Ternary operator
Ex. ?:
2) Type of operation performed by operator
a) Arithmetic operators
b) Relational operators
c) Logical operators
d) Assignment operators
e) Increment and Decrement operator
f) Conditional operator( Ternary operator)
g) Bitwise operators
h) sizeof operator
2.a) Arithmetic Operators :

Operator Name Example Result


+ Addition 20+10 30
- Subtraction 30-20 10
* Multiplication 23*2 46
/ Division 23/2 11.5
% Modulo 23%10 3

Modulo operator (%) gives remainder after integer division. It cannot be operated on real type
of operands.
Ex. 23.4%10 ---------- Wrong (23.4 is real type of operand)

2.b) Relational operators:


Operator Name Example Result
< Less than 10 < 20 True
<= Less than or equal to 20<=10 False
> Greater than 20>10 True
>= Greater than or equal to 10>=20 False
== Equal to 10= =11 False
!= Not equal to 10!=20 True

By Prof. Manoj Dhande 7738339960


7
Shah and Anchor Kutchhi Engg College, Chembur C Programming

True --------- Non zero value


False -------- Zero value
2.c) Logical Operators:
Operator Name Example Result
&& Logical AND (10<20) &&(30>10 ) True
‫׀׀‬ Logical OR (10>20) ||(30>10 ) True
! Logical NOT !(10>20) True

The logical AND logical OR operators are used when we want to test for more than one
condition and make decision. The truth tables for logical operators are as given below.
<

Operand1 Operand2 && (AND) ‫( ׀ ׀‬OR)


True True True True
True False False True
False True False True
False False False False
2.d) Assignment Operator(=) :
Assignment operator (=) is used to assign the results of an expression or constant to a variable.
Example:
x = a + b;
z = 0;
Final _value =100;
During the assignment operation the value of the expression on right hand side is computed and
is assigned to the variable on left hand side. Only variable name is allowed on left hand side,
expression is not allowed.
Short hand assignment operators:
In addition to the usual assignment operator ‘=’ C has short hand assignment operators.
For example:
x += y + 1 ; is equivalent x = x + (y+1)
a+=1 ; is equivalent to a=a+1
a- =1 ; is equivalent to a=a-1
a%= b ; is equivalent to a=a%b
a*=b ; is equivalent to a=a*b
a/=b ; is equivalent to a=a/b

2.e) Increment and Decrement operator:


C has two unary operators called increment and decrement operators. The increment operators
is ‘++’ which adds one to the operand.
For example: ++m or m++
Is same as m =m+1
The decrement operators is ‘--‘which subtracts one from the operand.
For example: --m or m--
Is equivalent to m=m-1.
Both the increment and decrement operators may either precede (prefix) or follow (postfix) the
operand.
By Prof. Manoj Dhande 7738339960
8
Shah and Anchor Kutchhi Engg College, Chembur C Programming

However, there is difference between prefix and postfix forms when you use these operators in
an expression. When an increment or decrement operator precedes its operand, the increment or
decrement operation is performed before obtaining the value of operand for use in the expression. If
the operators follow its operand, the value of the operand is obtained before incrementing or
decrementing it.
For example: if x = 10 then expression y = ++x sets y to 11 and x to 11.
However if you write the code as
x=10 then expression y =x++ sets y to 10 and x to 11.
2.f) Conditional Operator / Ternary Operator:
C contains a very powerful and convenient operator that can be used to form conditional
expression. This operator is also called ternary operator (? :) has the form:
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2 and Exp3 are expressions. The above expression says “if Exp1 is true (i.e. if
its value is non zero), then the value returned will be Exp2 otherwise the value returned will be Exp3”.
For example: y = x > 9 ? 100: 200;
The value 100 will be assigned to variable y if x is greater than 9, otherwise 200 will be
assigned to variable y. The above expression is equivalent to
if (x>9)
then y = 100;
else y = 200;
2. g) Bitwise operators:
One of C’s powerful features is the set of bit manipulation operators. Theses permit the
programmer to access and to manipulate individual bits within piece of data. Bitwise operators
can be used with char and integer data types. They cannot be used with other data types such as
float double etc. the bitwise operators are listed in table.
Consider: A= 193 and B = 127
Binary Equivalent of A: 11000001
Binary Equivalent of B: 01111111
Operators Name Example Result
& bitwise AND A&B 65
‫׀‬ bitwise OR A|B 255
^ bitwise XOR A^B 190
~ one’s complement ~A 62
>> right shift A>>1 96
<< left shift A<<1 386

Truth Table for Bitwise AND, OR, XOR and One’s complement operators
A B A&B A|B A^B
0 0 0 0 0 A ~A
0 1 0 1 1 0 1
1 0 0 1 1 1 0
1 1 1 1 0

By Prof. Manoj Dhande 7738339960


9
Shah and Anchor Kutchhi Engg College, Chembur C Programming

2. h) sizeof operator:
The sizeof operator used to compute the size of its operand. It returns the size of a variable. It can be
applied to any data type, float type, pointer type variables.
When sizeof() is used with the data types, it simply returns the amount of memory allocated to that
data type. The output can be different on different machines like a 32-bit system can show different
output while a 64-bit system can show different of same data types.
Example :
int a=16;
printf(“Size of variable a=%d”,sizeof(a)); Size of Variable a=4
printf(“Size of int data Type=%d”, sizeof(int)); Size of int data Type=4
Order of Precedence and Associativity of Operators:
Each operator in C has a precedence associated with it. Precedence is used to determine how an
expression involving more than one operator is evaluated. There are district levels of precedence and
operator may belong to one of the level. The operator at higher level of precedence is evaluated first.
The operators with same precedence are evaluated either from left to right or from right to left. This is
known as associativity property of an operator.

Operator Description Associativity Rank


:: scope resolution operator Left to Right 1
! Logical NOT
+ unary plus
- unary minus 2
++ Increment
-- Decrement Right to Left
~ One’s complement
* Pointer reference
& Address
sizeof sizeof
* Multiplication
/ Division 3
Left to Right
% Modulo division
+ Addition
- Subtraction Left to Right 4
<< Left shift 5
>> Right shift
< Less than
<= Less than or equal to Left to Right
> Greater than 6
>= Greater than or equal to
== Equality 7
!= Inequality Left to Right
& Bitwise AND Left to Right 8
By Prof. Manoj Dhande 7738339960
10
Shah and Anchor Kutchhi Engg College, Chembur C Programming

^ Bitwise XOR Left to Right 9


| Bitwise OR Left to Right 10
&& Logical AND Left to Right 11
|| Logical OR Left to Right 12
?: Conditional Statement Right to Left 13
= Assignment Right to Left 14

Data Types:
Data types in C can be classified into following categories:
1) Build-in data types
a) char
b) int
c) float
d) double
e) void
The use of void data type is
i) To specify the return type of a function when it is not returning any value.
ii) To indicate an empty argument list to a function.
2) Derived data types
a) Array b) Function c) Pointer
3) User-defined data types
a) Structure b) Union
Data Type Modifiers:
Data type modifiers can be used to increase memory size and range of the data types. short
a) short b) long c) signed d) unsigned
Sometimes, we know in advance that the value which we are using will be always positive.
In such a case we can use unsigned form of data type. Here the range of data type gets increased, since
we need not to reserve one bit for sign. By default data type is always signed. Signed and unsigned
modifiers cannot be used with float, double and long double data types.

Data Type Range Bytes


char -128 to +127 1
unsigned char 0 to 255 1
signed char -128 to +127 1
int -32768 to +32767 2
unsigned int 0 to 65535 2
signed int -32768 to +32767 2
short int -32768 to +32767 2
unsigned short int 0 to 65535 2
signed short int -32768 to +32767 2
long int -2147483648 to +2147483647 4
signed long int -2147483648 to +2147483647 4
unsigned long int 0 to 4294967295 4
float -3.4e38 to +3.4e38 4
double -1.7e308 to +1.7e308 8
long double -1.7e4932 to +1.7e4932 10
By Prof. Manoj Dhande 7738339960
11
Shah and Anchor Kutchhi Engg College, Chembur C Programming

Structure of C program:
Documentation Section
Files inclusion section
function declaration section
Global variable declaration section
Main function definition section
{
Local variable declaration
Body of main function
}
Function definition section
1) Write a program to display multi-line message on the screen.
Program:
//Display of multi-line message
# include<stdio.h >
#include<conio.h>
void main ( )
{
printf(“C is better than Pascal.\n”);
printf(”C is Procedural programming Language.”);
getch();
}
Output
C is better than Pascal.
C is Procedural programming Language.

2) Write a program to read three integer numbers and display their average.
Program:
//Average of three numbers
# include<stdio.h>
#include<conio.h>
void main( )
{
int m1,m2,m3;
float avg;
printf(”Enter 3 numbers: ”);
scanf(“%d%d%d”,&m1,&m2,&m3);
avg=(m1+m2+m3)/3.0;
printf(“ Average =%f”,avg) ;
getch();
}
Output:
Enter 3 numbers: 10 20 30
Average=20.000000

By Prof. Manoj Dhande 7738339960


12
Shah and Anchor Kutchhi Engg College, Chembur C Programming

Program Statements:
//Program for addition 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+b;
printf("addition=%d", c);
getch();
}

//Program to calculate area and circumference of a circle


#include<stdio.h>
#include<conio.h>
void main()
{
float r,c,a;
clrscr();
printf("enter the radius of circle");
scanf("%f",&r);
a=3.14*r*r;
printf("the area of circle is %f\n",a);
c=2*3.14*r;
printf("the circumference of circle is %f",c);
getch();
}

1) Write a program to calculate the volume of a sphere.


2) Write a program to find square and cube of a number.
3) Write a problem to convert a given temperature in Celsius to Fahrenheit by using formula.
F = 1.8 Celsius + 32
//Program to convert temperature from Fahrenheit to Celsius
#include<stdio.h>
#include<conio.h>
void main()
{
float F,C;
clrscr();
printf("enter temperature in Fahrenheit:");
scanf("%f",&F);
C=(F-32)*5/9;
By Prof. Manoj Dhande 7738339960
13
Shah and Anchor Kutchhi Engg College, Chembur C Programming

printf("temperature in Celsius=%f",C);
getch();
}

Rajesh’s basic salary is input through the keyboard. His dearness allowance is 40% of basic
salary and house rent allowance is 20% of basic salary. Write a program to calculate his grass
salary.
//Program to calculate gross salary of an employee
#include<stdio.h>
#include<conio.h>
void main()
{
float b,g;
clrscr();
printf("enter basic salary:");
scanf("%f",&b);
g=b+(b*40/100)+(b*20/100);
printf("gross salary is %f",g);
getch();
}

Write a program to interchange the value of the two variables using third variable.
//Program to swap the content of the two variables using the third variable
#include<stdio.h>
#include<conio.h>
void main()
{
int A,B,C;
clrscr();
printf("Enter value of A & B:");
scanf("%d%d",&A, &B);
C=A;
A=B;
B=C;
printf("After swapping:\n");
printf("A=%d\n",A);
printf("B=%d",B);
getch();
}

By Prof. Manoj Dhande 7738339960


14
Shah and Anchor Kutchhi Engg College, Chembur C Programming

Write a program to interchange the value of the two variables without using third variable.
//Program to swap content of two variables without using third variable
#include<stdio.h>
#include<conio.h>
void main()
{
int A,B;
clrscr();
printf("enter values of A & B:");
scanf("%d%d",&A,&B);
A=A+B;
B=A-B;
A=A-B;
printf("after swapping\n");
printf("A=%d\n",A);
printf("B=%d",B);
getch();
}
//Program to rotate the content of 3 variables without using 4th variable
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("enter value of a, b & c: ");
scanf("%d%d%d", &a, &b, &c);
a=a+b;
b=a-b;
a=a-b;
b=b+c;
c=b-c;
b=b-c;
printf("After Rotating\n");
printf("a=%d\n",a);
printf("b=%d\n",b);
printf("c=%d",c);
getch();
}

8) Write a program that converts inches to centimeters. For example, if user enters 16.9 for a length
in inches, the output would be 42.926 cm (One inch equals 2.54 centimeter).
9) Write a program to exchange the digits of a two digit number.
10) Write a program to accept a 3 digit number and display sun of digits and reverse of a number.

By Prof. Manoj Dhande 7738339960


15
Shah and Anchor Kutchhi Engg College, Chembur C Programming

//Program to find sum of digits and reverse of a given 3 digit number


#include<stdio.h>
#include<conio.h>
void main()
{
int no,sum,d1,d2,d3,rev;
clrscr();
printf("enter 3 digit no:");
scanf("%d",&no);
d1=no%10;
no=no/10;
d2=no%10;
no=no/10;
d3=no%10;
sum=d1+d2+d3;
rev=d1*100+d2*10+d3;
printf("sum of digits=%d",sum);
printf("reverse of two=%d",rev);
getch();
}
//Program to display maximum of 2 given numbers using conditional operator
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("enter 2 nos.:");
scanf("%d%d",&a,&b);
(a>b)?printf("%d is max",a): printf("%d is max",b);
getch();
}

11) Write a program to accept a 4 digit number and to check whether it is perfect square number or
not.
//Program to check weather given four digit number a perfect square number or not
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int no,no1,no2,sno,sno1,sno2;
printf("enter a 4 digit no");
scanf("%d",&no);
sno=sqrt(no);
By Prof. Manoj Dhande 7738339960
16
Shah and Anchor Kutchhi Engg College, Chembur C Programming

no1=no/100;
no2=no%100;
sno1=sqrt(no1);
sno2=sqrt(no2);
if(sno*sno==no&&sno1*sno1==no1&&sno2*sno2==no2)
printf("no is a perfect sq no");
else
printf("no is not a perfect sq no");
getch();
}

//Program to check whether a given number is a perfect square number or not


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int no,s;
clrscr();
printf("enter any no:");
scanf("%d",&no);
s=sqrt(no);
(s*s==no)? printf("no is perfect sq no"):printf("no is not a perfect sq no");
getch();
}

12) Write a program to accept a number and to check whether it is even or odd number.
13) Write a program to accept a year as input and printout if it is a leap year.
Write a program to display absolute value on an entered number.
//Program to find absolute value of given number using conditional operator
#include<stdio.h>
#include<conio.h>
void main()
{
int no,a;
clrscr();
printf("enter a no:");
scanf("%d",&no);
a=no>0?no:-no;
printf("absolute value is %d",a);
getch();
}

By Prof. Manoj Dhande 7738339960


17
Shah and Anchor Kutchhi Engg College, Chembur C Programming

//Program to find max of 3 numbers using conditional operator


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max;
clrscr();
printf("enter 3 nos:");
scanf("%d%d%d",&a,&b,&c);
max=(a>b)?((a>c)?a:c):((b>c)?b:c);
printf("%d is max",max);
getch();
}

By Prof. Manoj Dhande 7738339960


18
Shah and Anchor Kutchhi Engg College, Chembur C Programming

CONTROL STRUCTURES
Statement:
A statement is part of program that is executed. A statement specifies certain action. C program
is a set of statements. These statements are normally executed one after the other. This is known as
sequential execution.
But in practice we find sequential is always not suitable. There are situations when you need to
change our action as per circumstances. Sometimes we may need to repeat the actions. This involves a
kind of decision making.
This C provides three types of control structures (Statements).
1. Branching Statements
2. Loop Statements
3. Control Breaking Statements.

1. Branching Statements:
We test for condition and based on result of condition we execute certain group of statements.
A group of statement is also called as block. C provides following branching statements.
a) Simple if
b) if else
c) Nested if else
d) else –if ladder
e) Switch statement

2. Loop Statements:
Certain group of statements is executed repeatedly by forming a loop. C provides following
loop statements.
a) while loop
b) do-while loop
c) for loop

3. Control Breaking Statements :


Control breaking statements can be used to transfer execution to any required part of the
program. C provides following control breaking statements
a) break
b) continue
c) goto

1.a) Simple if Statement:


The if statement is powerful decision making statement and is used to control the flow of
execution of statements. It is a two way decision statement. The syntax of simple if statement is…

if (condition)
{
Statement-block;
}
Stmt-X;

By Prof. Manoj Dhande 7738339960


19
Shah and Anchor Kutchhi Engg College, Chembur C Programming

Here if is a keyword. The condition is an expression. This expression always returns a true
value (i.e. non zero value) or a false value (i.e. a zero value). The Statement–block may be a single
statement or a group of statements where each statement ends with semicolon. The Stmt–X is the next
statement appearing after Statement–block.
In if statement, first of all, condition is evaluated. If it is true then Statement-block is
executed, otherwise the Statement-block is skipped and the execution will jump to Stmt-X. Observe
that when condition is true, both the Statement–block and stmt-X are executed. But if condition is
false, only Stmt-X is executed. The flow-chart of simple-if statement is shown in fig

Flowchart:
Entry

True
Condition

Statement-block
False

Stmt-X

Program Statements:

WAP to display absolute value on an entered number.


// Program to find absolute value of given number using simple if

#include<stdio.h>
#include<conio.h>
void main()
{
int no;
clrscr();
printf("enter any no:");
scanf("%d",&no);
if(no<0)
no=-no;
printf("absolute no=%d",no);
getch();
}

1) WAP to find highest of three numbers.


2) WAP to find the value of Y for a particular value of K.

By Prof. Manoj Dhande 7738339960


20
Shah and Anchor Kutchhi Engg College, Chembur C Programming

If K=1 Y= a x +b
K=2 Y= ax2+b2
K=3 Y= - ax
K=4 Y= a+x
Accept values of a, x, b and K from user.

1.b) The if-else statement


The if-else statement is an extension of simple-if statement. In simple-if, if the condition is
false, then we go to next statement. Many times we need to execute certain group of statements if the
condition is false. In such a case we need to use if-else rather than simple-if.
The syntax of if-else statement is

if (condition)
{
Block1;
}
else
{
Block2;
}
Stmt-X;
Here if and else are keywords. The condition is an expression. It returns either a true or false
value. If condition is true, then Block1 is executed; otherwise Block2 is executed. In either case, either
Block1 or Block2 is executed, not both. In both the cases the control is subsequently transferred to
Stmt-X.
Flowchart:
Entry

True Test False


Expressiotn

Block1 Block2

Statement -X

By Prof. Manoj Dhande 7738339960


21
Shah and Anchor Kutchhi Engg College, Chembur C Programming

1. Suppose we are writing program to find largest of two numbers. The if-else statement for this
situation is shown below.
if (a > b)
{
prinf(“A is largest”);
}
else
{
prinf(“B is largest”);
}
Program Statements:
WAP to check whether an entered number is even or odd.
//Program to check weather given number is even or odd
#include<stdio.h>
#include<conio.h>
void main()
{
int no;
clrscr();
printf("enter no");
scanf("%d",&no);
if(no%2==0)
printf("no is even");
else
printf("no is odd");
getch();
}
//Program to find max of 2 numbers using if-else
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("enter 2 nos");
scanf("%d%d",&a,&b);
if(a>b)
printf("max is %d",a);
else
printf("max is %d",b);
getch();
}

By Prof. Manoj Dhande 7738339960


22
Shah and Anchor Kutchhi Engg College, Chembur C Programming

WAP to check whether entered number is divisible by 3 and 5 or not.


//Program to check if no is divisible by 3 & 5 or not
#include<stdio.h>
#include<conio.h>
void main()
{
int no, a;
clrscr();
printf("enter a no");
scanf("%d",&no);
if(no%3==0&&no%5==0)
printf("no is divisible by 3 & 5");
else
printf("no is not divisible 3 & 5");
getch();
}

WAP to calculate (a/b)+(c/d), display proper message if denominator is zero.


// Program to calculate (a/b)+(c/d), display proper message if denominator is zero
#include<stdio.h>
#include<conio.h>
void main()
{
float a,b,c,d,e;
clrscr();
printf("enter values of a,b,c&d");
scanf("%f%f%f%f",&a,&b,&c,&d);
if(b*d==0)
printf("denominator is zero");
else
{
e=(a*d+c*d)/(b*d);
printf("result is %f",e);
}
getch();
}

WAP to accept a 4 digit number and to check whether it is perfect square number or not.
// Program to check if no is perfect square(4 digit number)
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int no,no1,no2,sno,sno1,sno2;
clrscr();
By Prof. Manoj Dhande 7738339960
23
Shah and Anchor Kutchhi Engg College, Chembur C Programming

printf("Enter a 4 digit number\n");


scanf("%d",&no);
sno=sqrt(no);
no1=no/100;
no2=no/100;
sno1=sqrt(no1);
sno2=sqrt(no2);
if((sno*sno==no)&&(sno1*sno1==no1)&&(sno2*sno2==no2))
printf("perfect square");
else
printf("not a perfect square");
getch();
}

1. c) Nested if-else statement


In practice many times we need to make a series of decision. In such a case we may have to use
more than one if-else statement in the nested form. A nested if-else is an if-else that is the target of
another if or else. In nested if-else, an else always refers to the nearest if statement that is within the
same block.
The general form of Nested if-else statement is

if (condition1)
{
if( condition2)
{
Block1;
}
else
{
Block2;
}
}
else
{
if( condition3)
{
Block3;
}
else
{
Block4;
}
}
Stmt –X;

By Prof. Manoj Dhande 7738339960


24
Shah and Anchor Kutchhi Engg College, Chembur C Programming

Here if condition1 is true and condition2 also true them Block1 will execute. If condition1 is true
and condition2 is false then Block2 will execute. If condition1 is false and condition3 is true then
Block3 will execute. If condition1 is false and condition3 is false then Block4 will execute.

Flowchart:
Entry

F T
Cond1

F Cond3 T F T
Cond2
Block4 Block3 Block2 Block1

Stmtx
Program Statements:
WAP to find largest of three numbers.
//Program to find max of 3 numbers using nested if-else
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("enter 3 nos");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
printf("%d is max",a);
else
printf("%d is max",c);
}
else
{
if(b>c)
printf("%d is max",b);
else
printf("%d is max",c);
}
getch();
}

By Prof. Manoj Dhande 7738339960


25
Shah and Anchor Kutchhi Engg College, Chembur C Programming

WAP to find smallest of three numbers.


//Program to find smallest of 3 given numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,d;
clrscr();
printf("enter 3 nos:");
scanf("%d%d%d",&a,&b,&c);
if(a<b)
{
if(a<c)
printf("%d is smallest",a);
else
printf("%d is smallest",c);
}
else
{
if (b>c)
printf("%d is smallest",b);
else
printf("%d is smallest",c);
}
getch();
}
WAP to accept a year as input and printout if it is a leap year.
//Program to check whether an entered year is a leap year or not
#include<stdio.h>
#include<conio.h>
void main()
{
long int y;
clrscr();
printf("enter any year:");
scanf("%ld",&y);
if(y%100==0)
{
if(y%400==0)
printf("it is a leap year");
else
printf("it is not a leap year");
}
else
{
if(y%4==0)
printf("it is a leap year");
By Prof. Manoj Dhande 7738339960
26
Shah and Anchor Kutchhi Engg College, Chembur C Programming

else
printf("not a leap year");
}
getch();
}

1. d) The else-if ladder


When there are multi-path decisions involved, we can use ifs, another way. Here we have a chain
of if and each else is associated with if statement. This programming construct is called else-if ladder.
Because of its appearance, sometimes it is also called as if–else-if staircase. The general form of else-if
ladder is.
if (condition1)
{
block1;
}
else if (condition2)
{
block2;
}
else if (condition3)
{
block3;
}
-----------------------
-----------------------
else if (condition - n)
{
Block-n;
}
else
{
default block;
}
Stmt–X;
The conditions are evaluated from top, downwards. As soon as the true condition is found, the
block associate with it is executed and control is transferred to Stmt-X skipping the rest of the ladder.
When all n- conditions become false, then the final else containing the default block is executed.

By Prof. Manoj Dhande 7738339960


27
Shah and Anchor Kutchhi Engg College, Chembur C Programming

Flowchart:
Entry

T Condition-1 F

T Condition-2 F

Block1

Block2 T Condition -3 F

Block3 T Condition-n F

Block-n Default Block

Statement- X

Program Statements:
WAP to calculate value of f(x), if x has different ranges of values as below
f(x) = x2+2 0<=x<=10
= x2+2x 10<x<=20
3 2
= x +2x 20<x<=30
=0 x>30

//Program to calculate f(x) from given data


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float x,f_x;
clrscr();
printf("enter value of x");
scanf("%f",&x);
if((x>=0)&&(x<=10))
f_x=pow(x,2)+2;
else if(x<=20)
f_x=pow(x,2)+2*x;
By Prof. Manoj Dhande 7738339960
28
Shah and Anchor Kutchhi Engg College, Chembur C Programming

else if(x<=30)
f_x=pow(x,3)+2*pow(x,2);
else
f_x=0;
printf("function value f(x)=%f",f_x);
getch();
}

WAP to find all the roots of Quadratic equation.


//Program to find all the roots of a quadratic equation
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c,d,rp,img;
clrscr();
printf("enter value of a,b,c");
scanf("%f%f%f",&a,&b,&c);
if(a==0&&b==0)
printf("calculation not possible");
else if(a==0)
{
printf("not quad eqtn");
printf("root=%f",-c/b);
}
else
{
d=pow(b,2)-4*a*c;
if(d==0)
{
printf("only one root");
printf("root=%f",-b/2*a);
}
else if(a>0)
{
printf("two real roots");
printf("root1=%f",(-b+sqrt(d)/2*a));
printf("root2=%f",(-b-sqrt(d)/2*a));
}
else
{
rp=-b/2*a;
img=sqrt(abs(d)/2*a);
printf("root1=%f+i%f",rp,img);
printf("root2=%f-i%f",rp,img);
}
By Prof. Manoj Dhande 7738339960
29
Shah and Anchor Kutchhi Engg College, Chembur C Programming

}
getch();
}

1) An electric power distribution company charges its domestic customers as follows.

Consumption units Rate of charges


up to 30 units Rs. 0.75 per unit
31 to 100 units Rs. 2.50 per unit
101 to 301 units Rs. 3.00 per unit
Above 301 units Rs. 4.60 per unit

WAP to read customer number and number of units consumed. Compute charges.
//Program to calculate Electricity bill amount
#include<stdio.h>
#include<conio.h>
void main()
{
int u;
float bill_amt;
clrscr();
printf("enter no of units:");
scanf("%d",&u);
if(u<=30)
bill_amt=0.75*u;
else if(u<=100)
bill_amt=2.50*u;
else if(u<=301)
bill_amt=3.0*u;
else
bill_amt=4.60*u;
printf("bill amount is %f",bill_amt);
getch();
}

1. e) Switch-case Statement :
When we need to select many alternatives, the program using if statement becomes complex
one. The readability of the program decreases. Sometimes it may create confusion to the reader. C has
built in multi-way decision statement known as switch. It is also called as multiple branch selection
statement. The switch statement tests the value of given variable (or expression) against a list of case
values and when match is found, a block of statement associated with that case is evaluated.

By Prof. Manoj Dhande 7738339960


30
Shah and Anchor Kutchhi Engg College, Chembur C Programming

Syntax:
switch(expression)
{

case const-1: Block-1;


break;
case const-2 : Block-2;
break;
-----------------
-----------------
case const-n : Block-n;
break;
default : default Block;

}
Stmt–X;
Here switch, case, default and break are keywords. The expression is an integer expression or
character expression. That is value of the expression must evaluate to a character value or integer
value. Floating point or other expressions are not allowed. const-1, const-2,-----const-n are constants or
constant expressions. They are known as case labels. Each of this value should be unique with a switch
statement. Block-1, Block-2, -------, Block-n are statement lists and may contain zero or more
statements. There is no need to use braces around these blocks.
When switch statement is executed, the value of this expression is successively compared against
the values const-1, const-2, -------, const-n. If a case is found whose value matches with the value of
the expression, then the block of statements that follows the case is executed.
The break statement at the end of each block signal the end of particular case and causes an exit
from the switch statements, transferring control to the Stmt-X.
The default is as optional case. When present, it will be executed if the value of the expression
does not match with any of the case values. If not present, no action takes places if all matches fails
and control goes to the Stmt-X.

By Prof. Manoj Dhande 7738339960


31
Shah and Anchor Kutchhi Engg College, Chembur C Programming

Flowchart:

Expression

Const1 Y Block1

N
Y
Const2 Block2

ConstN Y Block-n

N
Default Block

Stmt-X

i) The switch statement differs from the if in that switch can only test for equality, whereas we
can evaluate any type of relational or logical expression using if.
ii) Two case values cannot be identical.
iii) If character constants are used in the switch statement, they are automatically converted to
integers.
iv) If you forget a break in a switch statement, the compiler will not issue an error message. The
present case is executed and computer will go on to execute next case also. This may produced
a puzzling output. When computer starts executing a case, it does stop unit it encounters either
a break or end of the switch statement.

Problem Statements:
WAP to simulate simple arithmetic calculator using switch-case.
//Program to simulate simple arithmetic calculator
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,op;
clrscr();
printf("enter 2 nos");
scanf("%d%d",&a,&b);
printf("1:add\n");
printf("2:sub\n");
By Prof. Manoj Dhande 7738339960
32
Shah and Anchor Kutchhi Engg College, Chembur C Programming

printf("3:mult\n");
printf("4:div\n");
printf("5:modulo\n");
printf("select operation:");
scanf("%d",&op);
switch(op)
{
case 1: c=a+b;
printf("add=%d",c);
break;
case 2: c=a-b;
printf("sub=%d",c);
break;
case 3: c=a*b;
printf("mult=%d",c);
break;
case 4: c=a+b;
printf("div=%d",c);
break;
case 5: c=a%b;
printf("modulo=%d",c);
break;
default: printf("wrong input");
}
getch();
}
// Program to accept first character of a color and to display name of color
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("enter any character (r,g,b):");
scanf("%c",&ch);
switch (ch)
{
case 'r':
case 'R': printf("red");
break;
case 'g':
case 'G': printf("green");
break;
case 'b':
case 'B': printf("blue");
break;
}
By Prof. Manoj Dhande 7738339960
33
Shah and Anchor Kutchhi Engg College, Chembur C Programming

getch();
}

1) WAP to accept number of the month and to display name of the month.
2) WAP to accept number of the day and to display name of the day.
WAP to accept one digit number and to display that number in word.
//Program to accept 1 digit no and to display it in word
#include<stdio.h>
#include<conio.h>
void main()
{
int no;
clrscr();
printf("enter one digit no");
scanf("%d",&no);
switch(no)
{
case 0: printf("zero");
break;
case 1: printf("One");
break;
case 2: printf("two");
break;
case 3: printf("three");
break;
case 4: printf("four");
break;
case 5: printf("five");
break;
case 6: printf("six");
break;
case 7: printf("seven");
break;
case 8: printf("eight");
break;
case 9: printf("nine");
break;
default: printf("wrong input");
}
getch();
}

By Prof. Manoj Dhande 7738339960


34
Shah and Anchor Kutchhi Engg College, Chembur C Programming

2. Loop Statements:
Computer has ability to perform a set of actions repeatedly. This involves repeating a set of some
portion of the program either a specific number of times or until a particular condition is being
satisfied. This repetitive operation is called looping.
C provides three loop statements. They are also called as interactions statements. They are:
a) The while loop.
b) The do- while loop.
c) The for loop.

2.a) While loop :


The general form of while loop is:

while (condition)
{
Body;
}
Stmt-X;
Here while is a keyword. The condition is an expression which may return zero or non zero
value. A non-zero value is treated as true value and zero value as a false value. The body of loop is an
empty statement, a single statement or a block of statements.
The while is entry-controlled loop. The condition is evaluated first and if the condition is true
then the body of loop is executed. After execution of body, the condition is once again evaluated and if
it is true, the body is executed once again. This process is repeated, execution of body continues until
the condition finally becomes false and control is transferred out of the loop. On exit, the program
continues with statement Stmt-X immediately after the body of the loop.

Flowchart:

False True
Cond
Body
StmtX

2. b) do-while Loop :
In while loop, the condition is tested first before the loop is executed. If condition is false in first
attempt then body of loop may not be executed even once. In some occasions it might be necessary to
execute body of the loop before test is performed. Such situation can be handled with do-while loop.
The general form of do-while statement is:
do
{
Body;

} while (condition);
Stmt-X;
Here do-while are keywords. The condition is an expression which may return true or false
value. The body of the loop is an empty statement, a simple statement or a block of statements.
By Prof. Manoj Dhande 7738339960
35
Shah and Anchor Kutchhi Engg College, Chembur C Programming

In do-while first body of loop will execute. At the end of the loop, the condition in while is
evaluated. If the condition is true, the program continues to execute the body of the loop ones again.
This process continues as long as condition is true. When condition becomes false, the loop will be
terminated and control goes to the next statement Stmt-X after the while loop. In do-while the body of
the loop is executed at least once and such a loop is called exit-controlled loop.

Flowchart:

Body

True
Cond
false

Stmt-X

Problem Statements:
//Program to display the table of a given number using while loop
#include<stdio.h>
#include<conio.h>
void main()
{
int no,a=0,b;
clrscr();
printf("enter any no:");
scanf("%d",&no);
while(a<=10)
{
b=no*a;
printf("%d*%d=%d\n",no,a,b);
a++;
}
getch();
}

WAP to find sum of the digits of a given number.

#include<stdio.h>
#include<conio.h>
void main()
{
int no,sum=0,d;
clrscr();
printf("enter any no:");
scanf("%d",&no);
By Prof. Manoj Dhande 7738339960
36
Shah and Anchor Kutchhi Engg College, Chembur C Programming

while(no!=0)
{
d=no%10;
sum=sum+d;
no=no/10;
}
printf("sum of digits =%d",sum);
getch();
}

WAP to find reverse of a given number.


#include<stdio.h>
#include<conio.h>
void main()
{
int no,rev=0,d;
clrscr();
printf("enter any no:");
scanf("%d",&no);
while(no!=0)
{
d=no%10;
rev=rev*10+d;
no=no/10;
}
printf("reverse of no=%d",rev);
getch();
}

WAP to check whether an entered number is palindrome or not.


#include<stdio.h>
#include<conio.h>
void main()
{
int no,rev=0,d,m;
clrscr();
printf("enter any no:");
scanf("%d",&no);
m=no;
while(no!=0)
{
d=no%10;
rev=rev*10+d;
no=no/10;
}
if(m==rev)
printf("Number %d is palindrome",m);
By Prof. Manoj Dhande 7738339960
37
Shah and Anchor Kutchhi Engg College, Chembur C Programming

else
printf("Number %d is not palindrome",m);
getch();
}

WAP to check whether an entered number is Armstrong number or not.


#include<stdio.h>
#include<conio.h>
void main()
{
int no,d,n,sum=0;
clrscr();
printf("enter any no:");
scanf("%d",&no);
n=no;
while(no!=0)
{
d=no%10;
sum=sum+d*d*d;
no=no/10;
}
if(n==sum)
printf("no is Armstrong no");
else
printf("no is not Armstrong no");
getch();
}

WAP to find GCD and LCM of two numbers.


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,r,m,n;
clrscr();
printf("enter 2 nos:");
scanf("%d%d",&a,&b);
m=a,n=b;
while(b!=0)
{
r=a%b;
a=b;
b=r;
}
printf("gcd=%d\n",a);
printf("lcm=%d",(m*n)/a);
By Prof. Manoj Dhande 7738339960
38
Shah and Anchor Kutchhi Engg College, Chembur C Programming

getch();
}

2.c) for Loop :


The for loop is most popular loop. It is widely used by the programmers. It is also an entry
controlled loop. The general form of for statement is:

for (Exp1; Exp2 ; Exp3)


{
Body;
}
Stmt-X;
Here,
Exp1: Initialization expression e.g. i=0, j=10
Exp2 : Condition expression e.g i<10, i<j
Exp3 : Update expression e.g. i++, j--

Flowchart:

Exp1 Exp3

False
Exp2

True
StmtX Body

In for loop first Exp1 will execute then Exp2 is evaluated, if Exp2 is true then Body of the loop
will be executed, then Exp3 will execute and again it will go to execute Exp1. This process continues
as long as Exp2 is true. When Exp2 becomes false, the loop will be terminated and control goes to the
next statement stmt-X after the for loop.

Nesting of for loop:


When one for statement is used within another for statement, then it is called nesting of for
loop. Two loops can be nested as follows:

for (i=1;i<10;i++)
{
---------------
for ( j = 1; j<5; j++)
{
----------------
}
}

By Prof. Manoj Dhande 7738339960


39
Shah and Anchor Kutchhi Engg College, Chembur C Programming

Problem Statements:
WAP to display table of a given number.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,no;
clrscr();
printf("enter a no:");
scanf("%d",&no);
for(i=0;i<11;i++)
printf("%3d*%3d=%3d\n",no,i,i*no);
getch();
}

WAP to calculate factorial of a given number.


#include<stdio.h>
#include<conio.h>
void main()
{
long int no,i,fact=1;
clrscr();
printf("enter any no:");
scanf("%ld",&no);
for(i=no;i>=1;i--)
fact=fact*i;
printf("factorial=%ld",fact);
getch();
}

WAP to calculate power of a number(x raised to n), accept value of x and n from user.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,x,i,result=1;
clrscr();
printf("enter x & n:");
scanf("%d%d",&x,&n);
for(i=1;i<=n;i++)
{
result=result*x;
}
printf("answer=%d",result);
getch();
}
By Prof. Manoj Dhande 7738339960
40
Shah and Anchor Kutchhi Engg College, Chembur C Programming

WAP to display first ‘n’ terms of a Fibonacci series.


#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,x=0,y=1,z;
clrscr();
printf("enter no of terms:");
scanf("%d",&n);
printf("%3d%3d",x,y);
for(i=1;i<=n-2;i++)
{
z=x+y;
printf("%3d",z);
x=y;
y=z;
}
getch();
}
WAP to display all palindrome numbers from 100 to 500
#include<stdio.h>
#include<conio.h>
void main()
{
int i,rev,d,a;
clrscr();
printf("Palindrome numbers from 100 to 500 are\n");
for(i=100;i<=500;i++)
{
rev=0;
a=i;
while(a!=0)
{
d=a%10;
rev=(rev*10)+d;
a=a/10;
}
if(i==rev)
printf("%d\n",i);
}
getch();
}

WAP to display all Armstrong numbers from 100 to 500.


#include<stdio.h>
#include<conio.h>
By Prof. Manoj Dhande 7738339960
41
Shah and Anchor Kutchhi Engg College, Chembur C Programming

void main()
{
int i,sum,d,a;
clrscr();
printf("Armstrong numbers between 100 to 500 are:\n");
for(i=100;i<=500;i++)
{
sum=0;
a=i;
while(a!=0)
{
d=a%10;
sum=sum+(d*d*d);
a=a/10;
}
if(i==sum)
printf("%d\n",i);
}
getch();
}

WAP to display all divisors of a given number.


#include<stdio.h>
#include<conio.h>
void main()
{
int no,i;
clrscr();
printf("Enter number: ");
scanf("%d",&no);
for(i=1;i<=no;i++)
{
if(no%i==0)
printf("%d\t",i);
}
getch();
}

WAP to display all possible combination of 1, 2 and 3.


#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k;
clrscr();
for(i=1;i<=3;i++)
{
By Prof. Manoj Dhande 7738339960
42
Shah and Anchor Kutchhi Engg College, Chembur C Programming

for(j=1;j<=3;j++)
{
for(k=1;k<=3;k++)
{
printf("%d%d%d",i,j,k);
printf("\n");
}
}
}
getch();
}

1. WAP to display all possible combination of 1, 2 and 3 without repeating character in


combination.
2. WAP to display all possible combination of A, B and C.
3. WAP to display all possible combination of A, B and C without repeating character in
combination.
4. WAP to display following patterns.
1 1 * **** * 1234 4321 1 ABCD A ABCDCBA
12 22 ** *** ** 123 321 121 ABC ABA ABCBA
123 333 *** ** **** 12 21 12321 AB ABCBA ABA
1234 4444 **** * ****** 1 1 1234321 A ABCDCBA A

/*program to print
1
12
123
1234 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
printf("enter no of rows:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
printf("%d",j);
printf("\n");
}
getch();
}

By Prof. Manoj Dhande 7738339960


43
Shah and Anchor Kutchhi Engg College, Chembur C Programming

/*program for 1
22
333
4444 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
clrscr();
printf("enter no of rows:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
printf("%d",i);
printf("\n");
}
getch();
}

/* program to display *
**
***
****
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
clrscr();
printf("enter no of rows:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
printf("*");
printf("\n");
}
getch();
}

/* program to display 4321


321
21
1 */
#include<stdio.h>
By Prof. Manoj Dhande 7738339960
44
Shah and Anchor Kutchhi Engg College, Chembur C Programming

#include<conio.h>
void main()
{
int i,j,n;
clrscr();
printf("enter no of rows:");
scanf("%d",&n);
for(i=n;i>=1;i--)
{
for(j=i;j>=1;j--)
printf("%d",j);
printf("\n");
}
getch();
}

/* program to display 1
121
12321
1234321
123454321 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,m,n;
clrscr();
printf("enter no of rows:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
printf(" ");
for(k=1;k<=i;k++)
printf("%d",k);
for(m=i-1;m>=1;m--)
printf("%d",m);
printf("\n");
}
getch();
}
/*program to display A
AB
ABC
ABCD */
#include<stdio.h>
#include<conio.h>
By Prof. Manoj Dhande 7738339960
45
Shah and Anchor Kutchhi Engg College, Chembur C Programming

void main()
{
int i,j,n;
char ch;
clrscr();
printf("enter no of rows:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
ch='A';
for(j=1;j<=i;j++)
printf("%c",ch++);
printf("\n");
}
getch();
}
/* program to display ABCDCBA
ABCBA
ABA
A */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,m,n;
char ch;
clrscr();
printf("enter no of rows:");
scanf("%d",&n);
for(i=n;i>=1;i--)
{
ch='A';
for(j=1;j<=n-i;j--)
printf(" ");
for(k=1;k<=i;k++)
printf("%c",ch++);
for(m=i-1;m>=1;m--)
printf("%c",ch-- );
printf("\n");
}
getch();
}

By Prof. Manoj Dhande 7738339960


46
Shah and Anchor Kutchhi Engg College, Chembur C Programming

3. Control Breaking Statements :


Loops execute certain set of statement repeatedly until the control variable fails to satisfy the test
condition. The number of times the loop is repeated is decided in advance and test condition is written
to achieve this. Sometimes, when executing a loop is becomes desirable to skip a part of the loop or to
leave as soon as certain condition occurs. Suppose we are searching for a name in 100 names. A
program loop will be written to get executed 100 times, but as soon as we find desired name, we want
the loop to get terminated.

3. a) Break Statement :
An early exit from loop can be accomplished using break statement. When break statement is
encountered inside a loop, the loop is immediately exited and entire program continues with statement
immediately following the loop. When the loops are nested, the break would only exit from the loop
containing it. That is, break will exit only a single loop.
The break statement can be used with the while loop, do-while loop and for loop. Consider a
while loop:
while (--------)
{
----------
-----------
if(condition)
break;
--------
exit from -------
loop }
--------

The use of break in do-while loop is shown in below.

do
{
----------
----------
if (condition )
break;
----------
exit from ---------
loop }
while (-------);
---------

By Prof. Manoj Dhande 7738339960


47
Shah and Anchor Kutchhi Engg College, Chembur C Programming

Problem Statements:
WAP to check prime property of a given number.
#include<stdio.h>
#include<conio.h>
void main()
{
int no,i,flag=0;
clrscr();
printf("enter any no:");
scanf("%d",&no);
for(i=2;i<no/2;i++)
{
if(no%i==0)
{
flag=1;
break;
}
}
if(flag==0)
printf("%d is a prime number");
else
printf("%d is not prime number");
getch();
}

WAP to find GCD and LCM of the two given numbers.


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,i,min;
clrscr();
printf("Enter two numbers:");
scanf("%d%d",&a,&b);
if(a<b)
min=a;
else
min=b;
for(i=min;i>=1;i--)
{
if(a%i==0 && b%i==0)
{
break;
}
}
printf("GCD= %d",i);
printf("\nLCM=%d",(a*b)/i);
By Prof. Manoj Dhande 7738339960
48
Shah and Anchor Kutchhi Engg College, Chembur C Programming

getch();
}

3. b) Continue statement :
Sometimes we want to skip statement inside the loop and want to take control to the beginning of
the loop. The continue statement allows us to do this.
When continue is the used inside any loop, control automatically passes to the beginning of the
loop. When we use continue within for loop, continue causes the conditional test and increment
portions of the loop to execute. When it is used in while and do-while loops program control passes to
the conditional tests as shown below:-

for (-----------) while (------------)


{ {
------------ ------------
if (----------) if (------------)
continue ; continue;
----------------
} }

do
{
-----------
if (---------)
continue;
-----------
} while (---------);

3.c) goto
A goto is unconditional branching statement of C. A goto statement can cause program control
end up anywhere in the program checking for any condition.
A goto requires a label in order to identify the place where the branch is to be made. A label is
placed immediately before the statement where the control is to be transferred. The general forms of
goto are as shown below.
The label can be anywhere in the program either before or after the goto statement.

goto label ; label : statement


--------- ---------
---------- ----------
label : statement goto label ;

Problem Statement:
WAP to find sum of digits, reducing it to one digit number.
By Prof. Manoj Dhande 7738339960
49
Shah and Anchor Kutchhi Engg College, Chembur C Programming

#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum,d;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
a:sum=0;
while(n!=0)
{
d=n%10;
sum=sum+d;
n=n/10;
}
if(sum>9)
{
n=sum;
goto a;
}
printf("sum=%d",sum);
getch();
}

WAP which will accept only positive number.


#include<stdio.h>
#include<conio.h>
void main()
{
int no;
a:clrscr();
printf("Enter number\n");
scanf("%d",&no);
if(no<0)
{
goto a;
}
printf("Number is=%d",no);
getch();
}

By Prof. Manoj Dhande 7738339960


50
Shah and Anchor Kutchhi Engg College, Chembur C Programming

FUNCTIONS
Functions:
May times we hire the services of other peoples in order to get the job done. Any complex job
cannot be performed by a single person. Consider a familiar example of marriage ceremony. This is
big event and many persons are involved in. The food contract is given to one, the other arrangement
are look after be other. We hire a hall for ceremony. For such event we need to make planning, we
need to divide job into small jobs and get it assigned to individuals. While attempting to solve complex
job by computer we find one program cannot handle all task by itself. It requires other subprograms to
get the task done. These subprograms are called as functions. Functions are building blocks of C
program.
What is a function?
A function is a self contained block of statement that performs a particular task. They may be
developed separately and tested. A name is given to each function and we can specify the method of
sending data to the function. The functions may be linked together.
In C functions can be classified into two categories.
i) Standard Library functions
ii) User defined functions
Standard Library functions are predefined functions. You can use these functions in your
program. When we use these function in program, we need to include corresponding header file (with
.h extension) in the program, in which the code for functions is defined.
User defined functions are developed by programmer. These are developed as per the need of
the programmer. The main( ) is an example of user defined function.
Advantage of functions:
Every C program can be through of as collection of functions. The program execution starts
from main() function. All of the code for program can not be incorporated into main() because it leads
to number of problems. The program may become too large and complex and hence debugging, testing
and maintenance becomes difficult. If the program is divided into functional parts, then each part may
be independently coded and later combined into single unit.
The advantages of using functions are:
i) Easy to write, correct small functions for small task.
ii) Easy to read, write and debug a function.
iii) The maintenance and modification of function is easier.
iv) The length of source program can be reduced by using functions at appropriate places.
v) A function once developed, may be used by many other programs so it avoids rewriting
of the same code again and again.

Standard Functions (Build-in Functions):


C language is having very rich library. Library consists of many header files. Each header file
contains many standard functions those programmer can use while writing program.
Example of header files:
math.h
Contain Functions required for mathematical operations like:
sqrt( ), abs( ), pow( ), ceil( ), floor( ), fabs() etc.
string.h
Contains functions required for string manipulation like:
strlen( ), strcpy( ), strcmp( ), strrev( ) etc.
By Prof. Manoj Dhande 7738339960
51
Shah and Anchor Kutchhi Engg College, Chembur C Programming

stdio.h
printf( ), scanf( ) etc.
conio.h
getch( ), clrscr( ) etc.

User defined Functions:


When standard function is not available in library of C then user can write his/her own function
as per his/her requirement, those functions are called user defined functions. For writing user
defined functions following things are required.
1. Function prototype
2. Function definition
3. Function call.

Function prototype:
In C all functions must be declared before they are used in program. This is achieved by
functions prototyping. The prototyping is a declaration that defines the arguments passed to the
function and the type of the value returned by the function. It has the form.
returntype function_ name (type arg1, type arg2,……..type argn);
Here returntype specifies type of value returned by function. function_name is any valid
variable name other than keyword. The arg1, arg2------ argn are n arguments. Before names of
argument the type of argument is mentioned. The use of argument names is optional, however writing
their type is mandatory. Function prototype appears before the function is called, normally function
prototypes are written before main function. The function prototype tells complier everything that it
needed to know about function. It tells name of the function, Number of arguments the function needs,
and the type of arguments.
For example, we may write function prototype as:
int factorial(int n);
int GCD(int, int);
Observe that function prototype ends with semicolon.
Defining a function:
A function definition describes how the function computes the value, it returns. The function
definition consists of a function header written as the same way as the function prototype, except that
the header does not have a semicolon at the end.
The function body consists of declaration and executable statements enclosed within the
braces. The function body is similar to that of main() part of program. When a function is called in
main ( ), the value of formal parameters are passed and the statements in body of function are
executed. The last statement in body is return statement. It consists of a keyword return followed by an
expression, it determine value return by function.
The general form of functions definition is:
returntype function_name (type arg1, -------,type argn)
{
local variable declarations ;
executable statement1;
executable statement2;
------------
By Prof. Manoj Dhande 7738339960
52
Shah and Anchor Kutchhi Engg College, Chembur C Programming

return (expression);
}
The variables that are declared within a function are called local variables. They are valid only
within function and they are destroyed on exit from function. A function’s code is private to the
function and can not be accessed by any statement except through a call to function. i..e. you can not
use goto to jump into the middle of the function.
Function Call:
A function can be called in main() by writing the name of the function.
For example, we may write statement
Bill = total _cost (number , price );

void main( )
{
int sqr (int x); function prototype
int m,t=10;
m=sqr(t); function sqr is called (call by value)
printf(“%d”,m)
}
int sqr(int x)
{
x=x*x;
return (x);
}
The return statement:
When a function is called, the control of execution gets transferred to function. There are two
ways that a function terminates execution and returns to the caller. The first occurs when the last
statement in the function has executed i.e. when closing brace } is encountered. This is the default
method of terminating of function.
In second method, we can use return statement to stop execution. A return statement may send
value to the calling function. A return statement can return only one value per call at the most.
The return statement can have the several forms.
For example we may have a plane return as:
return;
The plane return does not return any value but it only returns the control of execution to the
calling function.
return(expression);
This form, returns value of expression. Also, the return need not always be present at the end of
called function.
Program to calculate factorial of a given number using function
#include <stdio.h>

int main()
{
int factorial(int);
int n,f;

By Prof. Manoj Dhande 7738339960


53
Shah and Anchor Kutchhi Engg College, Chembur C Programming

printf("Enter Number: ");


scanf("%d",&n);
f=factorial(n);
printf("Factorial =%d",f);
return 0;
}
int factorial(int x)
{
int i,ff=1;
for(i=1;i<=x;i++)
{
ff=ff*i;
}
return ff;
}

#include <stdio.h>

int main()
{
int factorial(int);
float bio;
int n,r;
printf("Enter value of n and r: ");
scanf("%d%d",&n,&r);
bio=(float)factorial(n)/(factorial(r)*factorial(n-r));
printf("Bionomial Co:%f",bio);
return 0;
}
int factorial(int n)
{
int f=1,i;
for(i=1;i<=n;i++)
f=f*i;
return f;
}
int main()
{
int GCD(int,int);
int a,b,g;
printf("Enter two numbers:");
scanf("%d%d",&a,&b);
g=GCD(a,b);
printf("GCD=%d",g);
return 0;
}
By Prof. Manoj Dhande 7738339960
54
Shah and Anchor Kutchhi Engg College, Chembur C Programming

int GCD(int a, int b)


{
int r;
while(b!=0)
{
r=a%b;
a=b;
b=r;
}
return a;
}
//Program to find GCD and LCM using functions

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

int GCD(int , int ); // Function declaration


int LCM(int , int ); // Function declaration

void main()
{
int a,b,gcd,lcm;
clrscr();
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);

gcd=GCD(a,b); //Function Call

lcm=LCM(a,b); // Function call

printf("GCD=%d LCM=%d",gcd,lcm);
getch();
}

int GCD(int a, int b) // GCD Function Definition


{
while(a!=b)
{
if(a>b)
a=a-b;
else
b=b-a;
}
return a; //Return statement
}

int LCM(int a, int b) // LCM Function Definition


By Prof. Manoj Dhande 7738339960
55
Shah and Anchor Kutchhi Engg College, Chembur C Programming

{
return(a*b/GCD(a,b));
}
#include <stdio.h>

int main()
{
int n;
void armstrong(int);
printf("Enter Numer: ");
scanf("%d",&n);
armstrong(n);
return 0;
}
void armstrong(int n)
{
int d,sum=0,no;
no=n;
while(n!=0)
{
d=n%10;
sum=sum+d*d*d;
n=n/10;
}
if(sum==no)
printf("Numer is Armstrong");
else
printf("Number is not Armstrong");
}
#include <stdio.h>

int main()
{
int n;
void armstrong(int);
printf("Enter Numer: ");
scanf("%d",&n);
armstrong(n);
return 0;
}
void armstrong(int n)
{
int d,sum=0,no;
no=n;
while(n!=0)
{
d=n%10;
By Prof. Manoj Dhande 7738339960
56
Shah and Anchor Kutchhi Engg College, Chembur C Programming

sum=sum+d*d*d;
n=n/10;
}
if(sum==no)
printf("Number is Armstrong");
else
printf("Number is not Armstrong");
}
#include <stdio.h>

int main()
{
int a[50],n,s,i;
int addition(int a[],int);
void accept_matrix(int a[],int);
void display_matrix(int a[],int);
printf("Enter number of elements:");
scanf("%d",&n);
accept_matrix(a,n);
display_matrix(a,n);
s=addition(a,n);
printf("Sum of elements:%d ",s);
return 0;
}
void accept_matrix(int a[],int n)
{
int i;
printf("Enter Elelments: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}
void display_matrix(int a[],int n)
{
int i;
printf("Array: ");
for(i=0;i<n;i++)
printf("%d ",a[i]);
}
int addition(int a[],int n)
{
int i,sum=0;
for(i=0;i<n;i++)
sum=sum+a[i];
return sum;
}
Recursion:

By Prof. Manoj Dhande 7738339960


57
Shah and Anchor Kutchhi Engg College, Chembur C Programming

When a function calls itself directly or indirectly is called recursion. Generally a function calls
another function in that case control goes to a function executes it and comes back. When a function
calls itself then control goes to same function and executes it again.
In recursion a function can starts with a new value every time. It is very compact and powerful.
It must be conditional otherwise it may enter into an infinite loop.
// Program to calculate factorial of a given number using recursive function

#include<stdio.h>
#include<conio.h>
void main()
{
int factorial(int);
int n,f;
clrscr();
printf("enter no:");
scanf("%d",&n);
f=factorial(n);
printf("result=%d",f);
getch();
}
int factorial(int n)
{
if(n==0)
return(1);
else
return(n*factorial(n-1));
}
// Program to find GCD using recursion

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

int GCD(int , int );

void main()
{
int a,b,gcd,lcm,prod;
clrscr();

//Input
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);

gcd=GCD(a,b); //Function Call

lcm=(a*b)/gcd;

By Prof. Manoj Dhande 7738339960


58
Shah and Anchor Kutchhi Engg College, Chembur C Programming

printf("GCD=%d LCM=%d",gcd,lcm);
getch();
}
int GCD(int a, int b)
{
if (b==0)
return a;
else
return GCD(b,a%b);
}
//Program to find GCD of two numbers using Euclid’s Algorithm
#include<stdio.h>
#include<conio.h>
void main()
{
int gcd(int,int);
int p,q,g;
clrscr();
printf("enter p & q:");
scanf("%d%d",&p,&q);
g=gcd(p,q);
printf("result=%d",g);
getch();
}
int gcd(int p,int q)
{
if(q==0)
return(p);
else if(q>p)
gcd(q,p);
else
gcd(q,p%q);
}
// Program to find x to the power n using recursive function
#include <stdio.h>
#include <conio.h>
int power(int , int );
void main()
{
int n;
clrscr();
printf("Enter the value of n\n");
scanf("%d",&n);
y=power(x,n); //Function Call
printf("%d raise to %d =%d",x,n,y);
getch();
}
By Prof. Manoj Dhande 7738339960
59
Shah and Anchor Kutchhi Engg College, Chembur C Programming

int power(int x, int n) // Function header


{
if (n==0)
return 1;
else
return x*power(x,n-1);
}
//Program to implement Ackerman’s recursive algorithm
#include<stdio.h>
#include<conio.h>
int ack(int,int);
void main()
{
int m,n,a;
clrscr();
printf("enter m & n:");
scanf("%d%d",&m,&n);
a= ack(m,n);
printf("result=%d",a);
getch();
}
int ack(int m, int n)
{
if (m==0)
return (n+1);
else if (n==0 && m>0)
return ack(m-1,1);
else
return ack(m-1,ack(m,n-1));
}
Storage Classes:
The syntax for declaration of variable is
storage_class datatype variable_list;
In C, there are four storage classes.
Storage Class Keyword
Automatic Storage class auto
Register Storage class register
Static Storage class static
External Storage class extern
For example, variables can be declared as follows:
auto int a,b;
Here variables a and b are declared of type integer and with storage class Automatic using keyword
auto.
Storage class gives four different information about variable.
1) Location: Which memory will be allocated Main memory Or CPU register?
2) Default value: What will be default value of variable?

By Prof. Manoj Dhande 7738339960


60
Shah and Anchor Kutchhi Engg College, Chembur C Programming

3) Scope/ Visibility: Where variable will be accessible/visible?


4) Lifetime: When memory will be allocated and destroyed to the variable?

Auto register Static extern


Location Main Memory CPU Register Main Memory Main Memory
Default value Garbage Garbage Zero Zero
Scope/Visibility Local to the block Local to the block Local to the block Global
Life-Time Till the execution Till the execution Till the execution of Till the execution
of block/function. of block/function. program. Value of of program.
variable persists between
different function call.

Automatic variables:
Automatic variables are declared inside a function in which they are to be utilized. They are
created when a function is called and destroyed automatically when the function is exited. Hence
sometimes they are called automatically variables.
A variable declared inside a function without a storage class specification is by default,
automatic variable. We may declare and use the same variable name in different functions of same
program. For example,
void main ( )
{
void display (int i);
int i =20;
display (i);
}
void display (int j)
{
int k=35;
printf(“%d”,j);
printf(“%d”,k);
}
In this example, the presence of i is known to function main ( ) and not to any other function.
Similarly the variable k is local to function display ( ).
The scope of automatic variable is local to the function in which it is defined.
Register variables:
We can tell the complier that a variable should be kept in CPU registers, instead of keeping in
main memory. The register access is must faster than a main memory access. The variable or objects
which are frequently used are kept in register which leads to faster execution of program. This is done
as follow
register int count;
Character and integer can be stored in registers. Large objects such as arrays cannot be stored
in registers.
You can store any number of variables in registers. But only those are stored, which are
frequently referenced. If many of the variables are declared as register variables, the complier will
automatically transform register variable into non register variables, when the limit is reached. The
limit depends on execution environment.

By Prof. Manoj Dhande 7738339960


61
Shah and Anchor Kutchhi Engg College, Chembur C Programming

For example, suppose we are writing program for sum of m natural numbers. In this
program there are certain variables which are referenced more and hence they can be declared as
register variable as shown below.

int sum (register int m)


{
register int i;
register result =0;
for (i=1; i<=m; i++)
result += i;
return (result);
}
Static variables:
The value of static variables persists between function call until the end of the program. A
variable can be declared static using keyword static.
When you apply the static modifier to a local variable, the complier creates a permanent
storage for it, as it creates for global variable. A static variable is initialized only once with zero, when
the program is complied. It is never initialized again.
For example, consider the program:
int stat ( );
void main ( )
{
int i;
for (i=1; i<=3; i++)
stat ( );
}
int stat( )
{
static int x =0;
x = x + 10;
printf(“x=%d\n”,x);
}
In above program during first call to stat( ), x is increment to 1. Because x is static this value
persists and therefore, the next call adds another 1 to x giving it a value 2. The value of become 3
when third call is made.
The output of program is:
x=1
x=2
x=3
If we declare x as automatic variable in place of static, then the output would have been:
x=1
x=1
x=1

External variables:

By Prof. Manoj Dhande 7738339960


62
Shah and Anchor Kutchhi Engg College, Chembur C Programming

Variables that are active and alive throughout the entire program are called as external
variables or global variables. These variables can be accessed by any function in the program.
In program you can declared a global variable outside all the functions and before main( ).

For example,
int length; global declaration
void main ( )
{
extern int length; use of extern declaration
------------
------------
}

By Prof. Manoj Dhande 7738339960


63
Shah and Anchor Kutchhi Engg College, Chembur C Programming

ARRAYS AND STRINGS


Arrays:
A C program consists of different variables. If the program is large then keeping track of large
set of variables is difficult. Suppose we are writing program to arrange percentage marks scored by
100 students in a class. We want to arrange marks in descending order. In such a case there are two
options to store marks in memory.
i) Construct 100 separate variables to store percentage marks obtained by 100 different students.
That is, each variable will contain one student marks.
ii) Construct one variable capable of storing all hundred values.
The second alternative is better. The reason for this is that it is easier to handle one variable
rather than 100 variables. The C, all arrays are stored in contiguous memory location. The lowest
address corresponding to first element and the highest address to the last elements. Array can be of any
variable type. That is, we may have array of integers or floats or characters. Even we may have an
array of structure or user defined data types.
One dimensional array:
A list of items can be given one variable name using only one subscript and such a variable is
called a single subscripted variable or a one dimensional array.
Like any other variable, arrays must be declared before they are used. The general form of
array declaration is:
datatype variable _ name [size];
Here datatype is the type of each element in the array. The size defines how many element the
array will hold. The declaration of array causes complier to allocate space for them in memory.
For example, to declare a 100 element array called percent _marks of type float, we write
float percent_marks [100];
An element is assessed by indexing the array name. This is done by placing the index of the element
within square brackets after the name of the array.
For example,
percent_marks [3] = 58.89;
Assigns element number 3 in percent _ marks the value 58.89.
In C, all arrays have 0 as the index of their first elements. Therefore when we write,
char x [10];
We are declaring a character array that has 10 elements, x [0] through x [9].
Entering data into array:
Once the array is declared, we can enter data into array by forming a loop. The number of time
loop will be executed depends on number of elements in the array. We can make use of loop control
statement such as for, while, do- while for forming a loop.
For example,
int x [100];
for (i=0; i<100; i++)
{
Scanf(“%d”, &x[i]);
}
Here x is an array of type int. The number of elements of x is 100. We are using for loop to read
100 values. The initial value of i is 0. We read first value from keyboard and it is stored as x [0]. This
is first element of array. The loop will be executed 100 times to read 100 values. The last element of
array is x [99].
Reading data from an array:
By Prof. Manoj Dhande 7738339960
64
Shah and Anchor Kutchhi Engg College, Chembur C Programming

In order to read data elements of an array, again, we need to form a loop. The number of times
the loop is executed access to it.
For example, we read the array of integer x [100] and find the average.
int sum= 0;
for (i=0; i<100; i++)
sum =sum + x [i];
avg = sum /100;
printf(“%d”, avg);
Here initial value of sum is 0. The initial value of i is 0. The first element x [0] is read and is
added to sum thereby forming the new sum. This process continues till we add all 100 elements.
Finally we compute average and display it.

Array initialization:
So far, we have seen that the values in array can be stored during program execution. C allows
the initialization of array at the time of their declaration. The general form of array initialization is
datatype array _ name [size] ={ list of values};
The values in the list of values are separated by comma whose type is compatible with data type
mentioned. The first value is placed in first position of array, the second value in second position, and
so on. Note that a semicolon follows after }.
For example, a 10- element array is initialized with the numbers 1 through 10;
int x[10] = {1, 2 3, 4, 5, 6, 7, 8, 9, 10};
This means x [0] will have value 1 and x [9] will have value 10.
In array initialization, if the size of array is not specified, C complier automatically creates an
array big enough to hold all initial values.
For example, int n[ ] = {2, 4, 6, 8};
The advantage of using unsized array is that you can change length without mentioning it.

Representation of array in memory:


The amount of storage space required to hold an array is directly related to its type and size. For
a single dimensional array, the total size in bytes is computed as shown here.
total bytes= size of (base type ) x size of arry

C has no bound checking on arrays. You could overwrite either end of array. It is your job to
provide bounds checking whenever needed.
Array elements are store in contiguous memory locations in index order.
For an integer array
int x [8];
16 bytes of memory gets reserved for 8 integers, as every integer is 2-byte long. If the array not
initialized it may contain garbage values. This is because the storage class of array is assumed as auto.
If the storage class is declared as static then all the array elements would have a default initial value as
zero.
Suppose first element is stored at an address 1000 then the last 8 th elements will be stored at
address 1014. The total bytes required are 16.

By Prof. Manoj Dhande 7738339960


65
Shah and Anchor Kutchhi Engg College, Chembur C Programming

1st element 1000

2nd element 1002

.
.
.
.
8th element 1014

Consider another declaration,


char a [7];
char elements requires one byte of storage. Their memory representation is shown below.

1st character 1000


2nd character 1001
.
.
.
.
th
7 character 1006

Problem Statements:
1) WAP to find sum of all elements of one dimensional array.
#include <stdio.h>

void main()
{
int a[50],n,i,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("Enter No: ");
scanf("%d",&a[i]);
sum=sum+a[i];
}
printf("Sum of Elements: %d",sum);
getch();
}

2) WAP to find sum of even and odd elements present in an array of n elements.
#include <stdio.h>

void main()
By Prof. Manoj Dhande 7738339960
66
Shah and Anchor Kutchhi Engg College, Chembur C Programming

{
int a[50],n,i,sumo=0,sume=0;
printf("Enter number of elements: ");
scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("Enter No: ");
scanf("%d",&a[i]);
if(a[i]%2==0)
sume=sume+a[i];
else
sumo=sumo+a[i];
}
printf("Sum of odd Elements: %d",sumo);
printf("\nSum of Even Elements: %d",sume);
getch();
}
3) WAP to find largest element of one dimensional array.
#include <stdio.h>

void main()
{
int a[50],n,i,max;
printf("Enter number of elements: ");
scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("Enter No: ");
scanf("%d",&a[i]);
}
max=a[0];
for(i=1;i<n;i++)
{
if(a[i]>max)
max=a[i];
}
printf("Largest Elements: %d",max);
getch();
}
WAP to find largest and second largest element of an array.
//Program to find largest and second largest element in an array
#include<stdio.h>
#include<conio.h>
void main()
{
By Prof. Manoj Dhande 7738339960
67
Shah and Anchor Kutchhi Engg College, Chembur C Programming

int a[50],n,i,max,smax=-1;
clrscr();
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter the elements of array:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
max=a[0];
for(i=1;i<n;i++)
{
if(max<a[i])
{
max=a[i];
}
}
for(i=0;i<n;i++)
{
if(a[i]>smax && max>a[i])
{
smax=a[i];
}
}
printf("Largest no is %d\nSecond largest no is %d",max,smax);
getch();
}

WAP to search given element in an array.


// Program to search elements in an array
#include<stdio.h>
#include<conio.h>
void main()
{
int flag=0,a[30],no,i,n;
clrscr();
printf("Enter number of elements:\n");
scanf("%d",&n);
printf("Enter elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter element to search\n");
scanf("%d",&no);
for(i=0;i<n;i++)
{
if(n==a[i])
{
By Prof. Manoj Dhande 7738339960
68
Shah and Anchor Kutchhi Engg College, Chembur C Programming

printf("\n%d is present",a[i]);
flag=0;
}
}
if(flag==0)
printf("%d is not present");
getch();
}
WAP to search and display position of agiven element in an array.
#include <stdio.h>

int main()
{
int n,i,flag=0,x;
int a[50];
printf("Enter no of Elements: ");
scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("Enter Number:");
scanf("%d",&a[i]);
}

printf("Enter element to search: ");


scanf("%d",&x);

for(i=0;i<n;i++)
{
if(a[i]==x)
{
flag=1;
printf("\nElement %d is present at: %d",x,i);
}
}
if(flag==0)
printf("Element : %d is Not present ",x);
return 0;
}

WAP to accept and sort ‘n’ elements of an array in ascending order.


#include<stdio.h>
#include<stdio.h>
void main()
{
int n,a[50],temp,i,j;
clrscr();
By Prof. Manoj Dhande 7738339960
69
Shah and Anchor Kutchhi Engg College, Chembur C Programming

printf("Enter no. of elements:\n");


scanf("%d",&n);
printf("Enter elements:\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("sorted array=\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
getch();
}

WAP to find binary equivalent of the given decimal number.


WAP to find octal equivalent of the given decimal number.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50],i=0,n,j;
clrscr();
printf("Enter the decimal number:");
scanf("%d",&n);
while(n!=0)
{
a[i]=n%8;
n=n/8;
i++;
}
for(j=i-1;j>=0;j--)
{
printf("%d",a[j]);
By Prof. Manoj Dhande 7738339960
70
Shah and Anchor Kutchhi Engg College, Chembur C Programming

}
getch();
}
WAP to find hexadecimal equivalent of decimal number
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50],i=0,n,j;
clrscr();
printf("Enter the no");
scanf("%d",&n);
while(n!=0)
{
a[i]=n%16;
i++;
n=n/16;
}
for(j=i-1;j>=0;j--)
{
if(a[j]<=9)
printf("%d",a[j]);
else
printf("%c",a[j]+55);
}
getch();
}

WAP to calculate standard deviation of n items.


// Program to calculate mean, variance and standard deviation
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int x[20],sum=0,sv=0;
float mean,v,n;
clrscr();
printf("Enter number of elements:");
scanf(“%d”,n);
printf("Enter Elements:");
for(int i=0;i<n;i++)
{
printf("a[%d]",i)";
scanf(“%d”,&x[i]);
sum=sum+x[i];
By Prof. Manoj Dhande 7738339960
71
Shah and Anchor Kutchhi Engg College, Chembur C Programming

}
mean=float(sum/n);
for(i=0;i<n;i++)
{
sv=sv+((x[i]-mean)*(x[i]-mean));
}
v=float(sv/n);
printf("Mean=%f",mean);
printf("\nVariance=%f",v);
printf("\nStandard deviation:",sqrt(v));
getch();
}

WAP for fitting a straight line y=mx+c


#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,x[10],y[10],sumx=0,sumy=0;
float sumxy=0,sumx2=0;
float m,c;
clrscr();
printf("Enter number of points\n");
scanf("%d",&n);
printf("Enter coordinates\n");
for(i=0;i<n;i++)
{
printf("Enter x coordinate:\n");
scanf("%d",&x[i]);
printf("Enter y coordinate\n");
scanf("%d",&y[i]);
sumx=sumx+x[i];
sumy=sumy+y[i];
sumxy=sumxy+(x[i]*y[i]);
sumx2=sumx2+(x[i]*x[i]);
}
m=((n*sumxy)-(sumx*sumy))/((n*sumx2)-(sumx*sumx));
c=(1/n)*(sumy-(m*sumx));
printf("\nline y=%fx+%f",m,c);
getch();
}

Arrays as function arguments:


Array element can be passed to a function by calling the function by value or by reference. In
call by value, we pass values of the array elements to the function, whereas in call by reference, we
pass address of array elements to the function.
For example,
By Prof. Manoj Dhande 7738339960
72
Shah and Anchor Kutchhi Engg College, Chembur C Programming

void main()
{……….
int x[ ] = {1, 2, 3, 4, 5};
for (j=0; j<=4; j++)
display (x[j]);
-------------------
}
void display(int m)
{
printf(“%d”,m);
}
In above example an integer arrays x consists of 5 elements. The elements of an array are used
as arguments for a function display ( ). The each individual element of array is passed to function
where it is displayed. This is example of call by value.
The call by reference will be discussed later after discussion of pointers.
In C, you can not pass an entire array as an argument to the function. You can however, pass to
the function a pointer to an array by specifying array’s name without an index.
For example, the following fragment passes array x to func1 ( ).
void main ( )
{
int x [10];
-------------
func1(x);
-----------
}
Observe that the name of array x without index is used as actual argument. If a function
receives a one dimensional array, you may declare its formal parameter as:
void finct1(int m[10])
{
--------------------
--------------------
}
Or
void funct1 (int m[ ])
{
-------------------
------------------
}

// Program to sort elements of an array in ascending order using function

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

void sort(int a[],int n);


void main()
{
By Prof. Manoj Dhande 7738339960
73
Shah and Anchor Kutchhi Engg College, Chembur C Programming

int n,i,j,a[10];
clrscr();
printf("Enter n\n");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

sort(a,n);

printf("Sorted elements: ");


for(i=0;i<n;i++)
printf("%d\n",a[i]);
getch();
}
void sort(int a[],int n)
{
int temp,i,j;
for(i=0;i<n-1;i++)
for(j=0;j<n-(i+1);j++)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
// Program to accept n elements of an array and to calculate sum of n elements using function
#include<stdio.h>
#include<conio.h>
int add(int [],int);
void main()
{
int s,a[10],n,i;
clrscr();
printf("Enter no.of elements\n");
scanf("%d",&n);
printf("Enter elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
s=add(a,n);
printf("sum=%d",s);
getch();
}
int add(int a[],int n)
By Prof. Manoj Dhande 7738339960
74
Shah and Anchor Kutchhi Engg College, Chembur C Programming

{
int sum=0,i;
for(i=0;i<n;i++)
{
sum=sum+a[i];
}
return(sum);
}

Two dimensional arrays:


Suppose we have been given a table of values. It consists of rows and columns. We can think
of this table as a matrix. The particular value in this matrix can be represented by using two subscripts
such as Aij where A is the name of matrix and Aij refer to value in ith row and jth column.
C support multidimensional array. The simplest form of multidimensional arrays is two
dimensional arrays. The general form of declaration of two dimensional arrays is:
datatype array-name [row size] [column size];
For example, to declare a two dimensional array A of size 10, 20 we would write,
int A[10] [20];
Observe that we use separate set of brackets for each dimension.
To load data into two dimensional arrays we need to form loops, one for rows and other for
columns. The data can be entered row wise or column wise. Similarly to read array elements of two
dimensional arrays we need two loops.
We can write code for reading the table of numbers.
num[i] [j]
0 1 2 3
0 55 25 11 10
1 78 26 9 7
2 12 15 16 26
void main ( )
{
int i, j, num [3] [4];
// to read array element
for (i=0; i<3;i++)
for (j=0; j<4;j++)
scanf(“%d”,&num [i] [j]);
// to display array elements
for (i=0; i<3;i++)
for (j=0; j<4;j++)
printf(“%d”,num[i] [j]);
}
Observe that subscript i is used for row number and j for column number. Here data is read
row-wise and also displayed row-wise.

Memory representation of two dimensional arrays:


By Prof. Manoj Dhande 7738339960
75
Shah and Anchor Kutchhi Engg College, Chembur C Programming

In case of two dimensional arrays, the number of bytes of memory required can be calculated
by using formula.
Bytes = size of 1st index * size of 2st index *size of base type

Memory does not have row and column. Therefore the two dimensional array elements are
also stored in one continues chain as shown below.

num [0] [0] num [0] [1] num [0] [2] num [0] [3] num [1] [0]..............

55 25 11 10 78 ……..
5000 5002 5004 5006 5008……………...

Array initialization
A two dimensional array can be initialized by declaration.
int num [3] [4] = {55, 25, 11, 10, 78, 26, 9, 7, 12, 15, 16, 26};
Observe hat first dimension is optional while need to mention second dimension.
int num [ ] [4] = {55, 25, 11, 10, 78, 26, 9, 7, 12, 15, 16, 26}; is permitted but
int num [2] [ ] = {--------}; is not allowed.
It is necessary to mention right most dimension so that complier will know the length of each row.

Problem Statements:
1. WAP to find sum of elements of an array of size m*n.
#include <stdio.h>
int main()
{
int a[10][10],r,c,s,i,j;
int addition(int a[10][10],int,int);
printf("Enter number of rows and col of matrix:");
scanf("%d%d",&r,&c);
printf("Enter Elements: ");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
s=addition(a,r,c);
printf("Sum of Elements:%d",s);
return 0;
}
int addition(int a[10][10],int r,int c)
{
int i,j,sum=0;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
By Prof. Manoj Dhande 7738339960
76
Shah and Anchor Kutchhi Engg College, Chembur C Programming

{
sum=sum+a[i][j];
}
}
return sum;
}
2. WAP to find tract of square matrix.
3. WAP to calculate sum of elements present on, above and below diagonal of square matrix.
WAP to check whether square matrix is symmetric or not.

// Program to check whether 2-D matrix is symmetric or not

#include<stdio.h>
#include<conio.h>
#define size 3
void main()
{
int a[size][size],r,c,flag=1;
clrscr();
printf("Enter the Elements:\n");
for(r=0;r<size;r++)
{
for(c=0;c<size;c++)
{
scanf("%d",&a[r][c]);
}
}
for(r=0;r<size;r++)
{
for(c=r+1;c<size;c++)
{
if(a[r][c]!=a[c][r])
{
flag=0;
break;
}
}
}
if(flag==1)
printf("Matrix is Symmetric");
else
printf("Matrix is Not Symmetric");
getch();
}

WAP to find transpose of a square matrix using only one matrix.


// Program to find and display transpose of a square matrix using only one matrix
By Prof. Manoj Dhande 7738339960
77
Shah and Anchor Kutchhi Engg College, Chembur C Programming

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

void main()
{
int a[10][10],r,c,s,temp;
clrscr();
printf("Enter size: ");
scanf("%d",&s);
printf("Enter the Elements:\n");
for(r=0;r<s;r++)
{
for(c=0;c<s;c++)
{
scanf("%d",&a[r][c]);
}
}
for(r=0;r<s;r++)
{
for(c=0;c<s;c++)
{
if(r<c)
{
temp=a[r][c];
a[r][c]=a[c][r];
a[c][r]=temp;
}
}
}
printf("Transpose Matrix:\n");
for(r=0;r<s;r++)
{
for(c=0;c<s;c++)
printf("%d\t",a[r][c]);
printf("\n");
}
getch();
}
WAP to find transpose of a square matrix using two matrices.
WAP to find multiplication on two M*N matrices.
// Program to calculate Multiplication of two matrices
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,r1,r2,c1,c2;
By Prof. Manoj Dhande 7738339960
78
Shah and Anchor Kutchhi Engg College, Chembur C Programming

clrscr();
printf("Matrix:1:");
printf("\nEnter No of Rows & Columns: ");
scanf("%d %d",&r1,&c1);
printf("Matrix:2:");
printf("\nEnter No of Rows & columns: ");
scanf("%d %d",&r2,&c2);
if(c1!=r2)
printf("Multiplication Not Possible....");
else
{
printf("Enter the 1st matrix :\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
}

printf("Enter the 2nd matrix :\n");


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++)
{
c[i][j]=0;
for(k=0;k<c1;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
printf("Multiplication:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
printf("%d\t",c[i][j]);
printf("\n");
}
}
getch();
}
Passing 2D array to function:
// Program to find sum of all elements of the matrix except diagonal elements using function
#include<stdio.h>
#include<conio.h>
By Prof. Manoj Dhande 7738339960
79
Shah and Anchor Kutchhi Engg College, Chembur C Programming

void main()
{
int sum_of_elements(int [][10],int);
int a[10][10],n,i,j,s;
clrscr();
printf("Enter the size of matrix: ");
scanf("%d",&n);
printf("Enter the elements of the matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
s=sum_of_elements(a,n);
printf("Sum of elements of matrix except diagonal elements=%d\n",s);
getch();
}
int sum_of_elements(int a[][10],int n)
{
int i,j,sum=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i!=j)
sum=sum+a[i][j];
}
}
return (sum);
}
// Program for finding transpose of a matrix using only one matrix using functions
#include<stdio.h>
#include<conio.h>
void main()
{
void transpose(int [][10],int); //Local prototype
int a[10][10],n,i,j;
clrscr();
printf("Enter the size of matrix\n");
scanf("%d",&n);
printf("Enter the elements of the matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
By Prof. Manoj Dhande 7738339960
80
Shah and Anchor Kutchhi Engg College, Chembur C Programming

}
transpose(a,n);
printf("Transpose of the matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
getch();
}
void transpose(int a[][10],int n)
{
int i,j,temp;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i<j)
{
temp=a[i][j];
a[i][j]=a[j][i];
a[j][i]=temp;
}
}
}
}

Strings:
A string is one dimensional array of characters. The most common use of one dimensional
array is a character string. The string consists of null (‘\0’) as the last character. For a string of 10
characters we need to declare size of array 11 as:
char str [11];
This makes provision for the null at the end of the string.
You can assign a value of string. It is called as string constant. A string constant is enclosed in
double quotes.
For example,
char name [ ] =”MADAM”;
Observe that you need not add null at the end of the string constant. The C complier does this
for you automatically.
You can read a string from keyboard by using scanf().
For example
char name [15];
scanf(“%s”,name);

By Prof. Manoj Dhande 7738339960


81
Shah and Anchor Kutchhi Engg College, Chembur C Programming

Observe that you cannot incorporate white space into the value of the string. It will cause
termination of string.
C complier has a large set of useful string handling library functions. Out of these, strlen ( ),
strcpy ( ), strcat ( ) and strcmp ( ) are more commonly used. These functions use the standard header
file string.h. when we use these functions, we need to include this file in the program. Let’s discuss
how to use these functions.

strlen( ):
This function counts numbers of character in the string. Consider the program:
void main ( )
{
char arr[ ] = “Heloow”;
int len1, len2;
len1= strlen(arr);
len2= strlen(“Hi”);
printf(“%d %d”, len1,len2);
}
The output would be 6 2
While calculating the length, the function does not consider the last null character.
strcpy( ):
The function copies the contents of one string into another. The base address of the source
and target strings should be supplied to this function.

For example consider the program,


void main ( )
{
char source [ ] = “MADAM”;
char target [20];
strcpy (target, source);
printf(“%s %s”,source, target);
}
The output is MADAM MADAM
The strcpy() goes on coping the character of source string into target till it does not encounter
the null character(‘\0’) of the source string.

strcat( ):
This function concatenates the source string at the end of the target string.
For example consider the program,
void main ( )
{
char source[ ] = “Chavan“;
char target [ ] = “Ashok“;
strcat (target, source);
printf(“%s”,target);
}
The output is
Ashok Chavan
By Prof. Manoj Dhande 7738339960
82
Shah and Anchor Kutchhi Engg College, Chembur C Programming

strcmp( ):
This function compares two strings to find out whether they are same or different. The two
strings are compared character by character until there is mismatch or end of one of the string is
reached, whichever occurs first. If the two string are identical, strcmp( ) returns value zero, otherwise it
will return a numeric difference between ASCII values the non matching characters. Consider the
program.
void main( )
{
char s1[ ] = “Narendra”;
char s2[ ] = “Virendra”;
int i, j,
i= strcmp(s1, “Narendra”);
j= strcmp (s1, s2);
printf(“%d %d”, i, j);
}
The output is
0 -8
Observe that the difference between ASCII values of N and V is -8.
//Program to demonstrate the use of format specifiers
#include<stdio.h>
#include<conio.h>
void main()
{
char country[]="United Kingdom";
int a=1234;
float x;

clrscr();
scanf("%f",&x);
printf("%10.2f\n",x);

printf("%s\n",country);
printf("%40.6s\n",country);
printf("%-40.6s\n",country);
printf("%.3s\n",country);
printf("%15.0s\n",country);

printf("%35d\n",a);
printf("%37d\n",a);

getch();
}
//Output

12.34

By Prof. Manoj Dhande 7738339960


83
Shah and Anchor Kutchhi Engg College, Chembur C Programming

12.34

United Kingdom

United

United

Uni

1234
1234
Program to accept a line of text one char at a time

#include<stdio.h>
#include<conio.h>
void main()
{
char ch,line[80];
int c=0;
clrscr();
printf("Enter a line\n");
do
{
ch=getchar();
line[c]=ch;
c++;
}while(ch!='\n');
c=c-1;
line[c]='\0';
printf("String = %s",line);
getch();
}
Program to count the no of vowels and consonants in given string

#include<stdio.h>
#include<conio.h>
void main()
{
char str[80];
int vow=0,cons=0;
int c;
clrscr();
printf("Enter a string\n");
gets(str);
for(c=0;str[c]!='\0';c++)
{
By Prof. Manoj Dhande 7738339960
84
Shah and Anchor Kutchhi Engg College, Chembur C Programming

if(str[c]=='a' || str[c]=='A' || str[c]=='e' ||str[c]=='E'||str[c]=='i' ||str[c]=='I' || str[c]=='o'


||str[c]=='O'|| str[c]=='u' ||str[c]=='U')
{
vow++;
}
else
cons++;
}
printf("\nvowels = %d \t Consonants= %d",vow,cons);
getch();
}

Program to display different combination of a, b and c without duplicate character

#include<stdio.h>
#include<conio.h>
void main()
{
char i,j,k;
clrscr();
printf("Different Combinations Are:\n");
for(i='A';i<='C';i++)
{
for(j='A';j<='C';j++)
{
for(k='A';k<='C';k++)
{
if(i==j || j==k || i==k)
continue;
else
printf("%c %c %c\n",i,j,k);
}
}
}
getch();
}

Program to copy the string from one character array to another character array

#include<stdio.h>
#include<conio.h>
void main()
{
char string1[80],string2[80];
int c;
clrscr();
printf("Enter a string\n");
By Prof. Manoj Dhande 7738339960
85
Shah and Anchor Kutchhi Engg College, Chembur C Programming

gets(string1);
for(c=0;string1[c]!='\0';c++)
{
string2[c]=string1[c];
}
string2[c]='\0';
printf("\n%d characters copied in new string : %s",c,string2);
getch();
}
Program for concatenation of first, middle and last name

#include<stdio.h>
#include<conio.h>
void main()
{
char fname[30],mname[30],lname[30],name[100];
int c,cnt=0;
clrscr();
puts("Enter first name");
gets(fname);
puts("Enter middle name");
gets(mname);
puts("Enter last name");
gets(lname);
for(c=0;fname[c]!='\0';c++,cnt++)
name[cnt]=fname[c];
name[cnt++]=' ';
for(c=0;mname[c]!='\0';c++,cnt++)
name[cnt]=mname[c];
name[cnt++]=' ';
for(c=0;lname[c]!='\0';c++,cnt++)
name[cnt]=lname[c];
name[cnt]='\0';
puts(name);
getch();
}

Program to check whether the string is palindrome or not

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int i,j,n,flag=0;
char str[20];
clrscr();
By Prof. Manoj Dhande 7738339960
86
Shah and Anchor Kutchhi Engg College, Chembur C Programming

printf("Enter String:");
gets(str);
n=strlen(str);
for(i=0,j=n-1;i<=n/2;i++,j--)
{
if(str[i]!=str[j])
{
flag=1;
break;
}
}
if(flag==0)
printf("String is palindrome");
else
printf("String is not Palindrome");
getch();
}
Program to check whether both the strings are equal or not

#include<stdio.h>
#include<conio.h>
void main()
{
char str1[30],str2[30];
int c=0;
clrscr();
puts("Enter first string");
gets(str1);
puts("Enter second string");
gets(str2);
while(str1[c]!='\0' && str2[c]!='\0' && (str1[c]==str2[c]))
{
c++;
}
if(str1[c]=='\0' && str2[c]=='\0')
printf("Strings are equal");
else
printf("Strings are not equal");
getch();
}
WAP to accept a string and display it in alphabetical order.

int main()
{
char a[20],temp;
int n,i,j;
printf("Enter string: ");
By Prof. Manoj Dhande 7738339960
87
Shah and Anchor Kutchhi Engg College, Chembur C Programming

scanf("%s",a);
n=strlen(a);
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}

printf("Storted String is: %s",a);

return 0;
}

Write a program to accept lower case string from user and convert it to upper case.
E.g all the best --- ALL THE BEST
#include <stdio.h>
#include<string.h>

int main()
{
char a[20];
int i=0;
printf("Enter String:");
gets(a);
for(i=0;a[i]!='\0';i++)
{
if(a[i]>=97 && a[i]<=122 )
a[i]=a[i]-32;
}
printf("%s",a);
return 0;
}
//Program to sort list of names in alphabetical order

#include<stdio.h>
#include<conio.h>
#define cnt 5
void main()
{
By Prof. Manoj Dhande 7738339960
88
Shah and Anchor Kutchhi Engg College, Chembur C Programming

char name[cnt][20],temp[20];
int i,j;
clrscr();
printf("Enter %d names\n",cnt);
for(i=0;i<cnt;i++)
gets(name[i]);
for(i=0;i<cnt-1;i++)
{
for(j=i+1;j<cnt;j++)
{
if(strcmp(name[i],name[j])>0)
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}
printf("\nSorted name\n");
for(i=0;i<cnt;i++)
printf("%s\n",name[i]);
getch();
}
// Program to concatenate first, middle and last name using function
#include<stdio.h>
#include <conio.h>
void concat(char first[], char middle[], char last[]);
void main()
{
int i;
char first[20],middle[20],last[20];
clrscr();
printf("Enter first name: ");
scanf("%s",first);
printf("Enter middle name: ");
scanf("%s",middle);
printf("Enter last name: ");
scanf("%s",last);
concat(first,middle,last); // Function Call
getch();
}
void concat(char first[],char middle[],char last[]) // Function Definition
{
int i,j,k;
char join[30];
for(i=0;first[i]!='\0';i++)
{
By Prof. Manoj Dhande 7738339960
89
Shah and Anchor Kutchhi Engg College, Chembur C Programming

join[i]=first[i];
}
join[i]=' ';
for(j=0;middle[j]!='\0';j++)
{
join[i+j+1]=middle[j];
}
join[i+j+1]=' ';
for(k=0;last[k]!='\0';k++)
{
join[i+j+k+2]=last[k];
}
join[i+j+k+2]='\0';
printf("Concatenated String is: %s\n",join);
}

POINTERS

Pointers:
Pointers are important features of C language. In C it is frequency used. Using of pointer
provides certain advantages.
1. Pointer allows passing variables, arrays, functions, strings and structure as function
arguments.
2. A pointer allows returning structured variables from functions.
3. It supports dynamic allocation and deallocation of memory segments.
4. With the help of pointers, variable can be swapped without physically moving them.
5. It allows establishing a link between data elements or objects.
Pointer is one of the strongest but also one of the dangerous features in C. It may cause your
system to crash if they are not utilized properly. If they are used incorrectly, it causes bugs that
are difficult to find.
What is pointer?
As we know computer uses memory for storing instructions and the value of variables. The
computer memory is a sequential collection of storage cells. Each cell has a number called address of
the cell.
Whenever we declare a variable, then it gets associated with certain location where the value of
the variable is stored.
Consider the declaration
int x = 30;
This statement tells C complier to:
i) Reverse space of 2 bytes in memory to hold integer value.
ii) Associate the name x with this location.
iii) Store the value 30 at this location.
Figure show the variable declaration.

x Location name (variable)


30
30 Value at location
By Prof. Manoj Dhande 7738339960
90
Shah and Anchor Kutchhi Engg College, Chembur C Programming

6480 Location number (address)

We observe that the computer has selected a memory location 6480 as a place to store value 30.
The location is changing, as some other time computer may choose another location to store value.
Here the address of int memory is 6480.
The value 30 can be accessed by either x or the address 6480. This memory address can be
assigned to some variable. Such variable which holds memory address are called as pointer.
A pointer is variable that holds a memory address. This address is the location of another variable
in memory. For example, if one variable contains the address of another variable, the first variable is
said to point to the second.

Declaring a pointer variable:


In C, every variable must be declared for its type before use. Similarly the pointer variable must
be declared before we use them. The syntax for declaration of pointer variable is
datatype *pointer_name;
Here datatype is base type of pointer and may be any valid type. The pointer_ name is name of
the pointer variable. The asterisk (*) tells that pointer_name is a pointer variable. The datatype of
pointer defines what type of variables the pointer can point to.
For example, int *ptr;
This statement declares that ptr is pointer variable that points to an integer type variable.
Observe that the type int refers to the data type of variable being pointed by ptr and not the value of
the pointer.
The pointer operators:
There are two special pointer operators: * and &.
The & is unary operator called as Referencing operator that returns the memory address of its
operand. For example,
m= &count;
Assigns memory address of variable count to m. The operators & can be remembered as “the address
of”. Therefore the above statement means “m receives the address of count”.
If the variable count uses the address say, 6500 to store its value, say 10, then after above
assignment, m will have a value 6500.
The second pointer operator is *. This is also a unary operator called as indirection operator Or
dereferencing operator. It returns the value located at the address that follows. For example, if m
contains the memory address of the variable count,
q= *m;
Place the value of the count into q. thus q will have a value 10 because 10 is stored at location
6500, which is memory address that was stored in m. the operator * can be remembered as “value at
address”. The above statement means “q receives the value at address m”.
Both & and * have higher precedence than all other arithmetic operators except the unary minus,
with which they are equal.
m= &count; and q=*m; are equivalent to q=*(&count);
The following program demonstrates the above.
void main( )
{
int count =10; count ptr
int *ptr;
10 1000
By Prof. Manoj Dhande 7738339960
91
Shah and Anchor Kutchhi Engg College, Chembur C Programming

ptr=&count;
printf(“\n Address of count =%d”,&count); Address Address
printf( “\n Address of count =%d”,ptr); 1000 2000
printf( “\n Address of ptr =%d”, &ptr);
printf( “\n Value of ptr =%d”,ptr);
printf( “\n Value of count =%d”,count);
printf( “\n Value of count =%d”, *&count);
printf( “\n Value of count =%d”,*ptr);
}
The output of above program is:
Address of count = 1000
Address of count = 1000
Address of ptr = 2000
Value of ptr = 1000
Value of count =10
Value of count =10
Value of count =10
We can change the value of variable indirectly using a pointer and the indirection operators.
*ptr = 25; will change value of count to 25.
Pointer expressions:
Pointer expression is expression involving pointers. They follow rules as other expression.
Lets us discuss some aspects of pointer expression.
1) Pointer assignment
We can use a pointer variable on right hand side of assignment statement as we assign its value
to another variable.
If p1 and p2 are pointer variable they we may write.
p1=p2;
Here both p1 and p2 will point to same variable.
2) Pointer Arithmetic
There are only two operations that you may use on pointers: addition and subtraction. Suppose
p1 is an integer pointer with the current value 6000.
The expression,
p1=p1+10;
Makes p1 point to the tenth element of p1’s type beyond the one it currently points to.
If integer is 2 byte long, the news value of p1 will be 6020 and not 6010.
The expression,
p1 ++;
Will increment p1. The new value of p1 will be 6002 and not 6001.
The expression,
p1 - - ;
Will decrement p1. The new value of p1 will be 5998.
Each time the pointer is incremented, it points to the memory location of the next element of its
base type. Each time it is decremented, its points to the location of the previous element. In case of
character pointers it will cause increment and decrement by 1 only.
If p1 and p2 are pointers, then following statements
y=*p1 * *p2;
sum =sum + *p1;
By Prof. Manoj Dhande 7738339960
92
Shah and Anchor Kutchhi Engg College, Chembur C Programming

*p2=*p2+10;
Are all valid statements.
Pointers and arrays:
There is close relationship between pointer and arrays. Any operation that can be achieved by
array subscripting can also be achieved by using pointers.
It uses less memory and program runs faster.
The array name is a pointer to the first element of the array.
For example,
char c [MAX];
The array name c is a pointer to first element c [0].
If cptr is a character pointer,
char *cptr;
then
cptr=c;
cp=&c [0]. Are equivalent. Here cptr is set to the address of the first element of the c.
Array subscripting can also be defined in terms of pointer arithmetic. To access fifth element.
We can write,
char * cptr;
c[4]
*(c+4)
in general the expression
c[i]
is defined to same as
*[c+i]
Also &c[i] is same as c+i.
Pointers and Functions:
Pointers can be used in functions declaration. When pointer variable is used as formal
argument, then calling a function is referred as call by address.
In call by address, when a function is called by a program, the address of actual arguments are
copied on to the formal arguments. That is, formal and actual arguments are referencing to same
memory location. Therefore change in value of formal argument affects the value of actual argument.
The call by address is used when function produces more than one value and provides these values to
the caller.
For example,
void main ( )
{
void funct1 (int * a, int *b);
----------------
funct1 (&x, &y); // call by address
---------------------
}
void funct1(int *a, int *b)
{
-------------------------
}
We are calling the function in statement
funct1 (&x, &y);
By Prof. Manoj Dhande 7738339960
93
Shah and Anchor Kutchhi Engg College, Chembur C Programming

And we are passing address of x and y to the formal pointer variables a and b. therefore x and a refers
to same memory location. Similarly y and b refers to same memory location. Any change in value of a
or b will ultimately changes the value of x and y.
A function swap ( ) which exchange the value of two integer variables using pointers and
function arguments is shown below.
void swap (int *a, int *b)
{
int temp;
temp=*a;
*a =*b;
*b =temp;
}
swap ( ) is called by passing the addresses of two variables whose values are to be interchanged.
swap (&x, &y);
Passes address of x and y to pointer variable a and b.
swap ( ) function interchange values of x and y.
//Program to swap two numbers using call by value

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

void swap(int , int ); //Function declaration


void main()
{
int a,b;
clrscr();

printf("Enter two numbers\n"); //Input


scanf("%d%d",&a,&b);

printf("Before Swapping a=%d and b=%d",a,b);

swap(a,b); //Function Call

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


getch();
}

//Function Definition
void swap(int a, int b) // Function header
{
int temp;
temp=a;
a=b;
b=temp;
}

By Prof. Manoj Dhande 7738339960


94
Shah and Anchor Kutchhi Engg College, Chembur C Programming

//Output

Enter two numbers


5 10
Before Swapping a=5 and b=10

After Swapping a=5 and b=10

// Program to swap two numbers using call by address (reference)

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

void main()
{
void swap(int *,int *);
int a,b;
clrscr();
printf("CALL BY Address\n");
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
printf("BEFORE CALLING : \n");
printf("A : %d B : %d\n",a,b);
swap(&a,&b);
printf("AFTER CALLING : \n");
printf("A : %d B : %d",a,b);
getch();
}
void swap(int *x,int *y)
{
int z;
z=*x;
*x=*y;
*y=z;
}

//Output

CALL BY Address

Enter two numbers

10

20

BEFORE CALLING :
By Prof. Manoj Dhande 7738339960
95
Shah and Anchor Kutchhi Engg College, Chembur C Programming

A : 10 B : 20

AFTER CALLING :

A : 20 B : 10
// Program for addition of elements of an array using pointer
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],sum=0,n;
int *ptr;
clrscr();
printf("Enter number of elements:");
scanf(”%d”,&n);
for(int i=0;i<n;i++)
{
printf("a[%d]:",i);
scanf(“%d”,&a[i]);
}
ptr=a;
for(i=0;i<n;i++)
{
sum=sum+(*ptr);
ptr++;
}
printf("Addition of Elements: %d",sum);
getch();
}
// Program to display elements of an array in reverse order using pointer
#include<stdio.h>
#include<conio.h>
#define SIZE 10
void main()
{
int a[SIZE],*ptr,i,n;
clrscr();
printf("\nEnter the number of elements: ");
scanf("%d",&n);
printf("\nEnter the elements of an array :\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
ptr=a+n-1;
printf("\nThe elements in reverse order are : \n");
By Prof. Manoj Dhande 7738339960
96
Shah and Anchor Kutchhi Engg College, Chembur C Programming

for(i=0;i<n;i++)
{
printf("%d ",*ptr);
ptr--;
}
getch();
}

STRCTURE AND UNION

The fundamental data types in C are int, char, float and double. But in real life you will find
that the data is not as int, char, float or double. The data is mixed type and dissimilar. Consider a
person. A person is associated with many attributes like name, address, age and so many. Here you
will find name and address is a string data and age is integer data. In real life the data is a collection of
many data types and these data types are logically related to each other.
The C language provides several ways to create a custom (user defined) data types. They are:
i) Structure person
ii) Union name address age
iii) Enumeration
iv) Typedef p1
p2
Structure:
A structure is a collection of variables of same or different data types. A structure declaration
forms a template that may be used create structure variable or objects. We can declare a structure as
follows:
struct person
{
char name [10];
char address [20];
int age;
};
The keyword struct declares structures that hold three fields- name, address and age. These are
structure members. Each member may be belonging to different type of data but they are logically
related to each other. person is structure type name. Structure declaration is terminated by semicolon.
We can create variables belonging to structure type as follows:
struct person p1, p2;
Here p1 and p2 are variable belonging to structure type person. When structure variables are
declared, the complier automatically allocates sufficient memory to accommodate all of its members.
The structure variable may be declared while declaring the structure itself has as shown below.
struct person
{
char name [10];
char address [20];
int age;
} p1, p2;

By Prof. Manoj Dhande 7738339960


97
Shah and Anchor Kutchhi Engg College, Chembur C Programming

Accessing Structure Members:


Individual members can be accessed through the use of .(dot) operator.
For example: p1.name = “Ashok”;
The structure variable name followed by a dot and the member name
The general form for accessing a member of structure is
structure_variable_name.member_name
To display the name on screen we write,
Printf(“%s”, p1. Name);

Structure Assignment:
The information contained in one structure variable may be assigned to another structure
variable of the same type by single assignment statement. You need not to assign each member
separately.
For example,
struct Point
{
int x;
int y;
} a, b;
a.x=10;
b.y=20;
b= a;
Note that after assignment b.x will contain value10 and b.y will contain 20.
Array of structure variables:
The most common usage of structure is an array of structure variable. To define 100 element
array of structure person we write,
struct person p[100];
This creates 100 sets of variable that are organized as defined in structure person.
The following program demonstrate array of structure book.
struct book
{
char name [10];
float price;
int pages;
};
void main()
{
struct book b[100];
int i;
for (i=0; i<=99; i++)
{
scanf(“%s %f %d “,b[i].name, b[i].price, b[i]. pages);
}
}

Unions:
By Prof. Manoj Dhande 7738339960
98
Shah and Anchor Kutchhi Engg College, Chembur C Programming

The union is a collection of variable of same or different data types. It is used to create user
defined data type. Union allows different types of data items to share the same memory location. The
complier allocates space to hold the largest data item in the union.
The syntax of union is similar to that of structure.
union item
{
int m;
float x;
char c;
}code;
This declares a variable code of type union. Union contains three items, each with a different
data type. We can use only one of them at a time. To access a union member, we can use same syntax
as that for structure members.
code.m=379;
code.x= 7859.59;
code.c =’y’;
Union can be used in all places where structure is allowed. In structure each member has its
own storage location, but all members in union use same memory location. This storage location can
be used by only one union member at a time. When a different member is assigned a new value, the
new value supersedes the previous member’s value.
// Program for structure

#include <stdio.h>
struct Student
{
int roll,ia1,ia2,total;
char name[20];
};

int main()
{
struct Student s[60];
int n,i;
printf("Enter number of Students: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter roll, name and marks of IA1 and IA2: ");
scanf("%d%s%d%d",&s[i].roll,s[i].name,&s[i].ia1,&s[i].ia2);
}
for(i=0;i<n;i++)
{
s[i].total=s[i].ia1+s[i].ia2;
}
printf("Roll No\tName\tIA1\tIA2\tTotal\n");
for(i=0;i<n;i++)
{
By Prof. Manoj Dhande 7738339960
99
Shah and Anchor Kutchhi Engg College, Chembur C Programming

printf("%d\t%s\t%d\t%d\t%d\n",s[i].roll,s[i].name,s[i].ia1,s[i].ia2,s[i].total);
}
return 0;
}
// Program for structure

#include <stdio.h>
struct Student
{
int roll,ia1,ia2,total;
char name[20];
};

int main()
{
struct Student s[60],temp;
int n,i,j;
printf("Enter number of Students: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter roll, name and marks of IA1 and IA2: ");
scanf("%d%s%d%d",&s[i].roll,s[i].name,&s[i].ia1,&s[i].ia2);
}
for(i=0;i<n;i++)
{
s[i].total=s[i].ia1+s[i].ia2;
}
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(s[i].total>s[j].total)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}

printf("Roll No\tName\tIA1\tIA2\tTotal\n");
for(i=0;i<n;i++)
{
printf("%d\t%s\t%d\t%d\t%d\n",s[i].roll,s[i].name,s[i].ia1,s[i].ia2,s[i].total);
}
return 0;
}
// Program for structure

#include <stdio.h>
By Prof. Manoj Dhande 7738339960
100
Shah and Anchor Kutchhi Engg College, Chembur C Programming

#include <string.h>
struct Student
{
int roll,ia1,ia2,total;
char name[20];
};

int main()
{
struct Student s[60],temp;
int n,i,j;
printf("Enter number of Students: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter roll, name and marks of IA1 and IA2: ");
scanf("%d%s%d%d",&s[i].roll,s[i].name,&s[i].ia1,&s[i].ia2);
}
for(i=0;i<n;i++)
{
s[i].total=s[i].ia1+s[i].ia2;
}
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(strcmp(s[i].name,s[j].name)>0)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}

printf("Roll No\tName\tIA1\tIA2\tTotal\n");
for(i=0;i<n;i++)
{
printf("%d\t%s\t%d\t%d\t%d\n",s[i].roll,s[i].name,s[i].ia1,s[i].ia2,s[i].total);
}
return 0;
}
OUTPUT
Enter number of Students: 5
Enter roll, name and marks of IA1 and IA2: 1 xyz 12 13
Enter roll, name and marks of IA1 and IA2: 2 uvw 10 14
Enter roll, name and marks of IA1 and IA2: 3 trv 12 14
Enter roll, name and marks of IA1 and IA2: 4 sdf 10 12
Enter roll, name and marks of IA1 and IA2: 5 abc 12 13
Roll No Name IA1 IA2 Total
5 abc 12 13 25
By Prof. Manoj Dhande 7738339960
101
Shah and Anchor Kutchhi Engg College, Chembur C Programming

4 sdf 10 12 22
3 trv 12 14 26
2 uvw 10 14 24
1 xyz 12 13 25
#include<stdio.h>
#include <string.h>
struct Student
{
int roll,ia1,ia2,total;
char name[20];
};

int main()
{
void cal_Total(struct Student s[],int);
void sort(struct Student s[],int);

struct Student s[60];


int n,i,j;
printf("Enter number of Students: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter roll, name and marks of IA1 and IA2: ");
scanf("%d%s%d%d",&s[i].roll,s[i].name,&s[i].ia1,&s[i].ia2);
}
cal_Total(s,n);
sort(s,n);
printf("Roll No\tName\tIA1\tIA2\tTotal\n");
for(i=0;i<n;i++)
{
printf("%d\t%s\t%d\t%d\t%d\n",s[i].roll,s[i].name,s[i].ia1,s[i].ia2,s[i].total);
}
return 0;
}
void cal_Total(struct Student s[], int n)
{
int i;
for(i=0;i<n;i++)
{
s[i].total=s[i].ia1+s[i].ia2;
}
}
void sort(struct Student s[],int n)
{
int i,j;
struct Student temp;
By Prof. Manoj Dhande 7738339960
102
Shah and Anchor Kutchhi Engg College, Chembur C Programming

for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(strcmp(s[i].name,s[j].name)>0)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
//OUTPUT
Enter number of Students: 5
Enter roll, name and marks of IA1 and IA2: 1 aaa 12 13
Enter roll, name and marks of IA1 and IA2: 2 uvw 12 15
Enter roll, name and marks of IA1 and IA2: 3 bbb 12 13
Enter roll, name and marks of IA1 and IA2: 4 rrr 12 15
Enter roll, name and marks of IA1 and IA2: 5 uuu 12 11
Roll No Name IA1 IA2 Total
1 aaa 12 13 25
3 bbb 12 13 25
4 rrr 12 15 27
5 uuu 12 11 23
2 uvw 12 15 27

#include <stdio.h>
struct Point
{
int x,y;
};

int main()
{
struct Point addition(struct Point,struct Point);
struct Point p1,p2,p3;
printf("Enter coordinates of First Point");
scanf("%d%d",&p1.x,&p1.y);
printf("Enter coordinates of Second Point");
scanf("%d%d",&p2.x,&p2.y);
p3=addition(p1,p2);
printf("After Addition : x=%d y=%d",p3.x,p3.y);

return 0;
}
struct Point addition(struct Point p1,struct Point p2)
{
struct Point temp;
temp.x=p1.x+p2.x;
temp.y=p1.y+p2.y;
By Prof. Manoj Dhande 7738339960
103
Shah and Anchor Kutchhi Engg College, Chembur C Programming

return temp;
}

//Program to display the book information according to the given price using structure
#include<conio.h>
#include<stdio.h>
struct book
{
char title[20];
char author[20];
int quantity,price;
};
void main()
{
struct book b[10];
int i,cost;
clrscr();
for(i=0;i<3;i++)
{
printf("Enter the title of the book");
gets(b[i].title);
printf("Enter the author of the book");
gets(b[i].author);
printf("Enter the quantity of the book in stock");
scanf(“%d”,&b[i].quantity);
printf("Enter the price");
scanf(“%d”,&b[i].price);
}
printf("Enter the price range above which you want to view the books:\n");
scanf(“%d”,&cost);
for(i=0;i<3;i++)
{
if(b[i].price>cost)
{
printf("Book title %s Book author %s Quantity of books %d Cost of the
book\n",b[i].title,b[i].author,b[i].quantity,b[i].price);
}
}
}

By Prof. Manoj Dhande 7738339960


104
Shah and Anchor Kutchhi Engg College, Chembur C Programming

//Output

Enter the title of the book C program


Enter the author of the book Bala
Enter the quantity of the book in stock 10
Enter the price 200
Enter the title of the book C++ prog
Enter the author of the book Kanetkar
Enter the quantity of the book in stock 12
Enter the price 250
Enter the title of the book Socket guide
Enter the author of the book lal
Enter the quantity of the book in stock 13
Enter the price 90
Enter the price range above which you want to view the books
100
Book title C program Book author Bala Quantity of books 10 Cost of the book 200

Book title C++ prog Book author Kanetkar Quantity of books 12 Cost of the book 250

//PROGRAM TO store information of hotels and display hotels having charges less than entered
charge
#include<stdio.h>
#include<conio.h>
struct hotel
{
char name[10], address[10];
float avg_charge;
int rooms;
};
void main()
{
struct hotel h[50];
int n;
float charge;
clrscr();
printf("Enter No Of Hotels:");
scanf(“%d”,&n);
printf("Enter Information Of Hotels:\n");
for(int i=0;i<n;i++)
{
printf("Name:");
gets(h[i].name);
printf("Address:");
gets(h[i].address);
printf("Average Charge:");
By Prof. Manoj Dhande 7738339960
105
Shah and Anchor Kutchhi Engg College, Chembur C Programming

scanf(“%f”,&h[i].avg_charge);
printf("Total Rooms:");
scanf(“%d”,&h[i].rooms);
}
printf("Room Charge To Search:");
scanf(“%f”,&charge);
printf("List Of Hotels Having Average charge less than : %f",charge);
for(i=0;i<n;i++)
{
if(h[i].avg_charge<charge)
{
printf("\nName: %s ",h[i].name);
printf("\nAddress: %s",h[i].address);
printf("\nAverage Charge: %f",h[i].avg_charge);
printf("\nTotal Rooms: %d",h[i].rooms);
}
}
getch();
}
//OUTPUT

Enter No Of Hotels:2
Enter Information Of Hotels:
Name:TAJ
Address:MUMBAI
Average Charge:500.00
Total Rooms:10
Name:VEDANT
Address:PUNE
Average Charge:400.00
Total Rooms:5
Room Charge To Search:450.00

List Of Hotels Having Average charge less than :450

Name: VEDANT
Address:400.00
Average Charge:400
Total Rooms:5

By Prof. Manoj Dhande 7738339960


106
Shah and Anchor Kutchhi Engg College, Chembur C Programming

//Program to sort book information using book no.


#include<stdio.h>
#include<conio.h>
#include<string.h>
struct book
{
char title[10];
int no;
};
void main()
{
struct book b[10],temp;
int n,i;
clrscr();
printf("Enter no of books:");
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf("Enter Number and Title :");
scanf(“%d %s”,&b[i].no,b[i].title);
}
for(i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(b[i].no>b[j].no)
{
temp=b[i];
b[i]=b[j];
b[j]=temp;
By Prof. Manoj Dhande 7738339960
107
Shah and Anchor Kutchhi Engg College, Chembur C Programming

}
}
}
printf("After Sorting:\n)";
printf("No : Title:\n");
for(i=0;i<n;i++)
{
printf(“%d %s”,b[i].no,b[i].title);
}
getch();
}

//OUTPUT

Enter no of books:5
Enter Number and Title :5 PHY
Enter Number and Title :3 CHI
Enter Number and Title :4 CP1
Enter Number and Title :1 CP2
Enter Number and Title :2 M2
After Sorting:
No : Title:
1 CP2
2 M2
3 CHI
4 CP1
5 PHY

By Prof. Manoj Dhande 7738339960


108
Shah and Anchor Kutchhi Engg College, Chembur C Programming

//Program to store information of cricketer and to display information in ascending order of


batting average
#include<stdio.h>
#include<conio.h>
struct cricket
{
char p_name[10], team_name[10];
float bat_avg;
};
void main()
{
struct cricket c[50],temp;
int n;
clrscr();
printf("Enter Number of Players:");
scanf(“%d”,&n);
for(int i=0;i<n;i++)
{
printf("Player Name:");
scanf(“%s”,c[i].p_name);
printf("Team Name:");
scanf(“%s”,c[i].team_name);
printf("Batting Average:");
scanf(“%f”,&c[i].bat_avg);
}
for(i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(c[i].bat_avg>c[j].bat_avg)
{
temp=c[i];
c[i]=c[j];
c[j]=temp;
By Prof. Manoj Dhande 7738339960
109
Shah and Anchor Kutchhi Engg College, Chembur C Programming

}
}
}
for(i=0;i<n;i++)
{
printf("\nPlayer Name: %s",c[i].p_name);
printf(" Team Name: %s",c[i].team_name);
printf(" Batting Avg: %f",c[i].bat_avg);
}
getch();
}
//OUTPUT
Enter Number of Players:4
Player Name:Ganguly
Team Name:India
Batting Average:80.00
Player Name:Ponting
Team Name:Aus
Batting Average:75.00
Player Name:Usuf
Team Name:Pak
Batting Average:20.00
Player Name:Tendulkar
Team Name:India
Batting Average:90.00

Player Name:Usuf Team Name:Pak Batting Avg:20


Player Name:Ponting Team Name:Aus Batting Avg:75
Player Name:Ganguly Team Name:India Batting Avg:80
Player Name:Tendulkar Team Name:India Batting Avg:90

By Prof. Manoj Dhande 7738339960


110
Shah and Anchor Kutchhi Engg College, Chembur C Programming

By Prof. Manoj Dhande 7738339960


111

You might also like