C Programming: Algorithms & Flowcharts
C Programming: Algorithms & Flowcharts
Unit No:1
Introduction to Algorithm and
Flowchart
Faculty Name : Dr. Gautam M Borkar
1
Course Objective and Outcomes
Course Objectives
1. To familiarize the logic of structured programming approach.
2. To provide exposure in developing algorithm, flowchart and writing
efficient code for user defined problems.
Course Outcomes :
CO1: Understand the basic terminology used in computer programming.
CO2: Illustrate the concept of data types, variables and operators using
C.
CO3: Design and Implement various control structures in C.
CO4: Demonstrate the use of arrays, strings, structures in C.
CO5: Implement modular programming to solve real life problems.
CO6: Apply concepts of dynamic memory allocation to construct various
data structures.
Lecture 1 - Turing Model, Von Neumann Model and Types of Programming Languages 6
4
Module 1
Lecture Details of Topics to be Covered
No.
1. Basics of Computer
2. Problem Solving
3. Sequence
Algorithm and Decision(Selection)
4. flowchart:
5. Repetition
Lecture No: 1
Turing Model, Von Neumann
Model and Types of
Programming Languages
What is a Computer?
• A computer is a programmable electronic device that accepts raw data as
Process
Assembly language
The machine code cannot run on all machines, so The high-level code can run all the platforms, so it
it is not a portable language. is a portable language.
Lecture No: 2
Problem Solving and
Algorithm
Problem Solving
• Pseudocode
• Algorithm
• Flowchart
Begin program
get radius, PI
circumference = 2 * P I* radius
area=PI * radius * radius
display circumference, area
End program
Step 1: Start
Step 2: Take input for radius
Step 3: PI=3.14
Step 4: area=PI* radius * radius
Step 5: circumference=2*PI* radius
Step 6: Display radius, area and circumference
Step 7: Stop
Output: sum
Step 3 : sum=num1+num2
Step 5 : Stop.
Input: a, b, c
Output: avg.
Step 6 : Stop
.
60 Lecture 2: Problem Solving and Algorithm
Example 4 :
Q. Define problem “to calculate the simple interest using the
formula. Simple interest = P*N* R/100.”
Problem definition :IPO
Step 5 : Stop.
Lecture No: 3
Flowchart
Example 6 :
Q. Write an algorithm “to swap two numbers”.
Step 1 : Start.
Step 2 : Read two numbers num1 and num2.
Step 3 : Declare temporary variable temp.
Step 4 : Interchange the data
temp = num1
num1 =num2
num2 = temp
Step 6 : Print the value of num1 and num2.
Step 7 : Stop.
67 Lecture 3 Flowchart
Example 7 :
Q. Write an algorithm “to find the largest of two numbers X, Y.”
Step 1 : Start.
Step 3 : if X > Y
Print value of X as the largest number and go to step 5.
Step 4 : if X < Y
Print value of Y as the largest number and go to step 5.
Step 5 : Stop.
68 Lecture 3 Flowchart
Example 8 :
Q. Write an algorithm “to find the given number is even or
odd.”
Step 1 : Start.
Step 2 : Read number say Num.
Step 3 : if Num mod 2 = 0
Print “Number entered is even number.” and go to
Step 4 : if Num mod 2 <> 0
Print “Number entered is odd number.” and go to
Step 5 : Stop.
69 Lecture 3 Flowchart
Flowchart
• A flowchart is a pictorial representation of a sequence of steps to be
performed for solving a given problem
• The flowcharts helps to analyze the problem and plan its solution
in a systematic and orderly manner.
70 Lecture 3 Flowchart
Symbols used in Flowchart
Guidelines for preparing Flowcharts
• The flowchart should be clear, neat and easy to follow.
• The flowchart must have logical start and finish.
• Only one flow line should come out from a process symbol.
• Only one flow line should enter a decision symbol. However two
or three flow lines (one for each possible answer) may leave the
decision symbol.
• In case of complex flowcharts connector symbols are used to
reduce the number of flow lines.
75 Lecture 3 Flowchart
Example 1
Start
Step 1: Start
Step 2: Take input for radius Take input for radius
Step 3: PI=3.14
Step 4: area=PI* radius * PI=3.14
radius
Step 5: circumference=2*PI*
radius area =PI*radius*radius
Step 6: Display radius, area
and circumference Circumference=2*PI*radius
Step 7: Stop
Display radius ,area ,circumference
Stop
Example 2 :
Q. Draw a flowchart “to find the average of
three numbers”.
Start
Step 1 : Start.
Stop
77 Lecture 3 Flowchart
Example 3 :
Q. Draw a flowchart “to calculate the simple
interest using the formula. Simple interest = Start
P*N* R/100.”
Step 1 : Start. Read values of P,
N and R
Step 2 : Read the three input quantities’ P, N
and R.
Calculate Simple Interest
Step 3 : Calculate simple interest as = P*N*R/100
Step 5 : Stop.
Stop
78 Lecture 3 Flowchart
Example 4 :
Q. Draw a flowchart “to calculate the perimeter and area of
rectangle. Given its length and width. ”
Start
Calculate Perimeter =
2*(length +width)
Print value of
Perimeter and area
Stop
79 Lecture 3 Flowchart
Benefits of a flowchart
81 Lecture 3 Flowchart
Difference between Algorithm and Flowchart
Algorithm Flowchart
A method of representing the Flowchart is diagrammatic
step-by-step logical procedure representation of an algorithm.
for solving a problem
1
Faculty Name : Dr. Gautam M Borkar
Index -
2
Module No: 1 Introduction to Algorithm And Flowchart
Lecture No: 4
Flowchart with Sequence and
Decision
Three construct of Algorithm and flowchart
1. Sequence
2. Branching (Selection)
3. Loop (Repetition)
Stop
Stop
Step 4: Stop.
Stop
Stop
Lecture 4 Flowchart with Sequence
13
and Decision
Example 4 :
Q. Write an algorithm “to find out the biggest of the three unequal
positive numbers. “
Step 1: Start
Step 2: Declare variables a, b and c.
Step 3: Read variables a, b and c.
Step 4: If a > b
If a > c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b > c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop.
Lecture 4 Flowchart with Sequence
14
and Decision
Example 5 :
Q. Draw a flowchart “to find out the biggest of the three
unequal positive numbers. Start
“
Read A, B and C
Yes No
Is
A>B
No No
Is Is
A>C B>C
Yes Yes
Stop
Lecture 4 Flowchart with Sequence
15
and Decision
Example 6 :
Q. Draw a flowchart “ABC company plans to give a 6% year-end bonus to
each of its employees earning Rs 6,000 or more per month , and a fixed
Rs 250 bonus to the remaining employees. Draw a flowchart for
calculating the bonus for an employee”
Start
Input Salary of an
employee
No Is Yes
Salary>=6000
Print Bonus
Lecture 4 Flowchart with Sequence
16
and Decision Stop
Example 7 :
Q. Draw a flowchart “to find Roots of Quadratic equation ax2+ bx +
c = 0. The coefficients a, b, c are the input data ”
Lecture No: 5
Flowchart with Repetition and
Pseudo Code
Repetition (Loop)
• The loop allows a statement or a sequence of statements to be
repeatedly executed based on some loop condition.
• A trip around the loop is known as iteration.
• We must ensure that the condition for the termination of the
looping must be satisfied after some finite number of iterations,
otherwise it ends up as an infinite loop.
• The loop is also known as the repetition structure.
• It is represented by the ‘while’, ‘do-while’ and ‘for’ control
structures in most programming languages.
Step 1 : Start.
i = 1, Sum = 0
Step 2 : Read number N.
No
Step 3 : Initialize counter, i=1 and Sum=0 Is i≤ N
Sum = Sum + i
Calculate Sum = Sum + i
Increase counter, i = i + 1
i=i+1
Step 5 : Print value of Sum.
Print value of Sum
Step 6 : Stop.
Stop
Lecture 5 Flowchart with Repetition
24
and Pseudo Code
Example 4 :
Q. Write an algorithm and draw flowchart “to display Start
Step 1 : Start.
No
Is i≤ 20
Step 2 : Initialize counter, i =1
Yes
Step 3 : repeat until i <=20 No
Is i% 2=0
if i % 2 = 0
Yes
Print value of i
Print value of i
Increment counter, i = i + 1
i=i+1
Step 4 : Stop.
Stop
Step 6 : Stop.
i=i+1
Print value of f
Stop
Lecture 5 Flowchart with Repetition
26
and Pseudo Code
Model Questions :
1. Define Algorithm.
2. What is Flowchart?
3. What is Pseudo code?
4. What are the symbols of Flowchart?
5. Write an algorithm and draw flowchart for calculating area and perimeter of
Triangle.
6. What are the basic steps involved In problem solving?
7. Differentiate between Algorithm and Flowchart.
8. Write an algorithm and draw flowchart to find smallest of given three
numbers.
9. Write an algorithm and draw flowchart to find odd numbers from M to N
numbers.
10. Write an algorithm and draw flowchart to find cube of even numbers from 1 to N.
Lecture No: 6
History of C Programming,
Benefits of C, Structure of C
program
History of C ProgrammingC Programming
Preprocessor program
processes the code
Preprocessor Creates object code
and stores on disk
Compiler
Example :
int add(int a, int b)
{
int d;
d=a+b;
return d;
}
#include <stdio.h>
Declares the main The directive #include tells the
function. The "void" preprocessor to include code from the
specifies the return void main() file stdio.h.
type of main. In this stdio.h header file contains
case, nothing is { declarations for functions that the
returned to the program needs to use. A declaration for
operating system. the printf function is in this file.
printf("Hello
Students");
printf is a function from a standard C
library that is used to print strings on
} the standard output device i.e.
“{“ denotes the start
Monitor.
and “}” denote end of
the program.
Lecture 7 – Character Set, Identifiers and keywords, Data types, Constants, Variables
3
Lecture 8 – Data Input and Output – scanf( ), printf( ), getchar( ), putchar( ), gets( ), puts( )
19
2
Module No: 2 FUNDAMENTALS OF C-PROGRAMMING
Lecture No: 7
Character Set, Identifiers and
keywords, Data types,
Constants, Variables
Tokens in c
4 Lecture 7: Tokens in C
Character Set
• Numerals: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
• Alphabets: a, b, ….z
• A, B, ……...Z
• Special Characters:
(){}[]<>=!$?.,:;‘“&
| ^ ~ ` # \ blank - _ / * % @
5 Lecture 7: Tokens in C
Keywords
Ke yw o rd s
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
6 Lecture 7: Tokens in C
Identifiers
7 Lecture 7: Tokens in C
Variables
8 Lecture 7: Tokens in C
Constant
9 Lecture 7: Tokens in C
Constant
• Example
#define A 10000
void main(){
int X=A;
int Y=A;
Equivalent to
void main(){
int X=10000;
int Y=10000
}
10 Lecture 7: Tokens in C
CLASSIFICATION : DATA TYPE
11 Lecture 7: Tokens in C
Primitive Data Types
12 Lecture 7: Tokens in C
Size and range of Integer type on 16-bit machine:
13 Lecture 7: Tokens in C
Size and range of Float type on 16-bit machine
14 Lecture 7: Tokens in C
Size and range of Character type on 16-bit machine
15 Lecture 7: Tokens in C
Fundamental Data type
16 Lecture 7: Tokens in C
Derived Data type
17 Lecture 7: Tokens in C
Practice example
• Identify the variables, constant required along with their data types, to
solve following problem using C Programming language
1. To calculate simple interest.
principal, years, int type
rateofinterest ,simple_interest float type
18 Lecture 7: Tokens in C
Practice example
• Identify the variables, constant required along with their data types, to
solve following problem using C Programming language
5. To store employee details like employee id, name, department and salary
Structure of
eid, int type
name, department array of char type/string
salary float type
19 Lecture 7: Tokens in C
Module No: 2 FUNDAMENTALS OF C-PROGRAMMING
Lecture No: 8
Data Input and Output – scanf( ),
printf( ), getchar( ), putchar( ),
gets( ), puts( )
Input/Output in C
• printf ( ) statement;
– This function provides for formatted output to the
screen.
– The syntax is:
printf ( “format”, var1, var2, … ) ;
– The “format” includes a listing of the data types of the
variables to be output and, optionally, some text and
control character(s).
– Example:
float a=3.5 ;
int b=10 ;
printf ( “a= %f and b=%d \n”, a, b ) ;
25 Lecture 8: Data Input and Output
Format Specifiers
Format Meaning
String
%d Scan or print an integer as signed decimal
number
%f Scan or print a floating point number
%c To scan or print a character
%s To scan or print a character string. The scanning
ends at whitespace.
%l used with other specifiers to indicate a "long"
%e displays a floating point value in exponential
notation
• scanf ( ) statement:
– This function provides for formatted input from the keyboard.
– The syntax is:
scanf ( “format” , &var1, &var2, …) ;
– Example:
float a;
int b;
scanf (“%f%d”, &a, &b);
#include<stdio.h>
#include<conio.h>
void main()
{
//Variable declaration
short int count;
int num;
float salary;
double speedoflight;
long int weightofcontainer;
clrscr();
//Take input for above data types using corresponding format specifier
printf("\nEnter value for count");
scanf("%d",&count); //250
printf("\ncount=%d",count); //count=250
34
Demonstration of Data types in C
35
Thank You
Module No: 1 Introduction to Algorithm And Flowchart
Lecture No: 9
Operators-Arithmetic,
Relational
CLASSIFICATION:OPERATORS IN C
#include<stdio.h>
#include<conio.h>
Output:
void main () Enter the radius of a circle: 5
{ The area is equal:78.500000
float r, area;
clrscr();
printf("Enter the radius of a circle:");
scanf("%f",&r);
area=3.14 *r*r;
printf("The area is equal:%f",area);
getch();
}
41
Write a program to calculate average of 3 numbers
#include<stdio.h>
#include<conio.h>
void main () Output:
{ int a, b, c, sum; Enter three numbers:10 20 30
float avg; The average is equal to: 20
clrscr();
printf("Enter three numbers:");
scanf("%d %d %d",&a,&b,&c);
sum= a+b+c;
avg=sum/3.0;
printf("The average is equal to:%f",avg);
getch();
}
42
Write a program to calculate area and perimeter of rectangle
#include<stdio.h>
#include<conio.h>
void main ()
{
float length, breadth, area, perimeter;
clrscr();
printf("Enter the length and breadth of the rectangle:");
scanf("%f%f",&length,&breadth);
area= length * breadth;
perimeter= 2* (length + breadth);
printf("The area of rectangle is= %f and its perimeter is = %f", area,
perimeter);
getch();
} Output:
Enter the length and breadth of the rectangle: 10 15
The area of rectangle is=150.000000 and its perimeter is = 50.000000
43
UNARY OPERATION
• Unary operators: The unary ‘–’ operator negates the value of its
operand (clearly, a signed number). A numeric constant is assumed
positive unless it is preceded by the negative operator. That is, there is
no unary ‘+’. It is implicit.
Postfix:
• (a) x = a++;
First action: store value of a in memory location for variable x.
Second action: increment value of a by 1 and store result in memory
location for variable a.
• (b) y = b––;
First action: put value of b in memory location for variable y.
Second action: decrement value of b by 1 and put result in memory
location for variable b.
Prefix :
• (a) x = ++a;
First action: increment value of a by 1 and store result in memory
location for variable a.
Second action: store value of a in memory location for variable x.
• (b) y = ––b;
First action: decrement value of b by 1 and put result in memory
location for variable b.
Second action: put value of b in memory location for variable y.
Example
Let b = 10 then
(++b)+b+b = 33
b+(++b)+b = 33
b+b+(++b) = 33
b+b*(++b) = 132
48
#include<stdio.h>
#include<conio.h>
void main ()
{
int k=3,l=4,m; Output:
clrscr(); Value of m 8
m=++k +l--; Value of m 6
printf("Value of m %d\n",m);
m=k++ + --l;
printf("Value of m %d\n",m);
getch();
}
49
#include<stdio.h>
#include<conio.h>
void main () Output:
{ d d
int a=2,b=3,ab=4; 333
int i; 444
char ch='c'; 555
clrscr();
printf("%c %c\n",ch,(++ch));
printf("%d %d %d\n",a,a,++a);
printf("%d %d %d\n",b,b,++b);
printf("%d %d %d\n",ab,ab,++ab);
getch();
}
50
Assignment operators
2
Lecture 10
Relational, Logical,
Conditional Operators
RELATIONAL OPERATORS
#include<stdio.h>
#include<conio.h> c=a<=b;
void main () printf("a<=b: %d\n", c); //0
{ c=a>=b;
printf("a>=b: %d\n", c); //1
int a=10, b=5,c;
getch();
clrscr(); }
printf("a= %d \nb= %d \n",a,b);
c=a<b; Output
printf("a<b: %d\n", c); //0 a= 10
c=a>b; b=5
a<b: 0
printf("a>b: %d\n", c); //1
a>b:1
c=a==b; a==b:0
printf("a==b: %d\n", c); //0 a!b:1
c=a!=b; a<=b:0
printf("a!=b: %d\n", c); //1 a>=b:1
P Q P&&Q P||Q !P
• For example,
int m = 1, n = 2, min;
min = (m < n ? m : n); /* min is assigned a value 1 */
#include<stdio.h> Output:
#include<conio.h> Enter two numbers 5 6
void main () The smaller number is 5
{
int n1, n2, min;
clrscr();
printf("Enter two numbers:");
scanf("%d %d",&n1,&n2);
min=(n1<n2)?n1:n2;
printf("The smaller number is :%d“,min);
getch();
}
Write a program to find number is even or odd using ternary operator
#include<stdio.h>
Output:
#include<conio.h> Enter a number: 10
void main () Even number
{
int a, rem;
clrscr();
printf("Enter a number:");
scanf("%d",&a);
rem=a%2;
(rem==0)?printf("Even number"):printf("Odd number");
getch();
}
Practice programs
14
EXPRESSION EVALUATION:
PRECEDENCE & ASSOCIATIVITY
• Evaluation of an expression
in C is very important to
understand. Unfortunately
there is no ‘BODMAS’ rule in
C language as found in
algebra.
• The precedence of operators
determines the order in
which different operators are
evaluated when they occur in
the same expression.
Operators of higher
precedence are applied
before operators of lower
precedence.
#include<stdio.h>
#include<conio.h> Output:
void main() a=16
a=14
{ a=4
int a, b=4, c=8,d=2,e=4,f=2;
a=b+c/d+e*f;
printf(“\na=%d”,a);
a=(b+c)/d+e*f;
printf(“\na=%d”,a);
a=b+c/((d+e)*f);
printf(“\na=%d”,a);
getch();
}
Lecture 10: Relational, Logical
16
Operators
BIT WISE OPERATORS
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0
Bit 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
position
a=4 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
b=5 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
a&b=4 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
a|b=5 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
a^b 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
~a 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1
~b 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0
a>>2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
a<<2 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0
21
Write a program to demonstrate all bitwise operators
a<=b
a==b
a<b?a:b a>=c
a!=b
• where the expressions are evaluated strictly from left to right and their values
discarded, except for the last one, whose type and value determine the result
of the overall expression.
• Example:
a = 10,20,30; //a=10
b = (10,20,30); //b=30
Assignment has higher priority than comma operator and brackets has higher
precedence than assignment operator.
34
Control Statements/Constructs in ‘C’
Program Control
Statements/Constructs
Selection/Branching Iteration/Looping
if- continu
if if-else
else-if
switch break e
goto
<
! >
!= Operator ==
s
<=
||
>=
&& !=
• Selection Statements
– One-way decisions using if statement
– Nested if-else
• Syntax • Flowchart
if(TestExpr)
{ T TestEx
F
stmtT; pr
……
}
stmtT
Algorithm C Program
1. START #include <stdio.h>
2. PRINT “ENTER TWO #include <conio.h>
NUMBERS” void main()
{
3. INPUT A, B int a, b, max;
4. IF A>B THEN MAX=A printf(“\nEnter 2 numbers”);
scanf(“%d %d ”, &a, &b);
5. IF B>A THEN MAX=B
if(a>b)
6. PRINT “LARGEST {
NUMBER IS”, MAX max=a;
7. STOP }
if(b>a)
{
max=b;
}
printf(“Largest No is %d”, max);
getch();
}
Algorithm C Program
1. START #include <stdio.h>
2. PRINT “ENTER THREE #include <conio.h>
NUMBERS” void main()
{
3. INPUT A, B, C int a, b, c, max;
4. MAX=A printf(“\nEnter 3 numbers”);
scanf(“%d %d %d”, &a, &b, &c);
5. IF B>MAX THEN MAX=B
max=a;
6. IF C>MAX THEN MAX=C if(b>max)
7. PRINT “LARGEST {
NUMBER IS”, MAX max=b;
}
8. STOP if(c>max)
{
max=c;
}
printf(“Largest No is %d”, max);
getch();
}
40 Lecture 12: Branchin: if, if..else
Two-way decisions using if-else statement
Syntax
• Flowchart
T F
if(TestExpr) TestExpr
{
stmtT;
}
else stmtT stmtF
{
stmtF;
}
Algorithm C Program
1. START #include <stdio.h>
2. PRINT “ENTER ONE NUMBER” void main()
{
3. INPUT A int a ;
printf(“\nEnter any number”);
4. IF A%2==0 THEN PRINT “NUMBER IS
scanf(“%d”, &a);
EVEN”
if(a%2==0)
5. ELSE PRINT “NUMBER IS ODD” {
6. STOP printf(“%d is EVEN number”,a);
}
else
{
printf(“%d is ODD number”,a);
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main () Output:
{ Enter year 2020
int year; 2020 is leap year
clrscr();
printf(“Enter year”);
scanf(“%d”,&year);
if(year%4==0)
printf(“%d is leap year\n“,year);
else
printf(“%d is not leap year\n“,year);
getch();
}
43
WAP to check whether entered number is positive or negative number.
#include<stdio.h>
#include<conio.h>
void main () Output:
{ Enter n -25
int n; -25 is negative number
clrscr();
printf(“Enter n”);
scanf(“%d”,&n);
if(n>0)
printf(“%d is positive number\n“,n);
else
printf(“%d is negative number\n“,n);
getch();
}
44
Practice Program
Faculty Name :
1
Index -
2
Module No: 3 CONTROL STRUCTURES
Lecture No: 13
Multiway decision Statement
Multi-way decisions Statement
Syntax
if(TestExpr1){
stmtT1;}
else if(TestExpr2){
stmtT2;}
else if(TestExpr3){
stmtT3;
.. .}
else if(TestExprN){
stmtTN;}
else{
stmtF;}
Algorithm
1. START
2. PRINT “ENTER ONE NUMBER”
3. Take INPUT for A
4. IF A>0 THEN
PRINT “NUMBER IS POSITIVE”
5. ELSE IF A==0 THEN
PRINT “NUMBER IS ZERO”
6. ELSE
PRINT “NUMBER IS NEGATIVE”
7. STOP
#include<stdio.h> else {
#include<conio.h> printf("Largest = %d", c);
}
void main() { getch();
int a,b,c; }
printf("Enter three numbers: \n");
scanf("%d%d%d", &a, &b, &c); Output:
if(a>b && a>c) { Enter three numbers:
printf("Largest = %d", a); 10
} 15
else if(b>a && b>c) { 32
printf("Largest = %d", b); Largest= 32
}
Lecture No: 14
switch-case Statement
The switch statement
Flowchart
Syntax
switch(expr)
{
case constant1: stmtList1;
break;
case constant2: stmtList2;
break;
case constant3: stmtList3;
break;
………………………….
………………………….
default: stmtListn;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int no1,no2,result,choice;
clrscr();
printf("Enter two numbers:");
scanf("%d %d",&no1,&no2);
printf("1.Add\n2.Subtract\n3.Multiply\n4.Divide\n5.Modulus\nEnter your
choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: result=no1+no2;
printf(“ Sum= %d",result);
break;
case 2:result=no1-no2;
printf("Difference= %d",result);
break;
case 3:result=no1*no2;
printf("Product= %d",result);
break;
Output
case 4: result=no1/no2; Enter two numbers:4
printf("Quotient= %d",result);
break; 7
case 5:result=no1%no2;
printf("Remainder= 1.Add
%d",result);
break; 2.Subtract
default: printf("Invalid
3.Multiply
choice");
} 4.Divide
getch(); 5.Modulus
}
Enter your choice:3
Product= 28
Lecture No: 14 : switch case
22
statement
Write a program to print week day name using switch case
#include <stdio.h>
#include <conio.h>
vooid main()
{
int day;
printf("Enter a number(1-7): ");
scanf("%d", &day);
switch(day)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
Lecture No: 14 : switch case
23
statement
Write a program to print week day name using switch case
case 4:
OUTPUT
printf("Thursday");
Enter a number(1-
break;
7): 5
case 5:
printf("Friday");
Friday
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
default:
printf("Invalid input! Please enter week
number between 1-7.");
}
getch();
}
Lecture No: 14 : switch case
24
statement
switch vs nested if
Lecture No: 15
Practice Programs
Write a C program to check whether a triangle is valid or not if angles are
given using if else.
#include<stdio.h>
else
#include<conio.h>
{
void main(){
int angle1, angle2, angle3, sum; printf("Triangle is not valid.");
clrscr(); }
printf("Enter three angles of triangle: \n"); getch();
scanf("%d%d%d", &angle1, &angle2, }
&angle3);
/*OUTPUT
sum = angle1 + angle2 + angle3; Enter three angles of triangle:
30
if(sum == 180 && angle1 > 0 && angle2 > 0 && 60
angle3 > 0) 90
{
Triangle is valid. */
printf("Triangle is valid.");
}
1. Write a C program to input character from user and check whether character is
uppercase or lowercase alphabet using if else.
2. Write a C program to find minimum between two numbers.
3. Write a C program to check whether a number is divisible by 5 and 11 or not.
4. Write a C program to input any alphabet and check whether it is vowel or consonant.
5. Write a C program to input month number and print number of days in that month.
6. Write a C program to input electricity unit charges and calculate total electricity bill
according to the given condition:
For first 50 units Rs. 0.50/unit
For next 100 units Rs. 0.75/unit
For next 100 units Rs. 1.20/unit
For unit above 250 Rs. 1.50/unit
An additional surcharge of 20% is added to the bill
Faculty Name :
1
Index -
2
Module No: 3 Control Structures
Lecture No: 16
Looping Statements- while,
do-while
Looping Statements
Explanation :
- A while loop evaluates the condition
- If the condition evaluates to true, the code inside
the while loop is executed.
- The condition is evaluated again.
- This process continues until the condition is false.
- When the condition evaluates to false, the loop
terminates.
#include <stdio.h>
Working of the Program : Assume base
#include <conio.h> m=2 and power n=4
void main()
Iterati Variab i <=
{ on le 4
Action
int m, n, i, result=1;
result is multiplied with base i.e.
printf("Enter base and 1st i=1 true 1*m = 1 *2 =2 & “i” is increased
power:"); i=2.
result is multiplied with base i.e.
scanf("%d%d",&m,&n); 2nd i=2 true 2*m =2*2 =4 & “i” is increased
for(i=1;i<=n;i++) i=3.
result=result*m; 3rd i=3 true
result is multiplied with base i.e.
4*m = 4*2 =8 & “i” is increased
printf("%d raise to %d is i=4.
%d",m,n,result); result is multiplied with base i.e.
getch(); Output : 4th i=4 true 8*m = 8*2 =32 & “i” is increased
i=5.
} Enter base and power:2
4
5th i=5 false For loop will be terminated
2 raise to 4 is 16
27 Lecture No: 17 : For Loop Statement
Program 5:
Q. WAP to generate “m” number of terms of
Fibonacci series.
for(i=1;i<=m;i++)
Fibonacci Series = 0, 1, 1, 2, 3, 5, 8 ......
{
#include <stdio.h> c=a+b;
#include <conio.h> a=b;
void main() b=c;
{ printf("%d\t",c);
}
int m, a, b, c, i;
getch();
printf("Enter limit:"); }
scanf("%d",&m);
Output :
a=0; Enter limit:6
b=1; 0 1 1 2 3 5 8 13
printf("\n%d\t%d\t",a,b);
28 Lecture No: 17 : For Loop Statement
Program 6:
Q. WAP to calculate sum of
given series. for(i=1;i<=m;i++)
x + x2 + x3 +............+ xm {
#include <stdio.h> term=term*x;
#include <conio.h> sum=sum+term;
void main() }
{ printf("Sum of
int i, x, m, term=1, sum=0; series=%d",sum);
getch();
printf("Enter the value of x:");
}
scanf("%d",&x); Output :
printf("Enter the limit:"); Enter the value of x:2
Enter the limit:4
scanf("%d",&m); Sum of series=30
29 Lecture No: 17 : For Loop Statement
Program 8:
Q. WAP to calculate sum of given
for(i=1;i<m;i++)
series.
{
c=sign*(float)a/b;
#include <stdio.h> sum=sum+c;
a++;
#include <conio.h>
b++;
void main() sign=-sign;
{ }
int i, a, b, m, sign=1; printf("Sum of
float c, sum=1.0; series=%.2f",sum);
printf("Enter the limit:"); getch();
scanf("%d",&m); } %.2f will print 2 nos
after decimal point
a=2;
Output :
b=3; Enter the limit:5
31 Lecture No: 17 : For Loop Statement Sum of series=0.88
Program 9:
Q. WAP to calculate sum of given
series.
for(i=1;i<=n;i++)
{
#include <stdio.h> f=f*i;
#include <conio.h> sum=sum+(1.0/(float)f);
void main() }
{ printf("Sum of
int i, n, f=1; series=%.3f",sum);
float sum=0.0; getch();
}
printf("Enter the limit:");
scanf("%d",&n); Output :
Enter the limit:4
Sum of series=1.708
32 Lecture No: 17 : For Loop Statement
Practice Programs
#include <stdio.h>
Q. WAP to print following pattern.
#include<conio.h>
void main()
* {
* * * int i, j, k, space, rows;
printf("Enter the number of rows:
* * * * * ");
* * * * * * * scanf("%d", &rows);
* * * * * * * * *
1
1 2 1 #include <stdio.h>
#include<conio.h>
1 2 3 2 1 void main()
1 2 3 4 3 2 1 {
1 2 3 4 5 4 3 2 1 int i, j, k, space, rows;
printf("Enter the number of
rows: ");
scanf("%d", &rows);
2
Module No: 3 CONTROL STRUCTURES
Lecture No: 19
break, continue and goto
statement
SPECIAL CONTROL STATEMENTS
“goto” statements
“break” statements
“continue” statements
Control Transfer
#include<stdio.h> • OUTPUT
#include<conio.h> Enter a number:20
void main() Enter a number:25
{ Enter a number:25
int n, total=0; Enter a number:30
clrscr(); Total=100
again:
printf("Enter a number:");
scanf("%d",&n);
total=total+n;
if(total<100)
goto again;
printf("Total=%d",total);
getch();
}
#include<stdio.h>
OUTPUT
#include<conio.h>
j= 1
void main()
j= 4
{
j= 9
int i,j;
j= 16
clrscr();
j= 25
for(i=1;i<10;i++)
j= 36
{
j= 49
j=i*i;
LOOP TERMINATED
if(j>50)
break;
printf(“j=%d”,j);
}
printf(“LOOP TERMINATED”);
getch();
}
• Syntax
continue ;
#include<stdio.h>
#include<conio.h> OUTPUT
void main() i= 1
i= 3
{ i= 5
int i; i= 7
clrscr(); i= 9
for(i=1;i<10;i++)
{
if(i%2==0)
continue;
printf(“i=%d”,i);
}
getch();
}
Lecture 19:continue, break and goto
13
statement
“break” and “continue” statements
break continue
Lecture No: 20
Practice program on loops
Write a program to Check given number is armstrong number or not.
#include<stdio.h> if(sum==copy)
{
#include<conio.h>
printf("Armstrong Number"); }
void main() { else
int sum=0,digit,x,copy; {
printf("Not an Armstrong Number");
clrscr();
}
printf("Enter a number:"); getch();}
scanf("%d",&x);
copy=x; OUTPUT
while(x!=0) { Enter a number:153
Armstrong Number
digit=x%10;
sum=sum+digit*digit*digit;
x=x/10;
} Lecture 20:Practice Programs on
17
Loops
Write a program to Check given number is prime number or not.
* #include<stdio.h>
#include<conio.h>
** void main()
*** {
**** int i,j,n;
clrscr();
*** printf("Enter the number of rows in the upper half:");
** scanf("%d",&n);
* for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
{
printf(" ");
}
for(k=1;k<=i;k++)
{
printf("*");
}
printf("\n");
Lecture 20:Practice Programs on
19
Loops
}
//lower half triangle
for(i=n-1;i>=1;i--)
{
for(j=1;j<=n-i;j++)
{
printf(" ");
}
for(k=1;k<=i;k++)
{
printf("*");
}
printf("\n"); }
getch();
}
#include<stdio.h>
*
#include<conio.h>
* * void main() {
* * * int i,j,n;
* * * * clrscr();
* * * * * printf("Enter the number rows in upper half:");
scanf("%d",&n);
* * * *
for(i=1;i<=n;i++)
* * * {
* * for(j=1;j<=n-i;j++)
* {
printf(" ");
}
for(j=1;j<=i;j++)
{
printf("* ");
}
22
Lecture 20:Practice Programs on printf("\n"); }
Loops
//lower half triangle
for(i=n-1;i>=1;i--)
{
for(j=1;j<=n-i;j++)
{
printf(" ");
}
for(j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
} getch();}
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Logic:
row 0 =1
row 1 = (0+1), (1+0) = 1, 1
row 2 = (0+1), (1+1), (1+0) = 1, 2, 1
row 3 = (0+1), (1+2), (2+1), (1+0) = 1, 3, 3, 1
row 4 = (0+1), (1+3), (3+3), (3+1), (1+0) = 1, 4, 6, 4, 1
row 5 = (0+1), (1+4), (4+6), (6+4), (4+1),(1+0) = 1, 5, 10, 10, 5, 1
row 6 = (0+1), (1+5), (5+10), (10+10), (10+5), (5+1), (1+0) = 1, 6, 15, 20, 15, 6, 1
#include<stdio.h>
lcm = ( num1 * num2 ) / gcd;
#include<conio.h>
void main(){
int num1, num2, gcd, lcm, i = 1, min; printf("GCD = %d\nLCM = %d\n", gcd, lcm);
printf("Enter 2 integer numbers\n");
scanf("%d%d", &num1, &num2); getch();
}
min = (num1 < num2) ? num1 : num2;
while(i <= min)
{ OUTPUT
if(num1 % i == 0 && num2 % i == 0) Enter 2 integer numbers
{ 20
gcd = i; 30
} GCD = 10
i++; } LCM = 60
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
clrscr();
printf("Enter the value for n ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{ if(i%2!=0)
{
printf("%d\n",i);
}
}
getch(); }
Lecture 20:Practice Programs on
29
Loops
Write a program to calculate
1+x+x2/2+x3/3 +……….. +xn/n
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,j;
float x,sum,p;
clrscr();
printf("Enter the value for x and n ");
scanf("%f%d",&x,&n);
sum=1.0;
p=1.0;
for(i=1;i<n;i++)
{
p=p*x;
sum=sum+(p/i);
}
printf("%f\n",sum);
Lecture 20:Practice Programs on
30
getch();
Loops}
Thank You
Subject Name: C Programming
Unit No:4
Unit 4: ARRAYS, STRING, STRUCTURE
AND UNION
Faculty Name : Mrs. Tabassum Maktum
32
Module No: 4 ARRAYS, STRING, STRUCTURE AND UNION
Lecture No: 21
Array-Concepts, Declaration,
Definition, Accessing array
element
Array : Introduction
• Can you imagine how long we have to write the declaration part
by using normal variable declaration?
• You can initialize array in C either one by one or using a single statement
as follows:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
int A[5]={1,2,3,4,5};
• The number of values between braces {} can not be larger than the
number of elements that we declare for the array between square
brackets [ ].
• If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write:
int A[]={1,2,3,4,5};
Here, Size of array is 5.
2
Module No:4 ARRAYS, STRING, STRUCTURE AND UNION
Lecture No: 22
One dimensional array
WAP to calculate minimum and maximum from list of numbers
#include<stdio.h> for(i=1;i<=n-1;i++)
#include<conio.h> {
void main() if(a[i]>max)
{ int n,i,a[100],x,index=0; {
int max,min; max=a[i];
clrscr(); }
printf("Enter the number of elements:"); else
scanf("%d",&n); {
printf("Enter array elements:"); min=a[i];
for(i=0;i<=n-1;i++) }
{ }
scanf("%d",&a[i]); printf(“max=%d and min=%d\n”, max,
} min);
max=a[0]; getch();
min=a[0] }
Output
Enter the number of elements: 5
Enter array elements:
5
3
2
1
4
max=5 and min=1
Output
Enter the number of elements: 5
Enter array elements:
10
11
12
13
14
Enter the element to be searched: 14
The element is found at position 5
#include<stdio.h> for(i=0;i<=n-1;i++)
#include<conio.h> {
void main() if(a[i]%2==0)
{ int {
n,i,a[100],x,index=0,even[100],odd[100]; even[k]=a[i];
int k=0,j=0; k++;
clrscr(); }
printf("Enter the number of elements:"); else
scanf("%d",&n); {
printf("Enter array elements:"); odd[j]=a[i];
for(i=0;i<=n-1;i++) j++;
{ }
scanf("%d",&a[i]); }
}
printf(“Even list:\n:");
Output
for (i = 0; i < j; i++ )
{ Enter the number of
printf(" %d\t", even[i] ); elements: 5
} Enter array elements:
printf(“Odd list:\n:");
for (i = 0; i < k; i++ )
53214
{ Even list: 2 4
printf(" %d\t", odd[i] ); Odd list: 5 3 1
}
getch();
}
Lecture No: 23
Multi-dimensional array
Multi-dimensional array
• Syntax:
datatype arrayname[size1][size2]...[sizeN];
Eg:-
int A[3][3];
char name[10][5];
float B[3][3];
int A[3][3];
COL
0 1 2
int A[][]={{1,2,3},
{4,5,6},
{7,8,9}};
Size of A is 3X3.
int B[][3]={{1,1,1},
{2,2,2}};
Size of B is 2X3.
for(i=0;i<row;i++) for(i=0;i<row;i++)
{ {
for(j=0;j<col;j++) for(j=0;j<col;j++)
{ {
scanf(“%d”,&A[i][j]); printf(“%d\t”,A[i][j]);
} }
} printf(“\n”);
}
Lecture No: 24
Practice programs on Array
WAP to count the number of even numbers in the array
#include<stdio.h> for(i=0;i<=n-1;i++)
#include<conio.h> { if(a[i]%2==0)
void main() {
{ int n,i,a[100]; count++;
int count=0; }
clrscr(); }
printf("Enter the number of elements:"); printf(“Number of even numbers=%d”,
scanf("%d",&n); count);
printf("Enter array elements:"); }
for(i=0;i<=n-1;i++) getch();}
{
Output
scanf("%d",&a[i]);
Enter the number of elements: 5
}
Enter array elements:
53214
Number of even numbers=2
Lecture 24 –Practice programs on
23
Array
Bubble sort
42 42 42 42 42 42
60 60 26 26 26 26
26 26 60 55 55 55
55 55 55 60 34 34
34 34 34 34 60 28
28 28 28 28 28 60
#include<stdio.h> for(i=0;i<n-1;i++)
{
#include<conio.h>
for(j=0;j<n-i-1;j++)
void main() {
{ if(a[j]>a[j+1])
int n,i,j,a[100],temp; {
temp=a[j];
clrscr(); a[j]=a[j+1];
printf("Enter the number of a[j+1]=temp;
elements:"); }
scanf("%d",&n); }
}
for(i=0;i<=n-1;i++)
printf("Sorted array is:\n:");
{ for (i = 0; i < n; i++ )
printf("Enter a value:"); {
printf(" %d\t", a[i] );
scanf("%d",&a[i]);
}
} }
Output
Enter the number of elements: 5
Enter array elements:
5
3
2
1
4
Sorted array is: 1 2 3 4 5
for(i=0;i<3;i++)
#include<stdio.h> {
#include<conio.h> for(j=0;j<i;j++)
void main() { temp=A[i][j];
{ A[i][j]=A[j][i];
int A[3][3],i,j,temp; A[j][i]=temp;
}
clrscr(); }
printf("ENTER ARRAY printf("transpose of Matrix is\n\n");
ELEMENTS\n"); for(i=0;i<3;i++)
for(i=0;i<3;i++) {
for(j=0;j<3;j++)
{ {
for(j=0;j<3;j++) printf("%d\t",A[i][j]);
{ }
scanf("%d",&A[i][j]); printf("\n");
}
} getch();
} }
#include<stdio.h> for(i=0;i<3;i++)
{
#include<conio.h>
for(j=0;j<3;j++)
void main() {
{ sum[i]=sum[i]+A[j][i];
int A[3][3],i,j,sum[3]={0}; }
clrscr(); }
printf("ENTER ARRAY printf("sum of column elements
ELEMENTS\n"); is\n\n");
for(i=0;i<3;i++) for(i=0;i<3;i++)
{ {
printf("%d\t",sum[i]);
for(j=0;j<3;j++)
}
{
scanf("%d",&A[i][j]); getch();
} }
}
#include<stdio.h> for(i=0;i<3;i++)
#include<conio.h> {
void main() for(j=0;j<3;j++)
{ { scanf("%d",&B[i][j]);
int A[3][3],B[3][3],C[3][3],i,j,k; }
clrscr(); }
printf("ENTER ARRAY ELEMENTS Printf(“Matrix multiplication is:\n);
FOR A\n"); for(i=0;i<3;i++)
for(i=0;i<3;i++) {
{ for(j=0;j<3;j++)
for(j=0;j<3;j++) { C[i][j]=0;
{ for(k=0;k<3;k++)
scanf("%d",&A[i][j]); {
} C[i][j]+=A[i][k]*B[k][j];
} }
printf("ENTER ARRAY ELEMENTS printf("%d\t",C[i][j]);
FOR B\n"); }
Lecture 24 –Practice programs on printf("\n");
35
Array }getch();}
output
2
Module No:4 Arrays, String, Structure and Union
Lecture No: 25
String- Basic of String,
Programs on String
Strings
• A string is nothing but the collection of characters.
• String is enclosed within Double quotes.
• String is terminated with a null character ’\0’.
• When the compiler encounters a sequence of characters enclosed in
the double quotation marks, it appends a null character ’\0’ at the end
by default.
• For example :
Consider “programming“ word as an example of String.
p r o g r a m m i n g \0
• For input
• For output
Lecture No: 26
String Handling Functions
Program 4 : Write a program that reads text from keyboard
and count the frequency of any particular character.
#include <stdio.h> printf("Frequency of %c :%d", ch,
#include<conio.h> count);
void main() getch();
{ }
char str[1000], ch;
Output :
int count = 0;
Enter a string: This website is
printf("Enter a string: ");
awesome.
gets(str);
Enter a character to find its
printf("Enter a character to find its
frequency: e
frequency: ");
Frequency of e : 4
scanf("%c", &ch);
for (int i = 0; str[i] != '\0'; ++i)
{ if (ch == str[i])
++count; }
19 Lecture 26 :String- Basic of String, Programs on String
String Handling Functions
Function Purpose Example Output
strcpy(); Makes a copy of a string strcpy(s1, “Hi”); Copies “Hi” to
‘s1’ variable
strcat(); Appends a string to the strcat(“Work”, Prints
end of another string “Hard”); “WorkHard”
Output :
Output string after concatenation:
HelloWorld
Output :
string 1 and 2 are different
27 Lecture 26 : String handling functions
String Length (strlen)
• strlen( ) function gives the length of the given string.
• strlen( ) function counts the number of characters in a given
string and returns the integer value.
• It stops counting the character when null character is
found. Because, null character indicates the end of the
string in C.
• Syntax :
strlen(str);
• Example :
str=“welcome”;
printf(“%d”, strlen(str));
It will print value as 7.
Output :
Length of string str: 14
• Syntax :
strlwr(str);
• Syntax :
strupr(str);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main() {
char a[50];
int i=0,l,cons=0,alpha,space=0,vowel=0,digit=0,sp=0,words=0;
printf("ENTER STRING : ");
gets(a);
strlwr(a);
puts(a);
l=strlen(a);
while(a[i]!='\0‘){
if(a[i]>='a'&& a[i]<='z')
{
if(a[i]=='a'||a[i]=='e'||a[i]=='i'||a[i]=='o'||a[i]=='u')
{ vowel++; }
else { cons++; } }
35
ENTER STRING : CP Program 1 3% & FE
else if(a[i]<='9'&&a[i]>='0')
cp program 1 3% & fe
{ digit++; }
else if(a[i]==' ')
NUMBER OF VOWELS= 3
{ space++; words++; }
NUMBER OF ALPHABATES= 11
else{sp++;}
NUMBER OF CONSONANTS= 8
i++; }
NUMBER OF DIGITS= 2
alpha=cons+vowel;
NUMBER OF SPACES= 5
printf("\nNUMBER OF VOWELS= %d",vowel);
NUMBER OF WORDS= 6
printf("\nNUMBER OF ALPHABATES=
NUMBER OF SPECIAL SYMBOLS= 2
%d",alpha);
printf("\nNUMBER OF CONSONANTS=
%d",cons);
printf("\nNUMBER OF DIGITS= %d",digit);
printf("\nNUMBER OF SPACES= %d",space);
printf("\nNUMBER OF WORDS=
%d",(words+1));
printf("\nNUMBER OF SPECIAL SYMBOLS=
%d",sp);
getch();}
36
Thank You
Module No:4 Arrays, String, Structure and Union
Lecture No: 27
Array of String
What is an Array of String?
Syntax
maximum length of each
– data_type string_array_name [size1] [size2]; string
• Example
char s1[5][30]; how many strings to
declare
char s2[5][10];
s[0] h e l l o \0
\0
s[1] h i
\0
s[2] C
\0
s[3] G o o d
\0
s[4] M o r n i n g
OUTPUT
Sorted Strings
Banglore
Calcutta
Chenai
Delhi
Mumbai
2
Module No:4 ARRAYS, STRING, STRUCTURE AND UNION
Lecture No: 28
Structure-declaration,
initialization
INRODUCTION
6
• A structure is declared by using the keyword struct followed
by an optional structure tag followed by the body of the
structure.
For the first and last sets of code, myStruct is a defined tag and can be
used later, but in the middle code, there is no tag, so there is no way to
reference more examples of this structure
ACCESSING THE MEMBERS OF STRUCTURE
Example:
struct myStruct {
a b and c can be accessed as :
int a;
s1.a
int b;
s1.b
float c;
s1.c
}s1,s2;
Conceptual View of memory allocated for instances s1 and s2
9
s1.a s1.b s1.c
instance s1
s2.a s2.b s2.c
instance s2
Initialization of Structures
10
• Structures can be initialized by one of the following ways
:
struct myStruct {
int a;
int b;
float c;
}s1={10,20,2.3};
OR
struct myStruct s1={10,20,2.3};
Demonstration Of Input And Output
#include<stdio.h>
#include<conio.h>
OUTPUT
struct myStruct{
Enter values for a , b and c
int a;
2
int b;
3
float c;
4.5
}s1;
void main()
a=2
{clrscr();
b=3
printf("Enter values for a , b and c");
c=4.500000
scanf("%d%d%f",&s1.a,&s1.b,&s1.c);
printf("\na=%d",s1.a);
printf("\nb=%d",s1.b);
printf("\nc=%f",s1.c);
getch();
}
11
Define a structure named ‘Person’ which will store id, name and address .
Write a program to display all these details.
12
13 OUTPUT
Enter ID : 1
Enter Name : Riyan
Enter Address : Airoli
PERSON INFORMATION :
ID = 1
NAME = Riyan
ADDRESS = Airoli
Module No:4 ARRAYS, STRING, STRUCTURE AND UNION
Lecture No: 29
Nested Structure, Array of
structure
Nested Structures
struct Person{
int id;
char name[20];
char address[30];
struct DOB{
int day;
int month;
int year;
}d1;
}p1;
void main()
{
clrscr();
17 printf("Enter ID :\n");
scanf("%d",&p1.id);
printf("Enter Name :\n");
scanf("%s",&p1.name);
printf("Enter Address :\n");
scanf("%s",&p1.address);
printf("Enter Date of Birth in dd/mm/yyyy form :\n");
scanf("%d%d%d",&p1.d1.day,&p1.d1.month,&p1.d1.year);
printf("\n PERSON INFORMATION :");
printf("\nID = %d",p1.id);
printf("\nNAME = %s",p1.name);
printf("\nADDRESS = %s",p1.address);
printf("\nDATE OF BIRTH = %d:%d:%d",p1.d1.day,p1.d1.month,p1.d1.year);
getch();
}
OUTPUT
18
Enter ID : 1
Enter Name : Riyan
Enter Address : Airoli
Enter Date of Birth in dd/mm/yyyy form : 31
5
2012
PERSON INFORMATION :
ID = 1
NAME = Riyan
ADDRESS = Airoli
DATE OF BIRTH = 31:5:2012
Arrays of Structures
19
The structure variable would be an array of objects, each of which
contains the member elements declared within the structure
construct.
Example:
struct Person{
int id;
char name[20];
char address[30];
}p1[5];
Or
struct Person p1[5];
Example: Arrays of Structures
20
Define a structure named ‘Person’ which will store id, name and address . Write a
program to display all these details for 5 persons.
Lecture No: 30
Practice programs on
Structure
Define a structure named ‘Student’ which will store id, name and subject
marks . Write a program to display all these details.
23
24 OUTPUT
Enter ID : 101
Enter Name : Harsh
Enter Marks : 90
PERSON INFORMATION :
ID = 101
NAME = Harsh
MARKS = 90
Define a structure named ‘Manager’ which will store mid, mname, department,
salary and address as a collection of building name, flat number, city. Write a
program to display all these details.
25
#include<stdio.h>
#include<conio.h>
struct Manager{
int mid;
char mname[20];
char department[20];
double salary;
struct address{
char building[20];
int flatno;
char city[20];
}a1;
}m1;
void main()
{
clrscr();
26 printf("Enter ID :\n");
scanf("%d",&m1.mid);
printf("Enter Name :\n");
scanf("%s",&m1.mname);
printf("Enter Salary :\n");
scanf("%f",&m1.salary);
printf("Enter Address in building name, flat no and city :\n");
scanf("%s%d%s",m1.a1.building,&m1.a1.flatno,m1.a1.city);
printf("\n PERSON INFORMATION :");
printf("\nID = %d",m1.pid);
printf("\nNAME = %s",m1.pname);
printf("\nSALARY = %f",m1.salary);
printf("\nADDRESS = %s,%d,%s", m1.a1.building,m1.a1.flatno,m1.a1.city);
getch();
}
OUTPUT
27
Enter ID : 101
Enter Name : Mr. Kulkarni
Enter Salary : 85000.00
Enter Address in building, flat no and city form : Sunrise
102
Mumbai
PERSON INFORMATION :
ID = 101
NAME = Mr. Kulkarni
SALARY = 85000.00
ADDRESS= Sunrise, 102, Mumbai
Define a structure named ‘Product’ which will store pid, pname ,price and date of
manufacturer as a collection of day, month and year . Write a program to display
all these details.
28
#include<stdio.h>
#include<conio.h>
struct Product{
int pid;
char pname[20];
double price;
struct DOM{
int day;
int month;
int year;
}d1;
}p1;
void main()
{
clrscr();
29
printf("Enter ID :\n");
scanf("%d",&p1.pid);
printf("Enter Name :\n");
scanf("%s",&p1.pname);
printf("Enter Price :\n");
scanf("%f",&p1.price);
printf("Enter Date of Manufacturer in dd/mm/yyyy form :\n");
scanf("%d%d%d",&p1.d1.day,&p1.d1.month,&p1.d1.year);
printf("\n PERSON INFORMATION :");
printf("\nID = %d",p1.pid);
printf("\nNAME = %s",p1.pname);
printf("\nPRICE = %f",p1.price);
printf("\nDATE OF MANUFACTURER =
%d:%d:%d",p1.d1.day,p1.d1.month,p1.d1.year);
getch();
}
OUTPUT
30
Enter ID : 101
Enter Name : Laptop
Enter Price : 45000.00
Enter Date of Manufacturer in dd/mm/yyyy form : 31
5
2012
PERSON INFORMATION :
ID = 101
NAME = Laptop
PRICE = 45000.00
DATE OF MANUFACTURE = 31:5:2012
Module No:4 ARRAYS, STRING, STRUCTURE AND UNION
Lecture No: 31
Union
UNION
32
• A union is a structure, all of whose members share the same
storage.
– The amount of storage allocated to a union is sufficient to hold its
largest member.
– At any given time, only one member of the union may actually reside
in that storage.
– Virtually all other methods for declaring and accessing unions are
identical to those for structures.
Declaration of Union
33
Example
34
Structure versus Union
35
STRUCTURE UNION
At any given time, all members of the At any given time, only one member
structure may reside in the storage. of the union may actually reside in
the storage.
2
Module No:5 Functions and Parameter
Lecture No: 32
Introduction of Function,
Defining a Function, Accessing
a Function,
Function Prototype
Review of Structured Programming
• function_name :
• This is the name given to the function
• it follows the same naming rules as that for any valid
variable in C.
• return_data_type:
• This specifies the type of data given back to the calling
construct by the function after it executes its specific task.
• data_type_list:
• This list specifies the data type of each of the variables.
Formal Arguments
Lecture No: 33
Passing Arguments to a
Function
Example :no argument, returns nothing
#include<stdio.h>
Function OUTPUT
void sum(); Prototype Enter two numbers6
void main() 7
{ sum of 6 & 7 = 13
sum(); Function Call
}
void sum() {
Function
int x, y, z; Definition
printf("Enter two numbers");
scanf("%d%d",&x,&y);
z=x+y;
printf("sum of %d & %d = %d ",x,y,z);
}
#include<stdio.h> Formal
Arguments OUTPUT
void sum(int x,float y);
Enter two numbers3
void main() 4
{ sum of 3 & 4 = 7
int a;
float b;
printf("Enter two numbers");
scanf("%d%f",&a,&b);
sum(a,b);
}
void sum(int x, float y) {
float z; Actual
z=x+y; Arguments
printf("sum of %d & %f = %f ",x,y,z); }
returns value
19 Lecture 32: Passing Arguments
Example :with argument & returns value
Return type
#include<stdio.h> OUTPUT
double sum(double, double); Enter two numbers2.5
void main(){ 6.7
Data type Sum=9.200000
double a,b,c; list
printf("Enter two numbers");
scanf("%lf%lf",&a,&b);
c=sum(a,b);
printf("Sum=%lf",c);
}
double sum(double x, double y) {
double z;
z=x+y;
return z;
}
returns value
20 Lecture 32: Passing Arguments
CALL BY VALUE MECHANISM
Example Example
Lecture No: 34
Practice Programs
WAP to calculate factorial of a number using function
Factorial of 6 = 720
#include <stdio.h>
int prime(int n) {
#include <conio.h>
void main() int i;
{ for(i=2;i<=n/2;i++)
int num,res=0;
{
clrscr();
printf("\nENTER A NUMBER: "); if(n%i!=0)
scanf("%d",&num); continue;
res=prime(num);
else
if(res==0)
printf("\n%d IS A PRIME NUMBER",num); return 1; }
else return 0; }
printf("\n%d IS NOT A PRIME
NUMBER",num);
getch();
Output
}
ENTER A NUMBER 7
7 IS A PRIME NUMBER
33 Lecture 34: Practice Programs
WAP to check whether given matrix is an identity matrix or not.
#include <stdio.h>
int Identity(int m[10][10],int r,int c);
void main () {
int a[10][10];
int i = 0, j = 0, row = 0, col = 0;
int flag = 0;
printf ("Enter the number of rows :");
scanf ("%d", &row);
printf ("Enter the number of columns :");
scanf ("%d", &col);
Lecture 35 – Recursion 3
2
Module No:5 Functions and Parameter
Lecture No: 35
Recursion
Recursion
• A function that calls itself is known as a recursive function. And,
this technique is known as recursion.
• For a problem to be written in recursive form, two conditions
are to be satisfied:
– It should be possible to express the problem in recursive
form
• Solution of the problem in terms of solution of the same
problem on smaller sized data
– The problem statement must include a stopping condition
to break out of the recursion, otherwise recursion will occur
infinite times.
• To prevent infinite recursion, if...else statement can be used
where one branch makes the recursive call, and other doesn't.
4 Lecture 35 – Recursion
How recursion works?
5 Lecture 35 – Recursion
Example: Factorial of Number Using Recursion
#include <stdio.h> long int fact (int n)
#include<conio.h> {
long int fact(int n); if(n == 1)
return (1);
void main( ) { else
int number; return (n * fact(n-1));
long int result; }
printf("Enter a positive integer: ");
scanf("%d", &number); Output :
result = fact(number); Enter a positive integer:4
printf("Factorial of %d = %d", Factorial of 4 = 24
number, result);
getch(); }
8 Lecture 35 – Recursion
long int fact (int n)
Execution of Recursion : {
if (n == 1)
24 return (1);
fact(4)
else
return (n * fact(n-1));
if (4 = = 1) return (1); }
else return (4 * fact(3));
6
if (3 = = 1) return (1);
else return (3 * fact(2));
2
if (2 = = 1) return (1);
else return (2 * fact(1));
1
if (1 = = 1) return (1);
9 Lecture 35 – Recursion
Program 1: Calculate sum of natural numbers using
Recursion.
#include <stdio.h> int sum(int n)
#include<conio.h> {
int sum(int n); if (n != 0)
// sum() function calls
void main( ) itself
{ return n + sum(n-1);
int number, result; else
printf("Enter a positive return n;
integer: "); }
Output :
scanf("%d", &number);
result = sum(number); Enter a positive integer:4
printf("sum = %d", result); sum = 10
getch(); }
Lecture 35 –Practice Program on
12
Recursion
Program 2: Calculate nm using Recursion.
#include <stdio.h> int cal_power(int n, int m)
int cal_power(int base, int power); {
void main( ) if(m == 0)
return (1);
{ else if(m == 1)
int base, power, result; return (n);
printf("Enter a base value: "); else
scanf("%d", &base); return (n *
cal_power(n, m-1));
printf("Enter a power value: ");
}Output :
scanf("%d", &power);
Enter a base value: 2
result = cal_power(base, power);
Enter a power value: 3
printf("%d raise to %d = %d", base, 2 raise to 3 = 8
power,result); }
Lecture 35 –Practice Program on
13
Recursion
Program 3: Calculate Fibonacci series using
Recursion.
#include <stdio.h> int fibonacci(int num)
int fibonacci(int); {
int main(void) if(num == 0 || num == 1)
return num;
{ else
int n, terms; return fibonacci(num-1) +
printf("Enter no. of terms: fibonacci(num-2); }
");
scanf("%d", &terms); Output :
for(n = 0; n <terms; n++) Enter no. of terms: 5
{
0 1 1 2 3
printf("%d\t",
fibonacci(n)); } }
Lecture 35 –Practice Program on
14
Recursion
Program 4: Display reverse of a number using
Recursion.
#include <stdio.h> int reverse(int num)
#include<conio.h> {
int rem;
int reverse(int n); if(num!=0)
int sum=0; {
void main(){ rem=num%10;
sum=sum*10+rem;
int number, rev; reverse(num/10);
printf("Enter a number: "); }
scanf("%d",&number); return(sum);
}
rev = reverse(number);
printf("The reverse of %d is : Output :
%d",number,rev); Enter a number: 142
getch (); } The reverse of 142 is:241
Lecture 35 –Practice Program on
15
Recursion
Program 5: Check entered number is Palindrome or
not using Recursion.
#include <stdio.h> int reverse(int num)
int reverse(int n); {
int sum=0; int rem;
void main(){ if(num!=0)
{
int number, sum;
rem=num%10;
printf("Enter a number: ");
sum=sum*10+rem;
scanf("%d",&number); reverse(num/10);
sum = reverse(number); }
if(number==sum) return(sum);
printf("The number %d is a }
palindrome.",number);
else Output :
printf("The number %d is not a Enter a number: 14241
palindrome.",number); } The number 14241 is a
Lecture 35 –Practice Program on
16
Recursion
palindrome.
Thank You
Subject Name: C Programming
Unit No:6 Pointer
2
Module No:6 Pointer
Lecture No: 37
Introduction to Pointer
What is a variable?
• Variable names are just the symbolic representation of a memory
location.
• Each variable must be defined before we use it inside the program.
• Why we have to declare variables?
– First reason is To allocate memory.
– Second reason is Instruct compiler how to treat this memory
location? As int or float...
• What happen when we declare variable:
int x;
x = 44;
x Variable
44 Value
1645 Address
1008 a[0]: ‘a’ 1009 a[1]: ‘b’ 1010 a[2]: ‘c’ 1011 a[3]: ‘\0’
1008 a[0]: ‘a’ 1009 a[1]: ‘b’ 1010 a[2]: ‘z’ 1011 a[3]: ‘\0’
int i = 5;
int *ptr;
i 5
ptr = &i;
printf(“i = %d\n”, i);
printf(“*ptr = %d\n”, *ptr); pt address of i
printf(“ptr = %p\n”, ptr);
r
Output:
value of ptr =
i=5 address of i
*ptr = 5 in memory
ptr = effff5e0
10 Lecture 37 – Introduction to Pointers 10
Pointer Concepts 1 :
#include<stdio.h> i 5 1
void main()
{
int* ptr, i; pt address of i
i = 5;
ptr = &i;
r
printf(“i=%d\n", i); Output:
printf("%d\n", *ptr); i=5
i = 1; *ptr = 5
printf(“i=%d\n", i); i=1
printf("%d\n", *ptr); *ptr = 1
}
• What’s ptr + 1?
• What’s ptr - 1?
Invalid operations!!!
•Syntax :
int **p; // pointer to a pointer which is pointing to an integer
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Lecture 38 – Pointer Arithmetic, Pointers to Pointers,
21 21
Pointers and Array
Pointer Arithmetic and Array
float a[4]; Data Table
Name Type Description Value
float *ptr;
a[0] float float array element (variable) ?
ptr = &(a[2]);
a[1] float float array element (variable) ?
*ptr = 3.14;
a[2] float float array element (variable) 3.14
ptr++;
a[3] float float array element (variable) ?
*ptr = 9.0;
ptr float * float pointer variable address of a[2]
ptr = ptr - 3;
*ptr float de-reference of float pointer variable 3.14
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Lecture 38 – Pointer Arithmetic, Pointers to Pointers,
22 22
Pointers and Array
Pointer Arithmetic and Array
float a[4]; Data Table
Name Type Description Value
float *ptr; a[0] float float array element (variable) ?
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Lecture 38 – Pointer Arithmetic, Pointers to Pointers,
27 27
Pointers and Array
Pointer Arithmetic and Array
float a[4]; Data Table
Name Type Description Value
float *ptr; a[0] float float array element (variable) 6.0
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Lecture 38 – Pointer Arithmetic, Pointers to Pointers,
28 28
Pointers and Array
Program on Pointer and Arrays :
#include <stdio.h>
Output:
int main()
*ptr = 3
{ *(ptr+1) = 4
int x[5] = {1, 2, 3, 4, 5}; *(ptr-1) = 2
int* ptr;
// ptr is assigned the address of the
third element
ptr = &x[2];
printf("*ptr = %d \n", *ptr);
printf("*(ptr+1) = %d \n", *(ptr+1));
printf("*(ptr-1) = %d", *(ptr-1));
return 0;
} Lecture 38 – Pointer Arithmetic, Pointers to Pointers,
29 29
Pointers and Array
Program on Pointers to Array
#include<stdio.h> Output :
#include<conio.h> 10
void main()
{ 20
int a[5]={10,20,30,40,50}; 30
int *ptr, i; 40
ptr=a; 50
for(i=0;i<5;i++)
{
printf("\n%d",*ptr);
ptr++;
}
getch();
}
Lecture 38 – Pointer Arithmetic, Pointers to Pointers,
30 30
Pointers and Array
Program : Sum of array elements using pointer
#include<stdio.h>
int main() Output :
{
int n, i, Tab[10], sum=0; Enter no. of elements:5
int *p;
printf("Enter no. of elements:"); 1
scanf("%d", &n);
for(i=0;i<n;i++) 2
scanf("%d", &Tab[i]);
3
p=Tab;
4
for (i = 0; i < n; i++) 5
{
sum += *p; Sum=15
p++;
}
printf(“Sum=%d\n", sum);
return 0;
}
Lecture No:
Storage Classes –Auto , Extern
, Static,Register
Scope Rules
void increment();
void main() Output
{
increment();
a=1 b=1
increment(); a=2 b=1
increment();
increment(); a=3 b=1
} a=4 b=1
void increment()
{
static int a;
int b=0;
b++;
a++;
printf(“\na=%d\t b=%d”,a,b);
}
Example