Professional Documents
Culture Documents
C Notes - 05.06.2021
C Notes - 05.06.2021
C Notes - 05.06.2021
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.
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…
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
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.
Example :
1. Flowchart for addition of two numbers
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
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
Separators:
Separators are special symbols used to indicate where groups of code are divided and arranged.
Ex : . ; : ? Space ( ) [ ] etc
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 :
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)
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.
<
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
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.
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.
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
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();
}
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();
}
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.
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();
}
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();
}
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
if (condition)
{
Statement-block;
}
Stmt-X;
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:
#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();
}
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.
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
Block1 Block2
Statement -X
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();
}
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
if (condition1)
{
if( condition2)
{
Block1;
}
else
{
Block2;
}
}
else
{
if( condition3)
{
Block3;
}
else
{
Block4;
}
}
Stmt –X;
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();
}
else
printf("not a leap year");
}
getch();
}
Flowchart:
Entry
T Condition-1 F
T Condition-2 F
Block1
Block2 T Condition -3 F
Block3 T Condition-n F
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
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();
}
}
getch();
}
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.
Syntax:
switch(expression)
{
}
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.
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();
}
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.
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();
}
#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();
}
else
printf("Number %d is not palindrome",m);
getch();
}
getch();
}
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.
for (i=1;i<10;i++)
{
---------------
for ( j = 1; j<5; j++)
{
----------------
}
}
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 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
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();
}
for(j=1;j<=3;j++)
{
for(k=1;k<=3;k++)
{
printf("%d%d%d",i,j,k);
printf("\n");
}
}
}
getch();
}
/*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();
}
/*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();
}
#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();
}
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 }
--------
do
{
----------
----------
if (condition )
break;
----------
exit from ---------
loop }
while (-------);
---------
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();
}
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:-
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.
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();
}
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.
stdio.h
printf( ), scanf( ) etc.
conio.h
getch( ), clrscr( ) etc.
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;
#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
#include <stdio.h>
#include <conio.h>
void main()
{
int a,b,gcd,lcm;
clrscr();
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
printf("GCD=%d LCM=%d",gcd,lcm);
getch();
}
{
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:
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>
void main()
{
int a,b,gcd,lcm,prod;
clrscr();
//Input
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
lcm=(a*b)/gcd;
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
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.
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.
External variables:
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
------------
------------
}
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.
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.
.
.
.
.
8th element 1014
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();
}
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]);
}
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;
}
}
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();
}
}
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();
}
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[ ])
{
-------------------
------------------
}
#include<stdio.h>
#include <conio.h>
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);
{
int sum=0,i;
for(i=0;i<n;i++)
{
sum=sum+a[i];
}
return(sum);
}
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.
#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();
}
#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]);
}
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);
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.
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
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
#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();
}
#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;
}
}
}
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.
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.
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>
//Function Definition
void swap(int a, int b) // Function header
{
int temp;
temp=a;
a=b;
b=temp;
}
//Output
#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
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();
}
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;
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);
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);
}
}
}
//Output
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
Name: VEDANT
Address:400.00
Average Charge:400
Total Rooms:5
}
}
}
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
}
}
}
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