0% found this document useful (0 votes)
32 views548 pages

C Programming: Algorithms & Flowcharts

Uploaded by

Being INSANE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views548 pages

C Programming: Algorithms & Flowcharts

Uploaded by

Being INSANE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Subject Name: C Programming

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 : Introduction to Algorithm


2
and Flowchart
Course Overview
Sr. Hour Weightage* (in
Module CO
No. s %)
1. Introduction to Algorithm and 5 CO1 11.9%
Flowchart
2. Fundamentals of C-programming 6 CO2 14.3%

3. Control Structures 9 CO3 21.4%


4. Arrays, String , Structure and Union 11 CO4 28.6%

5. Functions and Parameter 6 CO5 14.3%


6. Pointer 5 CO6 11.9%

Lecture 1 : Introduction to Algorithm


3
and Flowchart
Index -

Lecture 1 - Turing Model, Von Neumann Model and Types of Programming Languages 6

Lecture 2 – Problem Solving and Algorithm 31

Lecture 3 - Flowchart and Pseudo Code 48

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 1 : Turing Model, Von Neumann Model and Types of


5
Programming Languages
Module No: 1 Introduction to Algorithm And Flowchart

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

input and processes it with a set of instructions (a program) to produce the


result as output.

Process

• A computer is designed to execute applications and provides a variety of


solutions through integrated hardware and software components.

7 Lecture 1:: Turing Model, Von Neumann Model and Types of


Programming Languages
Program

• Computer works with the help of programs and data.

• A program is a set of logically related instructions that is arranged in a

sequence that directs the computer in solving a problem tells the

computer what to do with data.

8 Lecture 1 – Neural Networks


Six Basic Computer Operations

1. A computer can receive (input) data


2. A computer can store data in memory
3. A computer can perform arithmetic and manipulate text
strings
4. A computer can compare the contents of two memory
locations and select one of two alternatives
5. A computer can repeat a group of operations
6. A computer can output information (processed data)
Computer Operations
Computational Model
• The common basis of programming language and computer
architecture is known as Computational Model.
• Provides higher level of abstraction(general idea) than the
programming language and the computer architecture
• It tells us how computer functions or runs.
• A computational model uses computer programs to simulate and
study complex systems using an algorithmic or mechanistic
approach and is widely used in a diverse range of fields.
• Basic Computational Models are :
- Turing
- Von Neumann

18 Lecture 1:: Turing Model, Von Neumann Model and Types of


Programming Languages
Computational Model

19 Lecture 1 – Neural Networks


Turing Model
• Alan Turing designed the model which is an abstract machine that processed the
symbols written on a strip of tape as the rules of the symbols defined in the table,
which defines the mathematical model of the computer.
• The Turing model is a fundamental machine model based on which modern,
general-purpose computer are designed.

20 Lecture 1:: Turing Model, Von Neumann Model and Types of


Programming Languages
Example :

21 Lecture 1:: Turing Model, Von Neumann Model and Types of


Programming Languages
Example :

22 Lecture 1:: Turing Model, Von Neumann Model and Types of


Programming Languages
Von Neumann Model
• Computers built on the Turing model store data in their memory
whereas John von Neumann proposed that, since program and
data are logically the same, programs should also be stored in the
memory of a computer.
• Von Neumann architecture is based on the stored-program
computer concept, where instruction data and program data are
stored in the same memory.
• It consist of a Control Unit, Arithmetic, and Logical Memory
Unit (ALU), Registers and Inputs/Outputs.

23 Lecture 1:: Turing Model, Von Neumann Model and Types of


Programming Languages
Von Neumann Basic Structure

24 Lecture 1:: Turing Model, Von Neumann Model and Types of


Programming Languages
Sequential execution of instructions
• A program in the Von Neumann model is made of a finite number
of instructions.
• Program and data are stored as binary patterns in memory—a
sequence of 0s and 1s.
• The control unit fetches one instruction from memory, decodes
it, then executes it.
• In other words, the instructions are executed one after another.
• Sequential execution of a program was the initial requirement of
a computer based on the Von Neumann model.

25 Lecture 1:: Turing Model, Von Neumann Model and Types of


Programming Languages
What is Programming

• Program – a very specific set of instructions (or


command lines) that making a computer do what
you want it to do
• Types of Program-
– System program
– Application program

• Programming – the process of creating a program


Types of Programming Languages
• A programming language defines a set of instructions that are compiled
together to perform a specific task by the CPU.
• These languages vary in the level of abstraction they provide from the
hardware.
• Some programming languages provide less or no abstraction while
some provide higher abstraction.
• Based on the levels of abstraction, they can be classified into two basic
categories:
1. Low-level language
2. High-level language

27 Lecture 1:: Turing Model, Von Neumann Model and Types of


Programming Languages
Low Level Languages
• The low-level language is a programming language that provides
no abstraction from the hardware, and it is represented in 0 or 1
forms, which are the machine instructions.

• The languages that come under this category are :

 Machine level language

 Assembly language

28 Lecture 1:: Turing Model, Von Neumann Model and Types of


Programming Languages
Computational Model: Revisited

29 Lecture 1 – Neural Networks


Machine Level Languages
• The machine-level language is a language that consists of a set of
instructions that are in the binary form 0 or 1.
• Creating a program in a machine-level language is a very difficult
task as it is not easy for the programmers to write the program in
machine instructions.
• A machine-level language is not portable as each computer has
its machine instructions, so if we write a program in one computer
will no longer be valid in another computer.
• The different processor architectures use different machine
codes.

30 Lecture 1:: Turing Model, Von Neumann Model and Types of


Programming Languages
Assembly Languages
• The assembly language contains some human-readable
commands such as
• MOV, ADD, SUB etc.
• It is easier to write and understand.
• As we know that computers can only understand the machine-
level instructions, so we require a translator that converts the
assembly code into machine code.
• The translator used for translating the code is known as an
assembler.
• The assembly language code is not portable because the data is
stored in computer registers, and the computer has to know the
different sets of registers.

31 Lecture 1:: Turing Model, Von Neumann Model and Types of


Programming Languages
Difference between Machine-Level language and
Assembly language
Machine-level language Assembly language
The machine-level language comes at The assembly language comes above
the lowest level in the hierarchy, so it the machine language means that it has
has zero abstraction level from the less abstraction level from the
hardware. hardware.
It cannot be easily understood by It is easy to read, write, and maintain.
humans.
The machine-level language is written in The assembly language is written in
binary digits, i.e., 0 and 1. simple English language, so it is easily
understandable by the users.
It does not require any translator as the In assembly language, the assembler is
machine code is directly executed by used to convert the assembly code into
the computer. machine code.
It is a first-generation programming It is a second-generation programming
32 Lecture 1:: Turing Model, Von Neumann Model and Types of
language. Programming Languages language.
High Level Language
• The high-level language is a programming language that allows a
programmer to write the programs which are independent of a particular
type of computer.
• The high-level languages are considered as high-level because they are
closer to human languages than machine-level languages.
• When writing a program in a high-level language, then the whole
attention needs to be paid to the logic of the problem.
• A compiler is required to translate a high-level language into a low-level
language.
• Examples : C, C++, Pascal

33 Lecture 1:: Turing Model, Von Neumann Model and Types of


Programming Languages
Difference between Low-Level language and High-
Level language
Low-level language High-level language
It is a machine-friendly language, i.e., the It is a user-friendly language as this language is
computer understands the machine language, written in simple English words, which can be
which is represented in 0 or 1. easily understood by humans.

The low-level language takes more time to It executes at a faster pace.


execute.
It requires the assembler to convert the assembly It requires the compiler to convert the high-level
code into machine code. language instructions into machine code.

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.

It is memory efficient. It is less memory efficient.


Debugging and maintenance are not easier in a Debugging and maintenance are easier in a high-
low-level language. level language.

35 Lecture 1:: Turing Model, Von Neumann Model and Types of


Programming Languages
Thank You
Module No: 1 Introduction to Algorithm And Flowchart

Lecture No: 2
Problem Solving and
Algorithm
Problem Solving

Problem solving is the act of defining a problem; determining


the cause of the problem; identifying, prioritizing, and
selecting alternatives for a solution; and implementing a
solution.

Lecture 2: Problem Solving and


38
Algorithm
Steps in program development/ Problem Solving

1. Define the problem


2. Outline the solution
3. Develop the outline into an algorithm
4. Test the algorithm for correctness
5. Code the algorithm into a specific programming
language
6. Run the program on the computer
7. Document and maintain the program

Lecture 2: Problem Solving and


39
Algorithm
Define the Problem

• Divide the problem into three components


(called IPO):
– Inputs – what do you have?
– Outputs – what do you want to have?
– Processing
• how do you go from inputs to outputs?

Lecture 2: Problem Solving and


40
Algorithm
Outline the Solution

• The major processing steps involved


• The major subtasks (if any)
• The major control structures (e.g. repetition loops)
• The major variables and record structures
• The mainline logic

Lecture 2: Problem Solving and


41
Algorithm
Develop the Outline into an Algorithm

• Algorithm is a set of precise steps that describe


exactly the tasks to be performed, and the order in
which they are to be carried out.

• Test data needs to be walked through each step in


the algorithm, to check that the instructions
described in the algorithm will actually do what
they are supposed to

Lecture 2: Problem Solving and


42
Algorithm
Steps in Problem Solving (Cont…)

• Write the programs in a specific programming


language

• Execute the program and get the desired output.

• Prepare the documentation.

Lecture 2: Problem Solving and


43
Algorithm
Representation of solution

• Pseudocode

• Algorithm

• Flowchart

Lecture 2: Problem Solving and


50
Algorithm
Pseudocode

• The term pseudocode means writing steps required to


perform a specific task, in any language that is spoken
across the globe.

• It is written in informal language.

• Pseudocode cannot be compiled nor executed, and


there are no real formatting or syntax rules.

Lecture 2: Problem Solving and


51
Algorithm
Algorithm

• An algorithm is a sequence of finite logical steps


required to perform a specific task.

• Algorithm is a set of precise steps that describe exactly


the tasks to be performed, and the order in which they
are to be carried out.

• It follows certain syntax.

Lecture 2: Problem Solving and


52
Algorithm
Characteristics of Algorithms
1. Finiteness: An algorithm must terminate in a finite number of
steps.
2. Definiteness: Each step of the algorithm must be precisely and
unambiguously stated.
3. Effectiveness: Each step must be effective, in the sense that it
should be primitive easily convert into program statement and
can be performed exactly in a finite amount of time.
4. Generality: The algorithm must be complete in itself so that it
can be used to solve problems of a specific type for any input
data.
5. Input/output: Each algorithm must take zero, one or more
quantities as input data produce one or more output values.

53 Lecture 2: Problem Solving and Algorithm


Example 1:

• Calculate the circumference and area of Circle


• Problem definition :IPO
– Input: radius
– Process: calculate circumference and area as
circumference = 2 * P I* radius
area=PI * radius ^ 2
– Output: circumference, area

Lecture 2: Problem Solving and


54
Algorithm
Example 1:Pseudocode

Begin program
get radius, PI
circumference = 2 * P I* radius
area=PI * radius * radius
display circumference, area
End program

Lecture 2: Problem Solving and


55
Algorithm
Example 1:Algorithm

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

Lecture 2: Problem Solving and


56
Algorithm
Example 2 :
Q. Define problem “To display addition of two numbers”.

Problem definition :IPO

Input: num1, num2

Process: calculate sum as sum=num1 + num2

Output: sum

57 Lecture 2: Problem Solving and Algorithm


Example 2 :
Q. Write an algorithm “To display addition of two numbers”.
Step 1 : Start.

Step 2 : Take input for two numbers num1 and num2

Step 3 : sum=num1+num2

Step 4 : Display sum.

Step 5 : Stop.

58 Lecture 2: Problem Solving and Algorithm


Example 3 :
Q. Define problem “to find the average of three numbers”.
Problem definition :IPO

Input: a, b, c

Process: calculate sum as sum=a+b+c


and average as avg =sum / 3

Output: avg.

59 Lecture 2: Problem Solving and Algorithm


Example 3 :
Q. Write an algorithm “to find the average of three
numbers”.
Step 1 : Start.

Step 2 : Take input for the numbers a, b, c.

Step 3 : Compute sum=a + b + c.

Step 4 : Compute avg=sum/3.

Step 5 : print value of 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

Input: Principal P, Number of years N and Rate of


interest R

Process: calculate Simple Interest as


SI=P*N*R/100

Output: Simple Interest SI


61 Lecture 2: Problem Solving and Algorithm
Example 4 :
Q. Write an algorithm “to calculate the simple interest using
the formula. Simple interest = P*N* R/100.”
Step 1 : Start.

Step 2 : Take input for P, N and R.

Step 3 : Calculate simple interest as SI= P* N* R/100

Step 4 : Print SI.

Step 5 : Stop.

62 Lecture 2: Problem Solving and Algorithm


Example 5 :
Q. Define Problem “to calculate the perimeter and area of
rectangle. Given its length and width. ”
Problem definition :IPO
Input: Length and width

Process: calculate perimeter as


perimeter=length*width
calculate area as
area=2*(length+width)

Output: Perimeter and area


63 Lecture 2: Problem Solving and Algorithm
Example 5 :
Q. Write an algorithm “to calculate the perimeter and area of
rectangle. Given its length and width. ”
Step 1 : Start.
Step 2 : Take input for length of the rectangle.
Step 3 : Take input for width of the rectangle.
Step 4 : Calculate perimeter of the rectangle using the
formula perimeter = 2* (length + width)
Step 5 : Calculate area of the rectangle using the formula
area = length *width.
Step 6 : Print perimeter.
Step 7 : Print area.
Step 8 : Stop.
64 Lecture 2: Problem Solving and Algorithm
Thank You
Module No: 1 Introduction to Algorithm And Flowchart

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 2 : Read two numbers X and Y.

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

• Or A flowchart is visual or graphical representation of an


algorithm that illustrates the sequence of operations to be
performed to get a solution.

• The flowcharts helps to analyze the problem and plan its solution
in a systematic and orderly manner.

• A flowchart when translated in to a proper computer language,


results in a complete program.

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.

Step 2 : Read the numbers a, b, c. Read the numbers


a, b and c
Step 3 : Compute the sum of a, b and c.

Step 4 : Divide the sum by 3. Calculate Sum = a + b + c

Step 5 : Store the result in variable Avg.


Calculate Avg = Sum / 3
Step 6 : Print the value of Avg.

Step 7 : Stop. Print value of Avg

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

Simple interest = P* N* R/100


Print value of
Step 4 : Print simple interest. Simple Interest

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

Read length and


width of rectangle

Calculate Perimeter =
2*(length +width)

Calculate area = length*width

Print value of
Perimeter and area

Stop
79 Lecture 3 Flowchart
Benefits of a flowchart

• It is easy to understand because of limited


symbols used
• It provides convenient and easy approach to
represent a solution to a problem
• It assists the user in reviewing and correcting the
solution
Limitations of Flowcharts
• Complex : The major disadvantage in using flowcharts is that when a
program is very large, the flowcharts may continue for many pages,
making them hard to follow.
• Costly : If flowcharts are to be drawn for huge application the time and
cost factor of program development may get out of proportion making it
costly.
• Difficult to Modify : Due to its symbolic nature any changes or
modification to a flowchart usually requires redrawing an entire logic
again and redrawing a complex flowchart is not a simple task.
• No Update : Usually programs are updated regularly. However the
corresponding update of flowcharts may not take place especially in the
case of large programs. As a result the logic in the flowchart may not
match with the actual program’s logic.

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

It contains step-by-step English The flowchart employs a series of


descriptions, each step blocks and arrows, each of which
representing a particular represents a particular step in an
operation leading to solution of algorithm
problem
These are particularly useful for These are useful for detailed
small problems representations of small
programs
For complex programs, For complex programs,
algorithms prove to be adequate Flowcharts prove to be
82 Lecture 3 Flowchart
inadequate
Thank You
Subject Name: C Programming
Unit No:1
Introduction to Algorithm and
Flowchart

1
Faculty Name : Dr. Gautam M Borkar
Index -

Lecture 4 – Flowchart with Sequence and Decision 3

Lecture 5 – Flowchart with Repetition 19

Lecture 6 – Structure of C program 35

2
Module No: 1 Introduction to Algorithm And Flowchart

Lecture No: 4
Flowchart with Sequence and
Decision
Three construct of Algorithm and flowchart

• The algorithm and flowchart can be classified to three types


of control structures.

1. Sequence

2. Branching (Selection)

3. Loop (Repetition)

Lecture 4 Flowchart with Sequence


4
and Decision
Flowchart : Sequence Construct
• The sequence is exemplified by sequence of statements place
one after the other – the one above or before another gets
executed first.
• In flowcharts, sequence of statements is usually contained in the
rectangular process box.
• A sequence construct tells the processors which statement is to be
executed next.
• In a sequence construct the program flow lines simply move
from one statement to the next.

Lecture 4 Flowchart with Sequence


5
and Decision
Flowchart : Sequence Construct (cont..)
• Sequence is the most basic form of
the constructs.
• It is simply performing one step
after another.
• Each step is followed in a specific
sequence, hence the name.
• Sequence can be thought of as
“do this, then do this, then do
this”.

Lecture 4 Flowchart with Sequence


6
and Decision
Example 4 :
Q. Write an algorithm and draw flowchart Start
“to swap two numbers”.
Read two numbers
Step 1 : Start.
num1 and num2
Step 2 : Read two numbers num1 and num2.
Step 3 : Declare temporary variable temp. temp = num1
Step 4 : Interchange the data num1 = num2
num2 = temp
temp = num1
num1 =num2 Print value of
num2 = temp num1 and num2

Step 5 : Print the value of num1 and num2.


Stop
Step 6 : Stop.
Lecture 4 Flowchart with Sequence
7
and Decision
Example 5 :
Q. Write an algorithm and draw flowchart “to convert temperature from
Celsius to Fahrenheit”. Start
Step 1 : Start.
Step 2 : Read temperature in Celsius. Read temperature in
Celsius
Step 3 : Calculate temperature in Fahrenheit
F = 32 + (centigrade * (1.8)) F = 32 + (centigrade * (1.8))
Step 4 : Display temperature in Celsius
and Fahrenheit.
Print temperature in
Step 5 : Stop. Celsius and Fahrenheit

Stop

Lecture 4 Flowchart with Sequence


8
and Decision
Flowchart : Decision Construct
• Flowchart with decision constructs refers to a binary decision based on
some condition specified in the problem.

• If the condition is true, one of the two branches is explored; if the


condition is false, the other alternative is taken.

• This is usually represented by the ‘if-then’ construct in pseudo-codes


and programs.

• In flowcharts, this is represented by the diamond-shaped decision box.

• This structure is also known as the selection structure.

Lecture 4 Flowchart with Sequence


9
and Decision
Flowchart : Decision Construct (cont..)
• Selection logic, also known as decision logic, is used for making decisions.

• Selection logic is depicted as either an IF…THEN…ELSE or IF…..THEN


structure.

• It is used to make yes/no or true/false decisions logically.

• Selection can be thought of as “if something is true, take this action,


otherwise take that action.

Lecture 4 Flowchart with Sequence


10
and Decision
Example 1 :
Start
Q. Write an algorithm “to print “YES” if number
is greater than 10”
Read the number X
Step 1 : Start.
No
Step 2 : Read one number X . Is
X >10
Step 3 : if X > 10 Yes
Print “YES”
Print as “YES”

Stop
Step 4: Stop.

Lecture 4 Flowchart with Sequence


11
and Decision
Example 2 :
Q. Write an algorithm “to find the largest of
two numbers X, Y.”
Start
Step 1 : Start.

Step 2 : Read two numbers X and Y. Read the numbers X


and Y
Step 3 : if X > Y

Print value of X as the largest number. No


Is X Print value
else >Y of Y
Yes
Print value of Y as the largest number.

Step 4 : Stop. Print value of X

Stop

Lecture 4 Flowchart with Sequence


12
and Decision
Example 3 :
Q. Write an algorithm “to find the
given number is even or odd.”
Step 1 : Start. Start

Step 2 : Read number say Num.


Step 3 : if Num mod 2 = 0 Read the number Num

Print “Number entered is even Is Print “Number


No
Num%2 entered is odd
number.”
=0 number.”
else Yes
Print “Number entered is odd
Print “Number entered is
number.” even number.”
Step 4 : 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

Print A Print C Print B

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

Bonus = 250 Bonus = 0.06*Salary

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 4 Flowchart with Sequence


17
and Decision
Thank You
Module No: 1 Introduction to Algorithm And Flowchart

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.

Lecture 5 Flowchart with Repetition


20
and Pseudo Code
Repetition (Loop) (cont..)
• Iteration comes from the word “reiterate”, which means to repeat
• Iteration is a combination of decision and sequence and can repeat steps
• Iteration can be thought of as “while something is true, do this, otherwise
stop”.
• Usually the loop has two important parts:
1. An expression that is tested for a true/false.
2. A statement or block that is repeated as long as the expression is true.

Lecture 5 Flowchart with Repetition


21
and Pseudo Code
Example 1 :
Q. Write an algorithm and draw flowchart “to find Start

sum of 1 to N numbers.” Read number N

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

Step 4 : repeat until i <=N Yes

Sum = Sum + i
Calculate Sum = Sum + i

Increment 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
22
and Pseudo Code
Example 3 :
Q. Write an algorithm and draw flowchart “to find sum of Start

square of 1 to N numbers i.e. 12+22+...... +N2 ”


Read number N
Step 1 : Start.
i = 1, Sum = 0
Step 2 : Read number N.

Step 3 : Initialize counter, i=1 and Sum=0 No


Is i≤ N
Step 4 : repeat until i <=N
Yes
Calculate Sum = Sum + ( i * i ) Sum = Sum + ( i * 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

even numbers from 1 to 20 numbers.” i=1

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

Lecture 5 Flowchart with Repetition


25
and Pseudo Code
Example 5 :
Q. Write an algorithm and draw flowchart “to display factorial of a Start
number.”
Step 1 : Start. Read number N

Step 2 : Read number N.


i = 1, f=1
Step 3 : Initialize counter, i=1 and f=1
Step 4 : repeat until i <=N No Is
Calculate f = f * i i≤ N
Yes
Increment counter, i = i + 1
f=f*i
Step 5 : Print value of f i.e. Factorial of N.

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 5 Flowchart with Repetition


27
and Pseudo Code
Thank You
Module No: 1 Introduction to Algorithm And Flowchart

Lecture No: 6
History of C Programming,
Benefits of C, Structure of C
program
History of C ProgrammingC Programming

Year Language Developed by Drawbacks


1960 ALGOL International Too general and too
Group abstract
1967 BCPL Martin Richard Less powerful and
too specific
1970 B Ken Thompson Too specific
1972 Traditional C Dennis Richie
1989 ANSI C ANSI Committee

1990 ANSI/ISO C ISO Committee

Lecture 6 :History of C Programming, Benefits of C, Structure of C


32
program
Benefits of C Programming
• Simple, versatile, general purpose
language
• Robust language, which can be used
to write any complex program.
• It has rich set of built-in functions
and Operators
• Program execution are fast and
efficient
• Well suited for writing both system
software and business applications
• Highly portable
• Well suited for structured
programming
• Dynamic memory allocation

Lecture 6 :History of C Programming, Benefits of C, Structure of C


33
program
Structured Programming Approach
• Generally the program is represented as a logical structure.
• C is called a structured programming language because it solves
a large problem by dividing the problem into smaller structural
blocks each of which handles a particular responsibility.

Lecture 6 :History of C Programming, Benefits of C, Structure of C


34
program
Structured Programming Approach (cont..)

• These structural blocks are –


 Decision making blocks like if-else, nested if-else, switch-
cases
 Repetitive blocks like For-loop, While-loop, Do-while loop
etc.
 Subroutines/Procedures – functions
• Structured programming is simple and easy to understand and
implement.
• Programmers do not require to know complex design concepts
to start a new program.
• Easier to Debug.
Lecture 6 :History of C Programming, Benefits of C, Structure of C
35
program
Stages of Compilation
• Like most high level languages C also uses compiler to convert its source code (files
with the extension .c) to object code (files with the extension .obj).
• The object code will be link-edited by the linker to form the machine language also
known as executable codes (files with the extension .exe).
Program edited in
C Program (*.c) Editor and stored on disk

Preprocessor program
processes the code
Preprocessor Creates object code
and stores on disk

Compiler

Loader puts program in Object Code Libraries


Memory and CPU Takes each
instruction and executes it Linker Editor
storing new data values. Links object code with
libraries and stores on disk

Executable Code (*.exe)


Lecture 6 :History of C Programming, Benefits of C, Structure of C
36
program
Structure of C Program
• A C program is divided into different sections as explained
below:
1. Documentation Section
2. Header File Section
3. Definition Section
4. Global Declaration Section
5. Main Section
6. Sub Program Section

Lecture 6 :History of C Programming, Benefits of C, Structure of C


37
program
Structure of C Program (cont..)
1. Documentation Section : The documentation section is the part of
the program where the programmer gives the details associated with
the program like name of the program, the details of the author ,
description etc.
Example :
/* Documentation Section */ Multiline comment
// File : Addition.c
// Description : Addition of two numbers Single Line
// Author : Student comment
2. Header File Section : This part of the code is used to declare all the
header files that will be used in the program. Compiler links the
header files to the system libraries.
Example :
#include<stdio.h>
#include<conio.h>

Lecture 6 :History of C Programming, Benefits of C, Structure of C


38
program
Structure of C Program (cont..)
3. Definition Section : In this section, we define different
constants. The keyword define is used in this part.
Example :
#define PI=3.14
4. Global Declaration Section : All the global variable used are
declared in this part. The user-defined functions are also
declared in this part of the code.
Example :
float area(float r);
int a=7;
Lecture 6 :History of C Programming, Benefits of C, Structure of C
39
program
Structure of C Program (cont..)
5. Main Section : Each main function contains 2 parts. A declaration
part and an Execution part. The declaration part is the part where
all the variables are declared. The execution part has actual logic.
Example :
/*main() section */
int main()
{
/* Declaration part */
int a, b, sum;
/* Execution part */
printf (“Enter two numbers:”);
scanf(“%d%d”, &a, &b);
sum= a+b;
printf(“Sum=%d”, sum);
}

Lecture 6 :History of C Programming, Benefits of C, Structure of C


40
program
Structure of C Program (cont..)
6. Sub Program Section : All the user-defined functions are
defined in this section of the program.

Example :
int add(int a, int b)
{
int d;
d=a+b;
return d;
}

Lecture 6 :History of C Programming, Benefits of C, Structure of C


41
program
C Preprocessor
• The C Preprocessor is not a part of the compiler, but is a
separate step in the compilation process.
• C Preprocessor is just a text substitution tool and it instructs the
compiler to do required pre-processing before the actual
compilation.
• All preprocessor commands begin with a hash symbol (#).
• It must be the first nonblank character, and for readability, a
preprocessor directive should begin in the first column.
• For example :
# include<header_filename>
 The #include directive will get a header file from System
Libraries and add the text to the current source file.
Lecture 6 :History of C Programming, Benefits of C, Structure of C
42
program
Simple C Program
Description of program in
/* A first C Program*/ multiline comment

#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 6 :History of C Programming, Benefits of C, Structure of C


43
program
Thank You
Subject Name: C Programming
Unit No:2
FUNDAMENTALS OF C-
PROGRAMMING

1 Faculty Name : Dr. Gautam M Borkar


Index -

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

Lecture 9 - Operators-Arithmetic, Relational 35

2
Module No: 2 FUNDAMENTALS OF C-PROGRAMMING

Lecture No: 7
Character Set, Identifiers and
keywords, Data types,
Constants, Variables
Tokens in c

• Tokens are the smallest elements of a program, which are


meaningful to the compiler.
• The following are the types of tokens in C:
• Character set
• Keywords
• Identifiers
• Constant and variables
• Data types
• Operators

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

• Arithmetic Operations: +, -, *, /, %(Mod)

• Special Characters:
(){}[]<>=!$?.,:;‘“&
| ^ ~ ` # \ blank - _ / * % @

5 Lecture 7: Tokens in C
Keywords

• Keywords are reserved words in any programming language.


• Keywords are written in lower case

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

• Identifiers are names given to different user defined things


like variables, functions ,constants etc.
• Rules to write identifiers:
– An Identifier is a sequence of letters and digits and special symbol,
Underscore ( _ )
– Always starts with a letter or underscore
– It can’t be a keyword.
– Identifiers are case sensitive.
– No blank space is allowed
• Example:
– Valid identifiers: Root, num1, _getchar, __sin, x1, x2, x3, x_1, If
– Invalid identifiers: 324, short, price$, My Name

7 Lecture 7: Tokens in C
Variables

• Variables represent names of memory locations during


program execution.
• Data values processed in the program are stored in memory
locations and referenced through variables.

• Example: int number=10;


10
number

8 Lecture 7: Tokens in C
Constant

• A constant is a named value.


• A constant cannot be reassigned a value.
Example
• #define SIZE 100
• #define PI 3.14

• The following are invalid:


– SIZE=200;
– PI=PI+2.5;
• The compiler replaces all occurrences of a constant by its
value

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:

Type Size(bytes) Range


int or 2 -32,768 to 32767
signed int
unsigned int 2 0 to 65535
short int or 1 -128 to 127
signed short int
unsigned short int 1 0 to 255
long int or 4 -2,147,483,648 to
signed long int 2,147,483,647
unsigned long int 4 0 to 4,294,967,295

13 Lecture 7: Tokens in C
Size and range of Float type on 16-bit machine

Type Size(bytes) Range


float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932

14 Lecture 7: Tokens in C
Size and range of Character type on 16-bit machine

Type Size(bytes) Range


char or 1 -128 to 127
signed char
unsigned char 1 0 to 255

15 Lecture 7: Tokens in C
Fundamental Data type

• void – used to denote the type with no values

• int – used to denote an integer type (4 byte/2 byte m/c dependent)


– Example: int marks=85;

• char – used to denote a character type(1 byte)


– Example: char grade=‘A’;

• float, double – used to denote a floating point/real numbers type(4


byte/8byte)
– Example: float price=10500.0;
double speedoflight=123456789.0;

16 Lecture 7: Tokens in C
Derived Data type

• Array – a finite sequence (or table) of variables of the same


data type
– Example: 1. store marks obtained by students
2. store name of the cities

• String – an array of character variables


– Example: 1. store name of the product,
2. store name of the city

• Structure – a collection of related variables of the same


and/or different data types.
– Example: 1. store name, roll number and marks of the student,
2. store name and price of the product

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

2. To calculate gross salary.


basic, hra, da, int type
Gross 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

3. To sort marks obtained by students in ascending order


marks, array of int type

4. To count number of vowels in the name of the city


count, int type
name, array of char type

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

• A library of functions is supplied to perform input and


output operations. The I/O library functions are listed
the “header” file <stdio.h>.

• You do not need to memorize them, just be familiar


with them.

21 Lecture 8: Data Input and Output


Streams

• All input and output is performed with streams.

• A "stream" is a sequence of characters organized into


lines.

• Each line consists of zero or more characters and ends


with the "newline" character.

22 Lecture 8: Data Input and Output


Types of Streams in C

• Standard input stream is called "stdin" and is normally


connected to the keyboard

• Standard output stream is called "stdout" and is normally


connected to the display screen.

• Standard error stream is called "stderr" and is also normally


connected to the screen.

23 Lecture 8: Data Input and Output


IO functions

Function Used for Data Type It


Works with
Formatted scanf() Input All
Functions printf() Output All

getchar() Input char


gets() Input char
Unformatted
Functions getc() Input char
putchar() Output char
putc() Output char
puts() Output char

24 Lecture 8: Data Input and Output


Formatted Output with printf

• 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

26 Lecture 8: Data Input and Output


Formatted input with scanf

• scanf ( ) statement:
– This function provides for formatted input from the keyboard.
– The syntax is:
scanf ( “format” , &var1, &var2, …) ;

– The “format” is a listing of the data types of the variables to be


input and the & in front of each variable name tells the system
WHERE to store the value that is input. It provides the address
for the variable.

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

27 Lecture 8: Data Input and Output


Demonstration of Data types in C

#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

printf("\nEnter value for num");


scanf("%d",&num); //6578
printf("\nnum=%d",num); //num=6578
printf("\nEnter value for salary");
scanf("%f",&salary); //23456.5
printf("\ngrade=%f",salary); //salary=23456.500000
printf("\nEnter value for speedoflight");
scanf("%lf",&speedoflight); //123456789.0
printf("\nspeedoflight=%lf",speedoflight);
//speedoflight=123456789.000000
printf("\nEnter value for weigthofcontainer");
scanf("%ld",&weightofcontainer); //987654321
printf("\nweightofcontainer=%ld",weightofcontainer);
//weightofconatiner=987654321
getch();
}

35
Thank You
Module No: 1 Introduction to Algorithm And Flowchart

Lecture No: 9
Operators-Arithmetic,
Relational
CLASSIFICATION:OPERATORS IN C

Lecture 9:Arithmetic and Relational


38
Operators
DIFFERENT OPERATORS

Lecture 9:Arithmetic and Relational


39
Operators
ARITHMETIC OPERATOR

• There are three types of arithmetic operators in


C:binary,unary, and ternary.
• Binary operators: C provides five basic arithmetic
binary operators.
Arithmetic binary operators:

Lecture 9:Arithmetic and Relational


40
Operators
Write a program to calculate area of circle

#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.

• Unary increment and decrement operators ‘++’ and ‘--’ operators


increment or decrement the value in a variable by 1.

• Basic rules for using ++ and – – operators:


 The operand must be a variable but not a constant or an expression.
 The operator ++ and -- may precede or succeed the operand.

Lecture 9:Arithmetic and Relational


44
Operators
POSTFIX

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.

Lecture 9:Arithmetic and Relational


45
Operators
PREFIX

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.

Lecture 9:Arithmetic and Relational


46
Operators
Increment and Decrement Operators

Example
Let b = 10 then
(++b)+b+b = 33
b+(++b)+b = 33
b+b+(++b) = 33
b+b*(++b) = 132

Lecture 9:Arithmetic and Relational


47
Operators
#include<stdio.h>
#include<conio.h>
void main ()
{
int x=4,y=9;
int z;
Output:
clrscr(); Value=20
z=(x++)+(--y)+y; Value=16
printf("Value=%d\n",z);
z=(--x)+x+(y--);
printf("Value=%d\n",z);
getch();
}

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

• The general form of an assignment operator ( = ) is


v3 = v1 op v2
or
v1 = v2
or
v=c
Where v, v1, v2, v3 are variables, c is constant and op is operator
Eg:-
a=b+c;
a=b;
s=10;

Lecture 9:Arithmetic and Relational


51
Operators
Arithmetic Assignment operators

The general form of an arithmetic assignment operator is


v op= exp
Where v is a variable and op is a binary arithmetic operator.
This statement is equivalent to
v = v op (exp)

• a=a+b can be written as a += b


• a=a*b can be written as a *= b
• a=a/b can be written as a /= b
• a=a–b can be written as a -= b

Lecture 9:Arithmetic and Relational


52
Operators
Thank You
Subject : C Programming
Unit 2: FUNDAMENTALS OF C-PROGRAMMING

Faculty Name : Dr. Gautam M Borkar


Index -

Lecture 10 – Relational, Logical, Conditional Operators 4

Lecture 11 - Bitwise, Comma, other operators, Expression,


16
statements

2
Lecture 10

Relational, Logical,
Conditional Operators
RELATIONAL OPERATORS

• C provides six relational operators for comparing numeric


quantities. Relational operators evaluate to 1, representing
the true outcome, or 0, representing the false outcome.

Lecture 10: Relational, Logical


4
Operators
WAP to demonstrate all 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

Lecture 10: Relational, Logical


5
Operators
LOGICAL OPERATORS

• C provides three logical operators for forming logical expressions. Like


the relational operators, logical operators evaluate to TRUE(nonzero)
or FALSE(zero).
 Logical negation is a unary operator that negates the logical value
of its single operand.
 If its operand is non-zero, it produces False (0), and if it is 0, it produces True(1).

 Logical AND produces False(0) if one or both its operands evaluate


to False(0). Otherwise, it produces True(1).

 Logical OR produces False(0) if both its operands evaluate to


False(0). Otherwise , it produces True(1).

Lecture 10: Relational, Logical


6
Operators
LOGICAL OPERATORS

P Q P&&Q P||Q !P

TRUE TRUE TRUE TRUE FALSE

TRUE FALSE FALSE TRUE FALSE

FALSE TRUE FALSE TRUE TRUE

FALSE FALSE FALSE FALSE TRUE

Lecture 10: Relational, Logical


7
Operators
LOGICAL OPERATORS

Lecture 10: Relational, Logical


8
Operators
WAP to demonstrate all logical operators

#include<stdio.h> // combined with relational operators


printf("a= %d \nb= %d \n",a,b);
#include<conio.h>
c=!(a<b);
void main () printf("c=: %d\n", c); //1
{ c=(a>b) || (a>11);
int a=10, b=5,c; printf("c=: %d\n", c); //1
int y=0, d=3, x; c= (a>b) && (b==6);
printf("c=: %d\n", c); //0
clrscr();
getch();
printf("y= %d \nd= %d \n",y,d); } Output
x=y && d;
y= 0
printf("x=: %d\n", x); //0 d=3
x=y || d; x=: 0
printf("x=: %d\n", x); //1 x=: 1
x=!d; x=: 0
a=10
printf("x=: %d\n", x); //0
b=5
c=:1
Lecture 10: Relational, Logical c=:1
9
Operators c=:0
CONDITIONAL OPERATOR /TERNARY OPERTOR

• The conditional operator has three expressions.


 It has the general form
expression1 ? expression2 : expression3

(Condition) ? (True statement) : (False statement)

 First, expression1 is evaluated; it is treated as a logical condition.


 If the result is non-zero, then expression2 is evaluated and its value
is the final result. Otherwise, expression3 is evaluated and its value
is the final result.

Lecture 10: Relational, Logical


10
Operators
CONDITIONAL OPERATOR

• For example,
int m = 1, n = 2, min;
min = (m < n ? m : n); /* min is assigned a value 1 */

• In the above example, because m is less than n, m<n


expression evaluates to be true, therefore, min is assigned
the value m, i.e., 1.

Lecture 10: Relational, Logical


11
Operators
Write a program to find minimum number among two numbers using ternary
operator

#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

• Write a program to display eligible if age is above 18


otherwise display not eligible using ternary operator.
• Write a program to find greater number among two
numbers using ternary operator.
• Write a program to check whether year is leap year or not
using conditional operator.
• Write a program to find smallest number among three
numbers using ternary operator.

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.

Lecture 10: Relational, Logical


15
Operators
EXAMPLE : OPERATOR 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

• C provides six bitwise operators for manipulating the individual


bits in an integer quantity . Bitwise operators expect their
operands to be integer quantities and treat them as bit sequences.
 Bitwise negation is a unary operator that complements the bits in
its operands.
 Bitwise AND compares the corresponding bits of its operands and
produces a 1 when both bits are 1, and 0 otherwise.
 Bitwise OR compares the corresponding bits of its operands and
produces a 0 when both bits are 0, and 1 otherwise.
 Bitwise exclusive compares the corresponding bits of its operands
and produces a 0 when both bits are 1 or both bits are 0, and 1
otherwise.

Lecture 1: Bitwise, comma,


19
expression and statememts
BITWISE OPERATORS

P Q P&Q P|Q P^Q ~P

0 0 0 0 0 1

0 1 0 1 1 1

1 0 0 1 1 0

1 1 1 1 0 0

Lecture 1: Bitwise, comma,


20
expression and statememts
Example

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

Enter two numbers:4


#include<stdio.h>
6
#include<conio.h> The AND of 4 and 6 is 4
void main (){ The OR of of 4 and 6 is 6
int a,b; The EXOR of of 4 and 6 is 2
clrscr(); The NOT of 4 is -5
The NOT of 6 is -7
printf("Enter two numbers:");
The right shift of 4 is 1
scanf("%d %d",&a,&b); The left shift of 6 is 24
printf("The AND of %d and %d is %d\n",a,b,(a & b));
printf("The OR of of %d and %d is %d\n",a,b,(a | b));
printf("The EXOR of of %d and %d is %d\n",a,b,(a ^ b));
printf("The NOT of %d is %d\n",a,~a);
printf("The NOT of %d is %d\n",b,~b);
printf("The right shift of %d is %d\n",a,(a>>2));
printf("The left shift of %d is %d\n",b,(b<<2));
getch();
}
Expressions in C a=b+c*d
a=b-c
a=p/q
a=c*d

a<=b
a==b
a<b?a:b a>=c
a!=b

a<=b && b<=c


a==b || b==c
!(a>=c)

Lecture 1: Bitwise, comma,


23
expression and statememts
COMMA OPERATOR

• This operator allows the evaluation of multiple expressions, separated by the


comma, from left to right in order and the evaluated value of the rightmost
expression is accepted as the final result.

• The general form of an expression using a comma operator is


Expression M = (expression1, expression2, …,expression N);

• 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.

Lecture 1: Bitwise, comma,


24
expression and statememts
Type Conversion

• C permits mixing of constants and variables of different types in an expression.


C automatically converts any intermediate values to the proper type so that
the expression can be evaluated without loosing any significance (implicit type
conversion).

Lecture 1: Bitwise, comma,


26
expression and statememts
Implicit type conversion

Lecture 1: Bitwise, comma,


27
expression and statememts
Explicit type conversion

• Sometimes we want to force a type conversion in a way that is different


from the automatic conversion.
• Example:
float ratio;
int females_number = 7;
int males_number = 5;
ratio = females_number / males_number; // the ratio will be 1
ratio = (float ) females_number / males_number; // the ratio is 1.4
• The operator (float) converts the females_number to floating point for
the purpose of evaluation of the expression.
• The general form of a cast (explicit conversion) is
(type-name)expression

Lecture 1: Bitwise, comma,


28
expression and statememts
Explicit type conversion/type casting

• Casting can be used to round-off a given value.


• Consider the following statement:
• x = (int) (y + 0.5);
• If y is 27.6, y+0.5 is 28.1 and on casting, the result becomes 28,
the value that is assigned to x.
Example Action
x = (int) 7.5 7.5 is converted to integer by truncation.
a = (int) 21.3 / (int) 4.5 Evaluated as 21/4 and result would be 5.
b = (double) sum/n Division is done in floating mode.
y = (int) (a + b) The result of a + b is converted to integer
z = (int) a + b a is converted to integer and the added to b
p = cos((double) x) Converts x to double before using it.

Lecture 1: Bitwise, comma,


29
expression and statememts
Statement

• Type declaration statement:


– to declare type of data used in program
– eg:- int num;
• Input/Output statement
– to take input and display result
– eg:- scanf and printf statement;
• Arithmetic statements
– to perform computation on input data
– eg:- a=b+c
• Control statements
– to take decision based on the data values
– eg:- if(a<b)

Lecture 1: Bitwise, comma,


30
expression and statememts
Subject : C Programming
Unit 3: CONTROL STRUCTURES

Faculty Name : Mrs. Tabassum Maktum


Lecture 12

Branching - if statement, if-


else Statement
Index -

Lecture 12 – Branching - if statement, if-else Statement 30

34
Control Statements/Constructs in ‘C’

Program Control
Statements/Constructs

Selection/Branching Iteration/Looping

Conditional Unconditional do-


for while
Type Type while

if- continu
if if-else
else-if
switch break e
goto

35 Lecture 12: Branchin: if, if..else


OPERATORS USED IN CONTROL STATEMENTS

<
! >

!= Operator ==
s
<=
||
>=
&& !=

36 Lecture 12: Branchin: if, if..else


Conditional Execution and Selection

• Selection Statements
– One-way decisions using if statement

– Two-way decisions using if-else statement

– Multi-way decisions USING if-else-if ladder

– Nested if-else

• The switch Statement

37 Lecture 12: Branchin: if, if..else


One-way decisions using if statement

• Syntax • Flowchart
if(TestExpr)
{ T TestEx
F
stmtT; pr
……

}
stmtT

38 Lecture 12: Branchin: if, if..else


Write a program that prints the largest among two numbers.

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();
}

39 Lecture 12: Branchin: if, if..else


Write a program that prints the largest among three numbers.

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;
}

41 Lecture 12: Branchin: if, if..else


Write a program to check given number is even or odd

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();
}

42 Lecture 12: Branchin: if, if..else


WAP to check whether the year entered is leap year or not.

#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

1. WAP to check whether the number entered is divisible by 10 or not.

2. WAP to check whether the given number is a three digit number or


not.

3. WAP to find minimum number from given two numbers.

4. WAP to find maximum number from given two numbers.

45 Lecture 12: Branchin: if, if..else


Thank You
Subject Name: C Programming
Unit No:3
Unit 3: CONTROL STRUCTURES

Faculty Name :
1
Index -

Lecture 13 – Multiway decision statements 3

Lecture 14 – switch statement 18

Lecture 15 – Practice progrms 30

2
Module No: 3 CONTROL STRUCTURES

Lecture No: 13
Multiway decision Statement
Multi-way decisions Statement

• When a series of decisions are involved we have to use


more than one if – else statement called as multiple if’s.

• if-else-if statement is also known as if-else-if ladder.

• It is used when there are more than two possible action


based on different conditions.

• Multiple if – else statements are much faster than a series


of if – else statements, since the if structure is exited when
any one of the condition is satisfied.

Lecture No: 13: Multiway Decision


4
Statement
Multi-way decisions Statement continued..

Syntax
if(TestExpr1){
stmtT1;}
else if(TestExpr2){
stmtT2;}
else if(TestExpr3){
stmtT3;
.. .}
else if(TestExprN){
stmtTN;}
else{
stmtF;}

Lecture No: 13: Multiway Decision


5
Statement
Flowchart of an if-else-if Construct
No
TestExpr
No
TestExpr2
Yes
No
Yes TestExpr3
stmtT1
No
stmtT2 Yes TestExprN

stmtT3 Yes stmt


TF
stmtTN

Lecture No: 13: Multiway Decision


6
Statement
1. Write a program to check given number is zero, positive, or
negative

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

Lecture No: 13: Multiway Decision


7
Statement
Write a program to check given number is zero, positive, or
negative

#include <stdio.h> else


#include <conio.h> {
void main() printf(“%d is NEGATIVE
{ NUMBER\n”,a);
int a ; }
printf(“\nEnter any number”); getch();
scanf(“%d”, &a); }
if(a>0)
{
printf(“%d is POSITIVE NUMBER\n”,a);
} Output:
else if(a==0) Enter any number :
{ -13
printf(“%d is NUMBER IS ZERO\n”, a);
}
-13 is NEGATIVE NUMBER

Lecture No: 13: Multiway Decision


8
Statement
2. Write a program to find largest from three numbers.

#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: 13: Multiway Decision


9
Statement
Nested if-else

 When any if statement is written Construct 1 Construct 2


under another if statement, this
cluster is called a nested if. if(TestExprA) if(TestExprA)
{ {
 The syntax for the nested is given if(TestExprB) if(TestExprB)
here:
{stmtBT;} {stmtBT;}
else else
{stmtBF;} { stmtBF;}
} }
else else{
{ stmtAF; if(TestExprC)
} { stmtCT;}
else
{stmtCF;}
10
Lecture No: 13: Multiway Decision
Statement
}
3 . Write a program to find the largest among three
numbers using the nested loop

Lecture No: 13: Multiway Decision


11
Statement
3 . Write a program to find the largest among three
numbers using the nested loop

#include <stdio.h> else{


#include <conio.h> if(b > c)
{ printf(“Largest= %d”, b);}
void main() else
{ { printf(“Largest= %d”, c); }
int a, b, c; }
printf(“\nEnter three numbers:\n”); getch();
scanf(“%d %d %d”, &a, &b, &c); }
if(a > b){
if(a > c) Output:
{ printf(“Largest= %d”, a);} Enter three numbers:
else 45
{ printf(“Largest= %d”, c); }
15
}
32
Largest= 45
Lecture No: 13: Multiway Decision
12
Statement
Summary of Decision Making Statement

• Decision making or branching statements are used to


select one path based on the result of the evaluated
expression.
• It is also called as control statements because it controls
the flow of execution of a program.
• We can also nest if-else within one another when multiple
paths have to be tested.
• The else-if ladder is used when we have to check various
ways based upon the result of the expression.

Lecture No: 13: Multiway Decision


13
Statement
Thank You
Module No: 3 CONTROL STRUCTURES

Lecture No: 14
switch-case Statement
The switch statement

• The switch case statement is used when we have multiple


options and we need to perform a different task for each
option.
• The switch statement allows us to execute one code block
among many alternatives.
• The expression is evaluated once and compared with the
values of each case label. If there is a match, the
corresponding statements after the matching label are
executed.
• If there is no match, the default statements are executed.

Lecture No: 14 : switch case


16
statement
The switch statement

Flowchart
Syntax
switch(expr)
{
case constant1: stmtList1;
break;
case constant2: stmtList2;
break;
case constant3: stmtList3;
break;
………………………….
………………………….
default: stmtListn;
}

Lecture No: 14 : switch case


17
statement
Few pointes o remember about the switch statement

• The switch expression must be of an integer or character type.


• The case value must be an integer or character constant.
• The expression provided in the switch should result in a constant
value otherwise it would not be valid.
• Duplicate case values are not allowed
• Break statements are useful when you want your program-flow
to come out of the switch body.
• Whenever a break statement is encountered in the switch body,
the control comes out of the switch case statement.
• If we do not use break, all statements after the matching label
are executed.

Lecture No: 14 : switch case


18
statement
Few pointes o remember about the switch statement

• The default statement is optional, if you don’t have a


default in the program, it would run just fine without any
issues.
• However it is a good practice to have a default statement
so that the default executes if no case is matched.

Lecture No: 14 : switch case


19
statement
Write a menu driven program to perform all arithmetic operations based on user
choice

#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);

Lecture No: 14 : switch case


20
statement
Write a menu driven program to perform all arithmetic operations based on user
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;

Lecture No: 14 : switch case


21
statement
Write a menu driven program to perform all arithmetic operations based on user
choice

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

 The switch differs from the else-if in that switch can


test only for equality, whereas the if conditional
expression can be of a test expression involving any
type of relational operators and/or logical
operators.

 The switch statement can always be replaced with


a series of else-if statements.

Lecture No: 14 : switch case


25
statement
Thank You
Module No: 3 CONTROL STRUCTURES

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.");
}

28 Lecture No: 15: Practice Programs


Write a C program to input a character from user and check whether the
given character is alphabet or not
#include<stdio.h> else
#include<conio.h> {
printf("Character is NOT
void main() ALPHABET.");
{ }
char ch;
getch();
}
printf("Enter any character: "); /*
scanf("%c", &ch); OUTPUT
Enter any character: g
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) Character is an ALPHABET.*/
{
printf("Character is an ALPHABET.");
}

29 Lecture No: 15: Practice Programs


Write a C program to input cost price and selling price of a product and check
profit or loss.

#include<stdio.h> else if(cp > sp)


#include<conio.h> {
void main() amt = cp - sp;
printf("Loss = %d", amt);
{ }
int cp,sp, amt; else
clrscr(); {
printf("Enter cost price: "); printf("No Profit No Loss.");
scanf("%d", &cp); }
printf("Enter selling price: ");
scanf("%d", &sp); getch();
}
if(sp > cp) { /*OUTPUT
amt = sp - cp; Enter cost price: 5000
printf("Profit = %d", amt); Enter selling price: 8000
} Profit = 3000 */

30 Lecture No: 15: Practice Programs


Write a program to input basic salary of an employee and calculate gross salary according to given conditions.
Basic Salary <= 10000 : HRA = 10%, DA = 80%
Basic Salary is between 10001 to 30000 : HRA = 20%, DA = 90%
Basic Salary >= 30001 : HRA = 30%, DA = 95%

#include <stdio.h> else {


#include<conio.h> da = basic * 0.95;
void main() hra = basic * 0.3;
{ }
float basic, gross, da, hra; gross = basic + hra + da;
clrscr();
printf("Enter basic salary of an employee: ");
printf("GROSS SALARY OF
scanf("%f", &basic); EMPLOYEE = %f", gross);
if(basic <= 10000) { getch();
da = basic * 0.8; }
hra = basic * 0.1;
/*OUTPUT
}
Enter basic salary of an employee:
else if(basic <= 30000) { 10000
da = basic * 0.9;
GROSS SALARY OF EMPLOYEE =
hra = basic * 0.2; 19000.000000 */
}
else

31 Lecture No: 15: Practice Programs


Write a program to input an alphabet and check whether it is vowel or
consonant using switch case.

#include <stdio.h> case 'A':


#include <conio.h> case 'E':
case 'I':
void main() case 'O':
{ case 'U':
printf("Vowel");
char ch; break;
clrscr();
printf("Enter any character: "); default: printf("Consonant");
ch=getchar(); }
switch(ch)
{ getch();
}
case 'a':
case 'e':
case 'i': /*Output:
case 'o': Enter any character: g
case 'u': Consonant
*/

32 Lecture No: 15: Practice Programs


Write a program to display grade of a student base on marks.
Grade A : 80-100 , Grade B: 60-79, Grade C : 40-59 Fail: 0-39
#include<stdio.h> case 5 :
void main() case 4 :
{ printf("\n Your Grade is: C" );
int marks, n; break;
case 3 :
printf("\nEnter The Marks Between 0 To case 2 :
100:"); case 1 :
printf("\nEnter The Mark: "); case 0 :
scanf("%d", &marks); printf("\n You Grade is: F or Fail\n");
n=marks/10; break;
switch(n) { default :
case 10 : printf("\n Enter proper marks \n");
case 9 : }
case 8 : getch();
printf("\n Your Grade is: A"); }
break;
case 7 : /*Output
case 6 : Enter The Marks Between 0 To 100:
printf("\n Your Grade is: B" ); Enter The Mark: 89
33 break;
Lecture No: 15: Practice Programs Your Grade is: A */
Practice Programs

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

34 Lecture No: 15: Practice Programs


Thank You
Subject Name: C Programming
Unit No:3
Unit 3: Control Structures

Faculty Name :
1
Index -

Lecture 16 – Looping Statments, while, do-while 3

Lecture 17 – For Loop 20

Lecture 18 – Nested Control Structures 35

2
Module No: 3 Control Structures

Lecture No: 16
Looping Statements- while,
do-while
Looping Statements

•In computer programming, loops are used to repeat a block


of code.
• For example, let's say we want to show a message 100
times. Then instead of writing the print statement 100 times,
we can use a loop.

• With the effective use of loops we can achieve much more


efficiency (in terms of time).

Lecture No: 16 t Looping Statements,


4
while, do-while
Types of Looping Statements

There are 3 types of


loops :
1. while loop
2. do…while loop
3. for loop

Lecture No: 16 t Looping Statements,


5
while, do-while
While Loop Statement
 Syntax :
while (condition)
{ // body of the loop }

 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.

Lecture No: 16 t Looping Statements,


6
while, do-while
Flowchart of while Loop Statement

Lecture No: 16 t Looping Statements,


7
while, do-while
Program 1 :
Q. Write a program to find sum of 1 to 10
numbers.
#include <stdio.h> Output :
#include <conio.h> The sum is 55.
void main()
{
int i = 1; //initialize counter i to 1
int sum = 0;
while (i <= 10) // repeat till we reach limit
{
sum += i; // add number
i++; //increment counter by 1
} // end of while
printf("\nThe sum is %d.",sum);
getch();
}
Lecture No: 16 t Looping Statements,
8
while, do-while
Program 3 :Q. Write a program to calculate reverse of a
number.
#include <stdio.h>
Output :
#include <conio.h> Enter a number:
void main() { 123
int num; The reverse of number is 321.
int rev = 0, rem;
printf("Enter a number:\n");
scanf("%d",&num);
while (num != 0) //repeat till number becomes 0
{
rem=num%10; //separates digits from number
rev = rev*10 + rem; //calculate reverse of number
num=num/10; //number gets updated
} // end of while
printf("\nThe reverse of number is %d.",rev);
getch();
}
Lecture No: 16 t Looping Statements,
10
while, do-while
Program 4 :
Q. WAP to check number entered by user is Armstrong or not.
Note : Number is called Armstrong if sum of cube of digits of the
number is equal to number itself. Ex. 153 = 13 + 53 + 33
#include <stdio.h>
#include <conio.h>
void main()
{
int num, temp;
int sum = 0, rem;
printf("Enter a number:\n");
scanf("%d",&num);
temp=num; //make a copy of number

Lecture No: 16 t Looping Statements,


11
while, do-while
Output :
Enter a number:
Program 4 : (cont..) 153
153 is Armstrong number.

while (num != 0) //repeat till number becomes 0


{
rem=num%10; //separates digits from number
sum = sum + (rem*rem*rem); //calculates sum
num=num/10; //number gets updated
} // end of while
if(temp==sum)
printf("\n%d is Armstrong number.",temp);
else
printf("\n%d is not Armstrong number.",temp);
getch(); }
Lecture No: 16 t Looping Statements,
12
while, do-while
Do...While Loop Statement
 Syntax :
do
{ // body of loop; }
while (condition);
 Explanation :
 The body of the loop is executed at first. Then the condition is evaluated.
 If the condition evaluates to true, the body of the loop inside
the do statement is executed again.
 The condition is evaluated once again.
 If the condition evaluates to true, the body of the loop inside
the do statement is executed again.
 This process continues until the condition evaluates to false. Then the
loop stops.
 Though condition is not true for first iteration , the loop will be executed
once.

Lecture No: 16 t Looping Statements,


13
while, do-while
Flowchart of do..while Loop Statement

Lecture No: 16 t Looping Statements,


14
while, do-while
Program 1 :
Q. Write a program to find sum of 1 to 10
numbers.
#include <stdio.h> Output :
#include <conio.h> The sum is 55.
void main()
{
int i = 1; //initialize counter i to 1
int sum = 0;
do
{
sum += i; // add number
i++; //increment counter by 1
} while (i <= 10); // end of do...while
printf("\nThe sum is %d.",sum);
getch();
}
Lecture No: 16 t Looping Statements,
15
while, do-while
Program 3 :Q. Write a program to display table of any number
entered by user.
Output :
#include <stdio.h> Enter a number:6
#include <conio.h>
void main() Table of 6:
{ 6 * 1 = 6
int i = 1; //initialize counter i to 1 6 * 2 = 12
int num; 6 * 3 = 18
6 * 4 = 24
printf("Enter a number:");
6 * 5 = 30
scanf("%d",&num);
6 * 6 = 36
printf("\nTable of %d:\n",num);
6 * 7 = 42
do 6 * 8 = 48
{ 6 * 9 = 54
printf("%d\t*\t%d\t=\t%d\n",num,i,num*i); 6 * 10 = 60
i++; //increment counter by 1
} while (i <= 10); // end of do..while
getch(); }

Lecture No: 16 t Looping Statements,


17
while, do-while
Difference between while and do..while
while do-while
Syntax: Syntax:
while(test expression) do
{ statement } { statement
} while(test expression);
Condition is checked first and then Statement is executed at least once
statement is executed. Hence it is thereafter condition is checked. Hence
entry controlled loop. it is exit controlled loop.
This is pre test loop. This is post test loop.
If condition is not true, for first Though condition is not true for first
iteration the loop will never get iteration , the loop will be executed
executed. once.
No semicolon is given after while While statement ends with semicolon.
statement.
Lecture No: 16 t Looping Statements,
18
while, do-while
For Loop Statement
 The for allows us to specify three things about a loop in a single line:
(a) Setting a loop counter to an initial value.
(b) Testing the loop counter to determine whether its value has reached
the number of repetitions desired.
(c) Increasing the value of loop counter each time the body of the loop
has been executed.
 Syntax :
for (initialize counter ; test counter ; update counter)
{ // body of-loop }
 Explanation :
- initialize counter - initializes variables and is executed only once
- test counter i.e. condition - if true, the body of for loop is executed
if false, the for loop is terminated
- update counter- updates the value of initialized variable and again
checks the condition

21 Lecture No: 17 : For Loop Statement


Flowchart of for Loop Statement

22 Lecture No: 17 : For Loop Statement


Program 1:
Q. WAP to print numbers Working of the Program :
from 1 to 5
Iteratio Variab i <=
#include <stdio.h> n le 5
Action
#include <conio.h>
1 is printed. i is
void main() 1st i=1 true
increased to 2.
{
int i; 2 is printed. i is
2nd i=2 true
increased to 3.
for (i = 1; i <= 5; i++)
{ 3 is printed. i is
3rd i=3 true
increased to 4.
printf(“%d\t“,i);
} //end of for loop 4 is printed. i is
4th i=4 true
increased to 5.
getch();
} 5 is printed. i is
Output : 5th i=5 true
increased to 6.
12345
The loop is
23 Lecture No: 17 : For Loop Statement 6th i=6 false
terminated
Program 1:
Q. WAP to print numbers from
1 to 5. Working of the Program :
#include <stdio.h>
#include <conio.h> Iteration Variable i <= 5 Action
void main() 1 is printed and “i” is
1st i=1 true increased by 1i.e. i=2.
{
2 is printed and “i” is
int i; 2nd i=2 true increased by 1i.e. i=3.
for (i = 1; i <= 5; i++) 3 is printed and “i” is
3rd i=3 true
{ increased by 1i.e. i=4.

printf("%d\t",i); 4 is printed and “i” is


4th i=4 true increased by 1i.e. i=5.
} //end of for loop
5 is printed and “i” is
getch(); 5th i=5 true increased by 1i.e. i=6.
} Output : For loop will be
6th i=6 false terminated
1 2 3 4 5
24 Lecture No: 17 : For Loop Statement
Program 2:
Q. WAP to print sum of 1 to n numbers.
#include <stdio.h> Working of the Program : Assume n=5
#include <conio.h>
void main() Iterati Variab i <=
{ Action
on le 5
int i, n, sum=0;
1 is added in sum i.e. 0+1 =1
printf("Enter limit :\n"); 1st i=1 true & “i” is increased by 1i.e. i=2.
scanf("%d",&n);
for (i = 1; i <= n; i++) 2 is added in sum i.e. 1+2 =3
2nd i=2 true & “i” is increased by 1i.e. i=3.
{
sum=sum+i; 3 is added in sum i.e. 3+3 =6
3rd i=3 true & “i” is increased by 1i.e. i=4.
} //end of for loop
printf("Sum=%d",sum); 4 is added in sum i.e. 6+4 =10
4th i=4 true & “i” is increased by 1i.e. i=5.
getch(); Output :
} Enter limit : 5th i=5 true
5 is added in sum i.e. 10+5 =15
& “i” is increased by 1i.e. i=6.
5
Sum=15 6th i=6 false For loop will be terminated
25 Lecture No: 17 : For Loop Statement
Program 3:
Q. WAP to print factorial of number
“n”.
#include <stdio.h> Working of the Program : Assume n=5
#include <conio.h> Iterati Variab i <=
void main() Action
on le 5
{
1 is multiplied with fact i.e. 1*1 =1
int i, n, fact=1; 1st i=1 true & “i” is increased by 1i.e. i=2.
printf("Enter the number :\n");
2 is multiplied with fact i.e. 1*2=2
scanf("%d",&n); 2nd i=2 true & “i” is increased by 1i.e. i=3.
for (i = 1; i <= n; i++)
3 is multiplied with fact i.e.
{ 3rd i=3 true 2*3=6
fact=fact*i; & “i” is increased by 1i.e. i=4.
4 is multiplied with fact i.e.
} //end of for loop 4th i=4 true 6*4=24
printf("Factorial of %d =%d", n, fact); & “i” is increased by 1i.e. i=5.
5 is multiplied with fact i.e. 24*5
getch(); Output : 5th i=5 true =120 & “i” is increased by 1i.e.i=6
} Enter the number :
5
6th i=6 false For loop will be terminated
Factorial of 5=120
26 Lecture No: 17 : For Loop Statement
Program 4: Q. WAP to calculate mn

#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

1. Write a C program to print all even and odd numbers from


1 to N.

2. Write a C program to print square and cube of all numbers


from 1 to N.

3. Write a C program to print all leap years from 1 to N.

33 Lecture 1 – Neural Networks


Nested Control Structures
• Nesting of loops is the feature in C that allows the looping of statements
inside another loop.
• Any number of loops can be defined inside another loop, i.e., there is no
restriction for defining any number of loops.
• We can define any type of loop inside another loop; for example, we can
define 'while' loop inside a 'for' loop.
• General Format :
Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop,
'while' loop or 'do-while' loop.

Lecture No: 18: Nested Control


36
Structures
Nested for Loop
• Syntax :
for ( init; condition; increment ) // outer for loop
{
for ( init; condition; increment ) // inner for loop
{
statement(s); // inner loop statements
}
statement(s); // outer loop statements
}
Lecture No: 18: Nested Control
37
Structures
Nested while Loop
• Syntax :
while(condition) // outer for loop
{
while(condition) // inner for loop
{
statement(s); // inner loop statements
}
statement(s); // outer loop statements
}
Lecture No: 18: Nested Control
38
Structures
Nested do….while Loop
• Syntax :
do // outer for loop
{
do // inner for loop
{
statement(s); // inner loop statements
} while( condition );
statement(s); // outer loop statements
} while( condition );
Lecture No: 18: Nested Control
39
Structures
Program 1 :
Q. WAP to print following pattern.
*
**
***
****
*****
#include <stdio.h>
#include<conio.h>
void main()
{
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
Lecture No: 18: Nested Control
40
Structures
Program 1 :
for(i = 1; i <= rows; i++) //outer for loop
{
for(j = 1; j <= i; j++) // inner for loop
{
printf("* "); // inner loop statement
}
printf("\n"); // outer loop statement, to Output :
// start printing next row on new line Enter the number of rows:
} // end of outer loop 5
getch(); *
} **
***
****
*****
Lecture No: 18: Nested Control
41
Structures
Program 2 :
Q. WAP to print following pattern.
1
12
123
1234
12345
#include <stdio.h>
#include<conio.h>
void main()
{
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
Lecture No: 18: Nested Control
42
Structures
Program 2 :
for(i = 1; i <= rows; i++) //outer for loop
{
for(j = 1; j <= i; j++) // inner for loop
{
printf(“%d “,j); // inner loop statement
}
printf("\n"); // outer loop statement, to
// start printing next row on new line
} // end of outer loop Output :
getch(); Enter the number of rows: 5
} 1
12
123
1234
12345
Lecture No: 18: Nested Control
43
Structures
Program 3 :
Q. WAP to print following pattern.
1
22
333
4444
55555
#include <stdio.h>
#include<conio.h>
void main()
{
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
Lecture No: 18: Nested Control
44
Structures
Program 3 :
for(i = 1; i <= rows; i++) //outer for loop
{
for(j = 1; j <= i; j++) // inner for loop
{
printf(“%d “,i); // inner loop
statement
}
printf("\n"); // outer loop statement, to
// start printing next row on new line
} // end of outer loop Output :
getch(); Enter the number of rows: 5
} 1
22
333
4444
45
Lecture No: 18: Nested Control 55555
Structures
Program 4 :
Q. WAP to print following pattern.
A
AB
ABC
ABCD
ABCDE
#include <stdio.h>
#include<conio.h>
void main()
{
int i, j, rows;
char ch;
printf("Enter the number of rows: ");
scanf("%d", &rows);
Lecture No: 18: Nested Control
46
Structures
Program 4 :
for (i = 1; i <= rows; i++) //outer for loop
{
ch='A’;
for (j = 1; j <= i; j++) // inner for loop
{
printf("%c ",ch); // inner loop statement
ch++;
} Output :
printf("\n"); Enter the number of rows: 5
} A
getch(); AB
} ABC
ABCD
ABCDE

Lecture No: 18: Nested Control


47
Structures
Program 5 :
Q. WAP to print following
pattern.
A
BB
CCC
DDDD
EEEEE
#include <stdio.h>
#include<conio.h>
void main()
{
int i, j, rows;
char ch=‘A’;
printf("Enter the number of
rows: ");
scanf("%d", &rows);
Lecture No: 18: Nested Control
48
Structures
Program 5 :
for (i = 1; i <= rows; i++) //outer for loop
{
for (j = 1; j <= i; j++) // inner for loop
{
printf("%c ",ch); // inner loop statement
}
ch++; Output :
printf("\n"); Enter the number of rows: 5
} // end of outer for loop statement A
getch(); BB
} CCC
DDDD
EEEEE

Lecture No: 18: Nested Control


49
Structures
Program 6 :
Q. WAP to print following pattern.
A
BC
DEF
GHIJ
KLMNO
#include <stdio.h>
#include<conio.h>
void main()
{
int i, j, rows;
char ch=‘A’;
printf("Enter the number of rows: ");
scanf("%d", &rows);
Lecture No: 18: Nested Control
50
Structures
Program 6 :
for (i = 1; i <= rows; i++) //outer for loop
{
for (j = 1; j <= i; j++) // inner for loop
{
printf("%c ",ch); // inner loop statement
ch++;
} Output :
printf("\n"); Enter the number of rows: 5
} // end of outer for loop statement A
getch(); BC
} DEF
GHIJ
KLMNO

Lecture No: 18: Nested Control


51
Structures
Program 7 :
Q. WAP to print following pattern.
*****
****
***
**
*
#include <stdio.h>
#include<conio.h>
void main()
{
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
Lecture No: 18: Nested Control
52
Structures
Program 7 :
for(i = rows; i >= 1; i--) //outer for loop
{
for(j = 1; j <= i; j++) // inner for loop
{
printf(“* “); // inner loop statement
}
printf("\n"); // outer loop statement, to
// start printing next row on new line Output :
} // end of outer loop Enter the number of rows: 5
getch(); *****
} ****
***
**
*

Lecture No: 18: Nested Control


53
Structures
Program 8 :
Q. WAP to print following pattern. for (i = rows; i >= 1; i--)
12345 {
1234 for (j = 1; j <= i; j++)
123 {
12
printf("%d ",j);
1
}
#include <stdio.h>
#include<conio.h> printf("\n");
void main() }
{ getch();
int i, j, rows; } Output :
printf("Enter the number of Enter the number of rows: 5
rows: ");
12345
scanf("%d", &rows);
1234
123
Lecture No: 18: Nested Control 12
54
Structures 1
Program 9 :
Q. WAP to print following pattern. for (i = rows; i >= 1; i--)
54321 {
4321 for (j = 1; j >= i; j++)
321 {
21
printf("%d ",j);
1
}
#include <stdio.h>
#include<conio.h> printf("\n");
void main() } Output :
{ getch(); Enter the number of rows:
int i, j, rows; } 5
printf("Enter the number of 54321
rows: "); 4321
scanf("%d", &rows); 321
21
1
Lecture No: 18: Nested Control
55
Structures
Program 10 :WAP to print following pattern
1 for(i = 1; i <= rows; i++)
1 2 {
for(space=i; space<rows; space++)
1 2 3 //for spacing
1 2 3 4 printf(" ");
1 2 3 4 5 for(j = 1; j <= i; j++)
printf("%d ", j);
#include <stdio.h> printf("\n");
#include<conio.h>
void main() }
{ getch();Output :
int i, j, space, rows; } Enter the number of rows: 5
printf("Enter the number of
rows: "); 1
scanf("%d", &rows); 12
123
Lecture No: 18: Nested Control 1234
56
Structures 12345
Program 11 :

#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);
* * * * * * * * *

Lecture No: 18: Nested Control


57
Structures
Program 11 :
for (i = 1; i <= rows; i++)
{
for(space=i; space<rows; space++) //for spacing
printf(" ");
for(j = 1; j <= i; j++) // for left triangle
printf("* ");
for(k=1;k<(j-1);k++) // for right triangle
printf("* ");
printf("\n");
} Output :
getch(); Enter the number of rows: 3
} *
***
*****

Lecture No: 18: Nested Control


58
Structures
Program 12 :WAP to print following pattern.

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);

Lecture No: 18: Nested Control


59
Structures
Program 12 :
for (i = 1; i <= rows; i++)
{
for(space=i; space<rows; space++)
printf(" ");
for(j = 1; j <= i; j++)
printf("%d ",j); Output :
for(k=1;k<(j-1);k++) Enter the number of rows: 3
printf("%d ",k); 1
printf("\n"); 121
12321
}
getch();
}

Lecture No: 18: Nested Control


60
Structures
Program 13 :
Q. WAP to print following pattern. for (i = 1; i <= rows; i++) {
A ch='A';
for(space=i; space<rows; space++)
A B A printf(" ");
A B C B A for(j = 1; j <= i; j++)
{
A B C D C B A
#include <stdio.h> printf("%c ",ch);
#include<conio.h> ch++;
void main() }
{
int i, j, k, space, rows; for(k=1;k<(j-1);k++)
char ch; {
printf("Enter the number of printf("%c ",(ch-2));
rows: "); ch--;
scanf("%d", &rows);
}
printf("\n"); }
getch(); }
Lecture No: 18: Nested Control
61
Structures
Program 14 :
Q. WAP to Floyd's triangle. for (i = 1; i <= rows; i++)
1 {
for (j = 1; j <= i; ++j)
2 3
{
4 5 6 printf("%d ", k);
7 8 9 10 k++;
}
#include <stdio.h> printf("\n");
#include<conio.h> }
void main() getch();
{ } Output :
int i, j, rows, k=1; Enter the number of
printf("Enter the number of rows: 4
rows: "); 1
scanf("%d", &rows); 23
Lecture No: 18: Nested Control 456
62
Structures 7 8 9 10
Practice Programs
Q. Write C programs for the following
pattern.
1. 5 4 3 2 1 4. A
5432 BCB
543 CDEDC
54 DEFGFED
5
5. 1
2. 5 5 5 5 5
4444 22
333 333
22 4444
1 55555
3. 1 2 3 4 5
2345 6. 1
345 232
45 34543
5 4567654
567898765

Lecture No: 18: Nested Control


63
Structures
Thank You
Subject Name: C Programming
Unit No:3
Unit 3: CONTROL STRUCTURES

Faculty Name : Dr. Gautam M Borkar


1
Index -

Lecture 19 – continue, break and goto statement 3

Lecture 20 – Practice programs on Loops 16

Lecture 21 – Array-Concepts, Declaration, Definition, Accessing array element 32

2
Module No: 3 CONTROL STRUCTURES

Lecture No: 19
break, continue and goto
statement
SPECIAL CONTROL STATEMENTS

“goto” statements

“break” statements

“continue” statements

Lecture 19:continue, break and goto


4
statement
goto Statement

 goto statement is used for altering the normal sequence of program


execution by transferring control to some other part of the program.
• The control is unconditionally transferred to the statement associated with
the label specified in the goto statement.
• The label is the identifier which defines where the control should go on the
execution of 'goto' statement.

• The form of a goto statement is:


goto label;
.............
.............
.............
label: statement;

Lecture 19:continue, break and goto


5
statement
goto Statement continued..

 Control Transfer

Lecture 19:continue, break and goto


6
statement
goto statement example

#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();
}

Lecture 19:continue, break and goto


7
statement
break Statement

• Break statement causes immediate exit from for, while,


do-while and switch statement
• Break statement neglects statements after it in the loop
and transfer the control outside the loop.
• Execution continues with the first statement after the
control structure
• The common use is:
Early escape from loop
Skip remainder statement in control structure
• Syntax:
break;

Lecture 19:continue, break and goto


8
statement
break statement control flow

Lecture 19:continue, break and goto


9
statement
break statement exmple

#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();
}

Lecture 19:continue, break and goto


10
statement
7.3 continue Statement

• Continue statement also neglects statements after it in the


loop and transfers control back to the starting of the loop for
next iteration.
• In case of for loop after continue statement increment
statement is executed and then test condition is evaluated.
• In case of do and do-while loop after continue statement the
test condition is evaluated.

• Syntax
continue ;

Lecture 19:continue, break and goto


11
statement
continue statement control flow

Lecture 19:continue, break and goto


12
statement
continue Statement example

#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

1. It helps to make an early 1. It helps in avoiding the


exit from the block where it remaining statements in a
appears. current iteration of the loop
and continuing with the next
Iteration

2. It can be used in all control 2. It can be used only in loop


statements including switch constructs.
construct.

Lecture 19:continue, break and goto


14
statement
Thank You
Module No: 3 CONTROL STRUCTURES

Lecture No: 20
Practice program on loops
Write a program to Check given number is armstrong number or not.

 If sum of cube of digits is equal to number then it is armstrong number

#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> if (flag == 0)


void main() { printf("%d is a prime number.", n);
else
int n, i, flag = 0;
printf("%d is not a prime number.", n);
printf("Enter a number: ");
scanf("%d", &n);
getch();
}
for (i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
flag = 1;
OUTPUT
break; Enter a number: 15
} 15 is not a prime number.
}

Lecture 20:Practice Programs on


18
Loops
Write a program to display given Pattern

* #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();
}

Lecture 20:Practice Programs on


20
Loops
#include<stdio.h>
#include<conio.h>
void main() {
Write a program to int i,j,n;
display following clrscr();
printf("Enter the number rows:");
scanf("%d",&n);
* * * * *
for(i=n;i>=1;i--)
* * * * {
* * * for(j=1;j<=n-i;j++)
* * {
* printf(" ");
}
for(j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
}
getch(); }
Lecture 20:Practice Programs on
21
Loops
Write a program to display given Pattern

#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();}

Lecture 20:Practice Programs on


23
Loops
Write a program to display pascal triangle

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

Lecture 20:Practice Programs on


24
Loops
Program

#include<stdio.h> for(j=0; j <= i; j++)


void main() {
{ if (j==0 || i==0)
val = 1;
int rows, val = 1, space, i, j; else
printf("\nEnter the number of rows : "); val = val*(i-j+1)/j;
scanf("%d",&rows);
printf("\n"); printf("%4d", val);
}
printf("\n");
for(i=0; i<rows; i++) }
{
for(space=1; space <= rows-i; space++) getch();
printf(" "); }

Lecture 20:Practice Programs on


25
Loops
Write a program to calculate factors of a number

#include <stdio.h> OUTPUT


void main() { Enter any number
int i, num; 6
printf("\n Enter any number \n");
scanf("%d", &num); Factors of the Given Number:
1 2 3 6
printf("\n Factors of the Given Number:\n");
for (i = 1; i <= num; i++)
{
if(num%i == 0)
{
printf(" %d ", i);
}
}
getch();}

Lecture 20:Practice Programs on Loops


26
Write a program to calculate LCM and GCD of two numbers

#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

Lecture 20:Practice Programs on Loops


27
Write a program to display odd numbers from first n numbers

#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

• An array is a derived data type.


• It is collection of similar type of elements
• Why need to use array?
• Consider the following issue:
"We have a list of 1000 students' marks of an
integer type. If using the basic data type (int),
we will declare something like the following…"

int studMark0, studMark1, studMark2, ..., studMark999;

• Can you imagine how long we have to write the declaration part
by using normal variable declaration?

34 Lecture 21: Array


• Instead of declaring individual variables, we can declare
one array variable such as
• int studMark[1000];

35 Lecture 21: Array


Array : Introduction

• An array is a fixed size sequential collection of elements of


same type that share common name.
• A specific element in an array is accessed by an subscript or
index.
• Array index starts with 0 and ends with size-1.
• All arrays consist of contiguous memory locations.
• The lowest address corresponds to the first element and the
highest address to the last element.

36 Lecture 21: Array


Array Declaration

• To declare an array in C, a programmer specifies the type


of the elements and the number of elements required by
an array as follows:

datatype arrayName [ arraySize ];


• This is called a single-dimensional array.
• The arraySize must be an integer constant greater than
zero and type can be any valid C data type.

• Eg:- double balance[10];


int A[5];
char Name[10];

37 Lecture 21: Array


Initializing Arrays

• 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.

38 Lecture 21: Array


Accessing Array Elements

• An element is accessed by indexing the array name.


int num = A[4];
• To read array elements
for(i=0;i<size;i++)
{
scanf(“%d”, &A[i]);
}
• To display array elements
for(i=0;i<size;i++)
{
printf(“%d\t”, A[i]);
}

39 Lecture 21: Array


WAP to read and display 10 integer type
array elements.
#include <stdio.h> Output
void main () Element[0]=1
{ Element[1]=2
int n[ 10 ]; // n is an array of 10 integers Element[2]=3
int i,j; // initialize elements of array n to 0 Element[3]=4
for ( i = 0; i < 10; i++ ) Element[4]=5
{
Element[5]=6
n[ i ] = i + 1 //set element at location i to i + 1
Element[6]=7
}
Element[7]=8
/* output each array element's value */
for (j = 0; j < 10; j++ ) Element[8]=9
{ Element[9]=10
printf("Element[%d] = %d\n", j, n[j] );
}
}

40 Lecture 21: Array


WAP to calculate sum and average of array
elements
#include<stdio.h> for(i=0;i<=n-1;i++)
for(i=0;i<=n-1;i++)
#include<conio.h> {{
void main() sum=sum+a[i];
sum=sum+a[i];
{ }}
avg=sum/n;
avg=sum/n;
int n,i,a[100],sum=0;
printf("The
printf("Thesum
sumis %d andand
is %d average
float avg; is %f",sum,avg);
average is %f",sum,savg);
clrscr(); getch();
getch();
printf("Enter the number of elements:"); }}
scanf("%d",&n); Output
for(i=0;i<=n-1;i++) Enter the number
number of elements:
elements: 55
{ Enter a value:10
value:10
printf("Enter a value:"); value:20
Enter a value:20
Enter a value:30
value:30
scanf("%d",&a[i]);
Enter a value:40
value:40
} Enter a value:50
value:50
The sum
sum is
is 150 and
and average
averageisis30
50
41 Lecture 21: Array
Thank You
Subject Name: C Programming
Unit No:4
ARRAYS, STRING, STRUCTURE AND
UNION
Faculty Name : Gautam M Borkar
1
Index -

Lecture 22 – One dimensioanl array 3

Lecture 23 – Multi dimensional array 20

Lecture 24 – Practice programs on array 35

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] }

4 Lecture 22 –One dimensional array


WAP to sort array elements in ascending order

Output
Enter the number of elements: 5
Enter array elements:
5
3
2
1
4
max=5 and min=1

5 Lecture 22 –One dimensional array


WAP to search an element in array
#include<stdio.h> for(i=0;i<=n-1;i++)
#include<conio.h> {
void main() if(x==a[i])
{ int n,i,a[100],x,index=0; {
clrscr(); index=1;
printf("Enter the number of elements:"); break;
scanf("%d",&n); }
printf("Enter array elements:"); }
for(i=0;i<=n-1;i++) if(index!=0)
{ { printf("The element is found at
scanf("%d",&a[i]); position %d",(i+1));}
} else
printf("Enter the element to be { printf("Not Found");
searched:"); } getch();
scanf("%d",&x); }
6 Lecture 22 –One dimensional array
WAP to search an element in array

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

7 Lecture 22 –One dimensional array


WAP to split the list of numbers in to two different lists(even and odd list)

#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]); }
}

8 Lecture 22 –One dimensional array


WAP to split the list of numbers in to two different lists(even and odd list)

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();
}

9 Lecture 22 –One dimensional array


Thank You
Module No:4 ARRAYS, STRING, STRUCTURE AND UNION

Lecture No: 23
Multi-dimensional array
Multi-dimensional array

• C programming language allows multidimensional arrays.


Here is the general form of a multidimensional array
declaration:

• Syntax:
datatype arrayname[size1][size2]...[sizeN];

Eg:-
int A[3][3];
char name[10][5];
float B[3][3];

12 Lecture 23 – Multi-dimensional array


2-Dimensional array

int A[3][3];
COL
0 1 2

ROW 0 A[0][0] A[0][1] A[0][2]

1 A[1][0] A[1][1] A[1][2]

2 A[2][0] A[2][1] A[2][2]

Memory Representation of 2-D array


A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2] A[2][0] A[2][1] A[2][2]

ROW 0 ROW 1 ROW 2

13 Lecture 23 – Multi-dimensional array


2-D Array initialization

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.

Note- size of row is optional

14 Lecture 23 – Multi-dimensional array


Accessing 2-D Array Elements

To read 2-D Array elemnts To display 2-D Array elements

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”);
}

15 Lecture 23 – Multi-dimensional array


WAP to read and display elements of integer type 2-D array.

#include <stdio.h> /* output each array element's


void main () value */
{ for(i=0;i<3;i++)
int A[3][3]; // A is an array of 3X3 size
{
int i,j;
for(j=0;j<3j++)
Printf(“ENTER ARRAY ELEMENTS:\n”);
{
for(i=0;i<3;i++)
{ printf(“Element[%d][%d]=%d\t
”,i,j,A[i][j]);
for(j=0;j<3;j++)
{ }
scanf(“%d”,&A[i][j]); printf(“\n”);
} }
} }

16 Lecture 23 – Multi-dimensional array


Output

ENTER ARRAY ELEMENTS:


123456789

Element[0][0]=1 Element[0][1]=2 Element[0][2]=3


Element[1][0]=4 Element[1][1]=5 Element[1][2]=6
Element[2][0]=7 Element[2][1]=8 Element[2][2]=9

17 Lecture 23 – Multi-dimensional array


WAP to display addition of two matrices of
size mxn
#include <stdio.h> for(i=0;i<m;i++)
void main () { for(j=0;j<n;j++)
{
{
scanf(“%d”,&A[i][j]);
int A[3][3],B[3][3],C[3][3]; }
int i,j,m,n; }
prinf(“Enter size of printf(“ENTER ARRAY ELEMENTS
matrices\n”); FOR B:\n”);
for(i=0;i<m;i++)
scanf(“%d%d”,&m,&n);
{ for(j=0;j<n;j++)
printf(“ENTER ARRAY {
ELEMENTS FOR A:\n”); scanf(“%d”,&B[i][j]);
}
}
18 Lecture 23 – Multi-dimensional array
for(i=0;i<m;i++) for(i=0;i<m;i++)
{ {
for(j=0;j<n;j++) for(j=0;j<n;j++)
{ {
C[i][j]=A[i][j]+B[i][j]; printf(“%d”,C[i][j]);
} }
} printf(“\n”);
printf(“Matrix addition is\n”); }
getch();
}

19 Lecture 23 – Multi-dimensional array


OUTPUT

Enter size of matrices 3 3


ENTER ARRAY ELEMENTS FOR A:
1 1 1
1 1 1
1 1 1
ENTER ARRAY ELEMENTS FOR B:
1 1 1
1 1 1
1 1 1
Matrix addition is
2 2 2
2 2 2
2 2 2

20 Lecture 23 – Multi-dimensional array


Thank You
Module No:4 ARRAYS, STRING, STRUCTURE AND UNION

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

• A bubble sort compares adjacent array


elements and exchanges their values if they
are out of order.
• In this way, the smaller values ‘bubble’ to the
top of the array (towards element 0), while
the larger values sink to the bottom of the
array.
• This sort continues until no exchanges are
performed in a pass.
Lecture 24 –Practice programs on
24
Array
Bubble sort example

Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5

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

Lecture 24 –Practice programs on


25
Array
Bubble sort example

Lecture 24 –Practice programs on


26
Array
WAP to sort array elements in ascending order using bubble sort

#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]);
}
} }

Lecture 24 –Practice programs on


27
Array
WAP to sort array elements in ascending order using bubble sort

Output
Enter the number of elements: 5
Enter array elements:
5
3
2
1
4
Sorted array is: 1 2 3 4 5

Lecture 24 –Practice programs on


28
Array
WAP to perform transpose of a matrix

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();
} }

Lecture 24 –Practice programs on


29
Array
output

ENTER ARRAY ELEMENTS


123
123
123
transpose of Matrix is
1 1 1
2 2 2
3 3 3
Lecture 24 –Practice programs on
30
Array
WAP to perform addition of column elements of a matrix

#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();
} }
}

Lecture 24 –Practice programs on


31
Array
output

ENTER ARRAY ELEMENTS


123
123
123
sum of column elements is
3 6 9

Lecture 24 –Practice programs on


32
Array
WAP to perform addition of diagonal
elements of a matrix
#include<stdio.h> for(i=0;i<3;i++)
{
#include<conio.h>
for(j=0;j<3;j++)
void main() {
{ if(i==j||i+j==2)
int A[3][3],i,j,sum=0; {
clrscr(); sum=sum+A[i][j];
printf("ENTER ARRAY }
ELEMENTS\n"); }
for(i=0;i<3;i++) }
{ printf("sum of diagonal elements
is\n\n");
for(j=0;j<3;j++)
{ printf("%d\t",sum);
scanf("%d",&A[i][j]);
}
} getch();
Lecture 24 –Practice programs on }
33
Array
output

ENTER ARRAY ELEMENTS


123
123
123
sum of diagonal elements is
10

Lecture 24 –Practice programs on


34
Array
WAP to perform matrix multiplication

#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

ENTER ARRAY ELEMENTS FOR A


111
111
111
ENTER ARRAY ELEMENTS FOR B
222
222
222
Matrix multiplication is:
6 6 6
6 6 6
6 6 6

Lecture 24 –Practice programs on


36
Array
Thank You
Subject Name: C Programming
Unit No:4
Arrays, String, Structure And Union

1 Faculty Name : Dr. Gautam M Borkar


Index -

Lecture 25 - String- Basic of String, Programs on String 3

Lecture 26 – String Handling Functions 18

Lecture 27 – Array of String 35

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

 Each Character occupy 1 byte of memory.


 Size of “programming“ = 11 bytes

4 Lecture 25 :String- Basic of String, Programs on String


NULL Character

• NULL Character is also known as string terminating


character.
• It is represented by “\0”.
• NULL Character is having ASCII value 0.
• NULL terminates a string, but isn’t part of it.
• Note : For strlen() function – length doesn’t include the
NULL character.

5 Lecture 25 :String- Basic of String, Programs on String


String Declaration
• C does not support String data type.
• Instead of string data type we use array of type “char” to create
String.
• Syntax :
char String_variable_name [ SIZE ] ;
• Examples :
char city[30];
char name[20];
char message[50];

6 Lecture 25 :String- Basic of String, Programs on String


Initializing String
• String can be initialized in multiple ways as shown below:
char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};

7 Lecture 25 :String- Basic of String, Programs on String


String Input / Output Function
• To handle string input and output, C provides various types
of predefined functions.

• For input

– Using scanf( ) with %s for string constant.

– Using gets() function.

• For output

– Using printf( ) with %s for string constant.

– Using puts( ) Function.

8 Lecture 25 :String- Basic of String, Programs on String


scanf( ) and printf() Function
• The scanf() function reads the sequence of characters until it
encounters whitespace (space, newline, tab, etc.).
• Syntax :
scanf(“%s”, var_name);
%s format specifiers are used to handle string
• For Example:
char name[10];
scanf(“%s”, name);
• The printf() function display string entered on screen.
• Syntax :
printf(“%s”, var_name);

9 Lecture 25 :String- Basic of String, Programs on String


Example on scanf( ) and printf() Function
#include <stdio.h>
void main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is : %s", name);
}
Output :
Enter name: Chirag ABC
Your name is : Chirag
Note : Even though Chirag ABC was entered in the above
program, only “Chirag" was stored in the name string.
It's because there was a space after Chirag.
10 Lecture 25 :String- Basic of String, Programs on String
gets( ) Function
• The gets function can be used to input multiword string
input contain white spaces excluding new line character.
• gets() is a pre-defined function in C which is used to read a
string or line from stdin (standard input) into the buffer
pointed to by str pointer, until terminated by newline
character.
• Syntax :
gets ( str ) ;
• Example:
char city[20];
gets (city) ;

11 Lecture 25 :String- Basic of String, Programs on String


puts() Function
• The puts() function writes the string str and a trailing
newline to stdout.
• Syntax :
puts ( str ) ;
• Example:
char city[20];
gets (city) ;
puts (city) ;

12 Lecture 25 :String- Basic of String, Programs on String


Example on gets( ) and puts() Function
#include <stdio.h>
#include<conio.h>
void main ()
{
char str[50];
printf("Enter a string : ");
gets(str);
printf("\nYou entered:”);
puts(str);
}
Output :
Enter a string : D Y P University
You entered: D Y P University

13 Lecture 25 :String- Basic of String, Programs on String


Program 1 : Write a program to copy one string to
another.
#include <stdio.h>
Output :
#include<conio.h>
Enter string s1: D Y P
void main()
{
University
char s1[100], s2[100]; String s2: D Y P University
int i;
printf("Enter string s1: ");
gets(s1);
for (i = 0; s1[i] != '\0'; ++i)
s2[i] = s1[i];
s2[i] = '\0';
printf("String s2: %s", s2);
getch();
}
14 Lecture 25 :String- Basic of String, Programs on String
Program 2 : Write a program to reverse a string.
#include <stdio.h> for(j=i-1;j>=0;j--)
#include<conio.h> {
void main() s2[k] = s1[j];
{ k++;
char s1[100], s2[100]; }
int i, j, k; s2[k] = '\0';
i=j=k=0; printf("\nReverse of string s1:
printf("Enter string s1: "); %s", s2);
gets(s1); getch();}
while(s1[i] != '\0')
{ Output :
i++; Enter string s1: hello world
} Length of s1:11
printf("Length of s1:%d", i); Reverse of string s1: dlrow olleh

15 Lecture 25 :String- Basic of String, Programs on String


Program 3 : Write a program to perform
concatenation of two strings.
#include <stdio.h> for(j=i;s2[k]!='\0';j++)
#include<conio.h> {
void main() s1[j] = s2[k];
{ k++;
char s1[100], s2[100],
}
s3[100];
s1[j] = '\0';
int i, j, k;
i=j=k=0; printf("\nConcatenation of string s1 &
printf("Enter string s1: "); s2: %s“,s1);
gets(s1); getch(); }
printf("Enter string s2: ");
Output :
gets(s2);
Enter string s1: hello
while(s1[i] != '\0')
Enter string s2: world
{ i++; }
Concatenation of string s1 and s2:
helloworld
16 Lecture 25 :String- Basic of String, Programs on String
Thank You
Module No:4 Arrays, String, Structure and Union

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”

strcmp(); compares two strings strcmp(“hi”, “bye”); Returns -1


character by character.
If the strings are equal,
the function returns 0.
If the strings are not
equal, the function
returns non-zero value.

20 Lecture 26 : String handling functions


String Handling Functions (cont..)
Function Purpose Example Output
strlen(); Returns the strlen(“Hi”); Returns length as
number of 2
characters in a
string
strrev(); Reverses a given strrev(“Hello”); olleH
string
strlwr(); Converts string to strlwr(“HELLO”); hello
lowercase
strupr(); Converts string to strupr(“hello”); HELLO
uppercase
• Strings handling functions are defined under "string.h" header file.
• So we have to include string.h to run string handling functions.

21 Lecture 26 : String handling functions


String Copy (strcpy)
• strcpy( ) function copies contents of one string into another
string.
• Syntax:
strcpy (destination_string , source_string );
• Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
• If destination string length is less than source string, entire
source string value won’t be copied into destination string.
• For example, consider destination string length is 20 and source
string length is 30. Then, only 20 characters from source string
will be copied into destination string and remaining 10
characters won’t be copied and will be truncated.

22 Lecture 26 : String handling functions


Example of strcpy()
#include <stdio.h>
#include <string.h>
void main()
{
char s1[30] = “Harish";
char s2[30] = “Tiwari";
strcpy(s1,s2); // copy string s2 into string s1
printf("String s1 is: %s", s1);
}
Output :
String s1 is: Tiwari

23 Lecture 26 : String handling functions


String Concatenation (strcat)
• strcat( ) function in C language concatenates (appends) one
string at the end of another string.
• Syntax :
strcat ( destination_string , source_string);
• Example :
strcat ( str2, str1);
 String str1 is concatenated at the end of String str2.
• Each string in C is terminated up with null character (‘\0’).
• In strcat( ) operation, null character of destination string is
overwritten by source string’s first character and null character is
added at the end of new destination string which is created after
strcat( ) operation.

24 Lecture 26 : String handling functions


Example of strcat()
#include <stdio.h>
#include <string.h>
void main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
}

Output :
Output string after concatenation:
HelloWorld

25 Lecture 26 : String handling functions


String Compare (strcmp)

• strcmp( ) function in C compares two given strings and returns


values as,
 If length of string1 < string2, it returns < 0 value that is -1.
 If length of string1 > string2, it returns > 0 value that is 1.
 If length of string1 = string2 it returns 0.
• Syntax :
strcmp (str1 , str2 );
• Note : strcmp( ) function is case sensitive. i.e, “A” and “a” are
treated as different characters.

26 Lecture 26 : String handling functions


Example of strcmp()
#include <stdio.h>
#include <string.h>
void main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s2) ==0)
printf("string 1 and string 2 are equal");
else
printf("string 1 and 2 are different");
}

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.

28 Lecture 26 : String handling functions


Example of strlen()
#include <stdio.h>
#include <string.h>
#include<conio.h>
void main()
{
char str[20] = “Hello everyone";
printf("Length of string str: %d", strlen(str));
getch();
}

Output :
Length of string str: 14

29 Lecture 26 : String handling functions


String Reverse (strrev)
• strrev() function is used to reverse the given string.
• This function returns the string after reversing the given
string.
• Syntax :
strrev(str);
• Example:
char str[] = “computers”;
strrev(str);
printf(“%s”,str);

 It will print sretupmoc

30 Lecture 26 : String handling functions


Example of strrev()
#include<stdio.h>
#include<string.h>
void main()
{
char str[50] = “Computer Programming";
printf("The given string is= %s\n", str);
printf("After reversing string is= %s", strrev(str));
}
Output :
The given string is= Computer Programming
After reversing string is= gnimmargorP
retupmoC

31 Lecture 26 : String handling functions


String Uppercase and Lowercase
• The strlwr function returns string characters in lowercase

• Syntax :

strlwr(str);

• The strupr function returns string characters in uppercase.

• Syntax :

strupr(str);

32 Lecture 26 : String handling functions


Example of uppercase and lowercase
#include<stdio.h>
#include<string.h>
void main()
{
char str[50] = “Computer Programming ";
printf(“Given String is= %s", str);
printf(“String in lowercase is= %s", strlwr(str));
printf(“String in uppercase is= %s", strupr(str));
} Output :
Given String is = Computer Programming
String in lowercase is= computer programming
String in uppercase is= COMPUTER PROGRAMMING

33 Lecture 26 : String handling functions


Program 1 : WAP to check entered string
is palindrome or not.
#include<stdio.h> Output:
#include<string.h> Enter a string: madam
void main() String madam is
{
Palindrome.
char s1[100], s2[100];
printf("Enter a string: ");
gets(s1); Enter a string: Madam
strcpy(s2,s1); // copy the string String madam is not
strrev(s2); // reverse the string Palindrome.
if(strcmp(s1,s2)==0)
printf(“String %s is Palindrome.“,
s1);
else
printf("String %s is not
Palindrome.“, s1);
}34
Lecture 26 : String handling functions
Write a C program to count the numbers of vowels, consonants, digits,
white spaces, special characters, and words in a given line of text.

#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?

• The string is a collection of characters, an array of a string is an array of


arrays of characters.

• A String can be defined as a one-dimensional array of characters, so an


array of strings is two –dimensional array of characters.
• A two-dimensional array of strings can be declared as follows:

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];

39 Lecture No 27: Array of Strings


Initialization

• char s[5][10] ={“hello”,”hi”,”C”,”Good”,”Morning”};

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

• Here every row is a string. That is, s[i] is a string.

40 Lecture No 27: Array of Strings


Initialization

Initialization can also be done as:

char str_arr[2][6] = { {‘g’,’o’,’u’,’r’,’i’,’\0’}, {‘r’,’ a’,’ m’,’\0’}};

41 Lecture No 27: Array of Strings


PROGRAM FOR INPUT AND OUTPUT
#include<stdio.h> OUPPUT
#include<conio.h>
Enter Strings :
#include<string.h>
void main() { Hello
char s[5][10]; Good
int i,j; Morning
clrscr();
Hi
puts("Enter String :");
for(i=0;i<5;i++){ CP
gets(s[i]); } s[0]=Hello
for(i=0;i<5;i++) { s[1]=Good
printf(“s[%d]= “,i); s[2]=Morning
puts(s[i]); s[3]=Hi
} s[4]=CP
getch();
}
42 Lecture No 27: Array of Strings
Write a program to sort strings in ascending
order
#include<stdio.h> i=0;
#include<conio.h> printf("Sorted Strings : “);
#include<string.h> while(i<5)
void main(){ {
char printf("\n%s",str[i]);
str[5][10]={"Mumbai","Delhi",“Calcutta","Chennai"," i++;
Banglore"}; }
int i=0,j=0; getch();
char temp[10]; }
clrscr();
for(i=0;i<5;i++){
for(j=i+1;j<5;j++) {
if((strcmp(str[i],str[j]))>0) {
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp); } } }

43 Lecture No 27: Array of Strings


continued..

OUTPUT
Sorted Strings

Banglore
Calcutta
Chenai
Delhi
Mumbai

44 Lecture No 27: Array of Strings


Write a program to search string in an array

#include<stdio.h> for(i=0; i<n; i++)


#include<string.h> {
void main() if(strcmp(s1, str[i]) == 0)
{ {
char str[20][50], s1[50]; flag=1;
int n, i, flag=0; printf("Found in row-%d\n", i+1);
}
printf("Enter how many string (names): "); }
scanf("%d", &n);
if(flag==0) printf("Not found");
printf("Enter strings:"); getch();
for(i=0; i<n; i++) }
{
scanf("%s",str[i]); OUTPUT:
} Enter how many string (names): 4
Enter strings:Sumit
printf("Enter a string to search: "); Reema
scanf("%s",s1); Akash
Priya
Enter a string to search: Priya
45 Lecture No 27: Array of Strings Found in row-4
Thank You
Subject Name: C Programming
Unit No:4
ARRAYS, STRING, STRUCTURE AND
UNION
Faculty Name : Dr. Gautam M Borkar
1
Index -

Lecture 28 – Structure-declaration, initialization 3

Lecture 29 – Nested Structure and Array of Structure 20

Lecture 30 – Practice Programs on Structure 35

2
Module No:4 ARRAYS, STRING, STRUCTURE AND UNION

Lecture No: 28
Structure-declaration,
initialization
INRODUCTION

• Array’s disadvantage is that all elements stored in array


must be of same type.

• If we want collection of elements of different types then it is


not possible with array.

• Structure can be used to store elements of different types.


WHAT IS STRUCTURE
5
• Structure is a user defined data type.
• A structure is a collection of variables under a single name.
• These variables can be of different types, and each has a name
that is used to select it from the structure.
• The memory required to store structure is total of memory
required to store each individual element.
• The proper place for structure declarations is in the global area of
the program before main().
• It is not possible to compare structures for equality using ‘==’, nor
is it possible to perform arithmetic on structures.
DECLARING STRUCTURES

6
• A structure is declared by using the keyword struct followed
by an optional structure tag followed by the body of the
structure.

General Format: Example:

struct <structure tag_name> { struct myStruct {

<data _ype member _ame1> int a;


<data _ype member _ame1> int b;
. float c;
.
}; };

• Structure tag name is name of the structure.


Different Ways Of Declaring Structures

struct myStruct { struct {


struct myStruct {
int a; int a; int a;
int b; int b; int b;
float c; float c; float c;
}; } s1,s2; }s1, s2;
struct myStruct s1, s2 s1, s2 both same as the other
both contains a b, have the defined two versions, but
and c value structure, containing united into one set
a ,b, and c ,but of code.
do not have a tag

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

8 • The members of a structure can be accessed by using the ‘.’,


which is known as the ‘dot operator’.
• The general form of the statement for accessing a member
of a structure is as follows:
< structure_variable >.< member_name > ;

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.

#include<stdio.h> printf("\n PERSON INFORMATION :");


#include<conio.h> printf("\nID = %d",p1.id);
struct Person{ printf("\nNAME = %s",p1.name);
int id;
printf("\nADDRESS =
char name[20]; %s",p1.address);
char address[30];
getch();
}p1;
}
void main()
{clrscr();
printf("Enter ID :\n");
scanf("%d",&p1.id);
printf("Enter Name :\n");
scanf("%s",&p1.name);
printf("Enter Address :\n");
scanf("%s",&p1.address);

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

• A structure can be placed within another structure.


15

• In such cases, the dot operator in conjunction with the


structure variables are used to access the members of the
innermost as well as the outermost structures.
Example
struct First{
a and b can be accessed as :
int a;
struct Second{ f1.a
float b;
}s1; f1.s1.b
}f1;
Define a structure named ‘Person’ which will store id, name ,address and date of
birth as a collection of day, month and year . Write a program to display all these
details.
16
#include<stdio.h>
#include<conio.h>

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.

#include<stdio.h> printf("\n PERSON INFORMATION


#include<conio.h> :\n");
struct Person{ for(i=0;i<5;i++)
int id; {
char name[20];
printf("\nPerson %d\n",i+1);
char address[30];
printf("\nID = %d",p1[i].id);
}p1[5];
printf("\nNAME = %s",p1[i].name);
void main()
{int i; printf("\nADDRESS =
clrscr(); %s\n",p1[i].address);
for(i=0;i<5;i++){ }
printf("Enter Details for Person %d\n",i+1); getch();
printf("Enter ID :\n"); }
scanf("%d",&p1[i].id);
printf("Enter Name :\n");
scanf("%s",&p1[i].name);
printf("Enter Address :\n");
scanf("%s",&p1[i].address);
}
21
Module No:4 ARRAYS, STRING, STRUCTURE AND UNION

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.

#include<stdio.h> printf("\n STUDENT INFORMATION


#include<conio.h> :");
struct Student{ printf("\nID = %d",s1.id);
int id; printf("\nNAME = %s",s1.name);
char name[20]; printf("\nMARKS= %f",s1.marks);
int marks;
getch();
}s1;
}
void main()
{clrscr();
printf("Enter ID :\n");
scanf("%d",&s1.id);
printf("Enter Name :\n");
scanf("%s",&s1.name);
printf("Enter Marks :\n");
scanf("%f",&s1.marks);

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.

– A union is identified in C through the use of the keyword ‘union’ in


place of the keyword struct.

– Virtually all other methods for declaring and accessing unions are
identical to those for structures.
Declaration of Union

 The general construct:


union tag_name
{ a
member1;
...
memberN; 1001 1002 1003 1004
}variable1,variable2,…,variableX;
b
 Example
union First{
c
char a;
3 members of union sharing memory location
int b;
float c;
};

33
Example

#include<stdio.h> printf("\nEnter values for b");


#include<conio.h> scanf("%d",&u1.b);
union First{
printf("\nb= %d",u1.b);
char a;
int b;
float c; printf("\nEnter values for c");
}u1; scanf("%f",&u1.c);
void main() printf("\nc= %f",u1.c);
{
getch();
clrscr();
printf("Enter values for a\n"); }
scanf("%c",&u1.a);
printf("\na= %c",u1.a);

34
Structure versus Union

35
STRUCTURE UNION

Memory allotted to structure is equal Memory allotted for union is equal to


to the space required collectively by the space required by the largest
all members of structure member of union

Structure requires more memory Union requires less memory

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.

All members of structure can be No attempt should be made to


initialized initialize more than one union
member.
Thank You
Subject Name: C Programming
Unit No:5
FUNCTIONS AND PARAMETER

1 Faculty Name : Dr. Gautam M Borkar


Index -

Lecture 32 – Introduction to Function 3

Lecture 33 – Function Parameters 18

Lecture 34 – Practice Programs 35

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

• Structured programming is a problem solving


strategy and a programming methodology that
Involves repeatedly decomposing a problem into
smaller problems
• Eventually leads to a collection of small problems
or tasks each of which can be easily coded
• The function construct in C is used to write code
for these small, simple problems.

4 Lecture 32: Introduction to Function


Introduction to Functions

• A ‘C’ program is made up of one or more functions.


• All C programs contain at least one function, called
main() where execution starts.
• Execution always begins with main( ), no matter where
it is placed in the program. By convention, main( ) is
located before all other functions.
• Basically there are two categories of function:
– Predefined functions: available in C standard
library such as stdio.h, math.h, string.h etc.
– User-defined functions: functions that
programmers create for specialized tasks

5 Lecture 32: Introduction to Function


Introduction to Functions

•When program control


Calling function()
encounters a function
{
//Body of calling function name, the function is
Function call; called (invoked).
//after function call –Program control
} passes to the
Called function() function.
{ –The function is
//Body of called function executed.
–Control is passed
} back to the calling
function

6 Lecture 32: Introduction to Function


Introduction to Functions

• Elements related to User defined Function


• Function prototype
• Function call
• Function parameters
• Function Definition

7 Lecture 32: Introduction to Function


Function Prototype Declaration

• The general form of function declaration statement is as


follows:
return_data_type function_name (data_type variable1,...);

Example:- void sum(); int sum();


int sum(int a,int b); void sum(int a,int b);
Or
return_data_type function_name (data_type_list)
Example:- int sum(int, int);

• Functions can be declared before main() or inside main


function but not after main().
8 Lecture 32: Introduction to Function
Function Prototype Declaration

• 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.

9 Lecture 32: Introduction to Function


Function arguments and parameters

• Arguments are also called actual parameters. Arguments are


written within parenthesis at the time of function call.
• Parameters are also called formal parameters. These are written
within parenthesis at the time of function definition.
• The number of parameters in the actual and formal parameter
lists must be consistent.
• Parameter association in C is positional.
• Actual parameters and formal parameters must be of
compatible data types.
• Actual (input) parameters may be a variable, constant, or any
expression matching the type of the corresponding formal
parameter.

10 Lecture 32: Introduction to Function


Function definition

• Function definition is a block of code which specifies the objective of the


function.
General form of Function definition is:-
return_data_type function_name (data_type variable1,...)
{
//body of function
}

• Arguments in function definition are called as formal arguments


• Return_type, name and number and type of arguments must be same in
function declaration, function definition as well as in function call.

11 Lecture 32: Introduction to Function


Function definition Example

Formal Arguments

int sum(int a,int b) void sum(int x,int y)


{ {
int c; int z;
c=a+b; z=x+y;
return c; printf(“sum of %d & %d = %d
} ”,x,y,z);
}

12 Lecture 32: Introduction to Function


Function call

The general form of function call are:


Return_data_type var=functin_name(var1,var2,…..);
Or
functin_name(var1,var2,…..);
var1, var2 etc are called as actual arguments. Actual Arguments

void main() void main()


{
int s=sum(10,15);
{
printf(“sum=%d”,s); sum(10,15);
} }

13 Lecture 32: Introduction to Function


Rules for Functions

• The name of a function is global.

• No function can be defined in another function body.

• Number of arguments must agree with the number of


parameters specified in the prototype.

• The function return type cannot be an array or a function


type.

14 Lecture 32: Introduction to Function


Thank You
Module No:5 Functions and Parameter

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);
}

17 Lecture 32: Passing Arguments


Example :with arguments, returns nothing

#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); }

18 Lecture 32: Passing Arguments


Example :without argument and returns value
Return type
#include<stdio.h>
OUTPUT
int sum();
Enter two numbers5
void main() 2
{ int c; Sum=7
c=sum();
printf("Sum=%d",c);
}
int sum(){
int x,y,z;
printf("Enter two numbers");
scanf("%d%d",&x,&y);
z=x+y;
return 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

• In call by value, a copy of the data is made and the copy is


sent to the function.

• The copies of the value held by the actual arguments are


passed by the function call.

• As only copies of the values held in the actual arguments


are sent to the formal parameters, the function cannot
directly modify the actual arguments passed.

21 Lecture 32: Passing Arguments


WAP to swap two no.’s using call by value mechanism

void swap(int,int); void swap(int x,int y)


void main() {
{ int z;
int a,b; z=x;
printf(“nter two no.’s”);
x=y;
scanf(“%d%d”,&a,&b);
y=z;
swap(a,b);
printf(“After swap, inside main printf(“After swap, inside
function--->”); swap function--->”);
printf(“a=%d\tb=%d”,a,b); printf(“x=%d\ty=%d”,x,y);
} }

22 Lecture 32: Passing Arguments


Output

enter two no.’s


10 20
After swap, inside main function--->a=10
b=20
After swap, inside swap function--->x=20
y=10

23 Lecture 32: Passing Arguments


CALL BY REFERENCE MECHANISM

• In call by reference, an address or reference of the actual


arguments is passed by function call.
• The address or reference of the actual arguments is sent
to/assigned to formal parameters.
• Hence the same set of values are accessed in calling and
called function
• Function can directly modify the actual arguments passed.

24 Lecture 32: Passing Arguments


WAP to swap two no.’s using call by reference mechanism

void swap(int *,int *); void swap(int *x,int *y)


void main() {
{ int z;
int a,b; z=*x;
printf(“enter two no.’s”); *x=*y;
scanf(“%d%d”,&a,&b);
*y=z;
swap(&a,&b);
printf(“After swap, inside
printf(“After swap, inside main
function--->”); swap function--->”);
printf(“a=%d\tb=%d”,a,b); printf(“x=%d\ty=%d”,*x,*y);
} }

25 Lecture 32: Passing Arguments


Output

enter two no.’s


10 20
After swap, inside main function--->a=20
b=10
After swap, inside swap function--->x=20
y=10

26 Lecture 32: Passing Arguments


Difference between call by value and call by reference

Call by value Call by reference

Values of actual arguments are passed Addresses of actual arguments are


passed
Another Copy of value is created Same copy is referred

No update to original arguments Updates original arguments

Example Example

27 Lecture 32: Passing Arguments


Benefits of functions

• It break up a program into easily manageable chunks


and makes programs significantly easier to understand.

• Well written functions may be reused in multiple


programs. eg. The C standard library functions.

• Functions can be used to protect data.

• Different programmers working on one large project can


divide the workload by writing different functions.

28 Lecture 32: Passing Arguments


Thank You
Module No:5 Functions and Parameter

Lecture No: 34
Practice Programs
WAP to calculate factorial of a number using function

#include<stdio.h> int factorial(int x)


int factorial(int); {
void main() int i,fact=1;
for(i=x;i>=1;i--)
{
{
int n,f; fact=fact*i;
printf(“Enter the no”); }
scanf(“%d”,&n); return fact;
f=factorial(n); }
printf(“\n Factorial of %d = %d”, n,f);
} Enter the no6

Factorial of 6 = 720

31 Lecture 34: Practice Programs


WAP to compare two strings using functions

#include <stdio.h> void compare(char str1[],char str2[])


#include<conio.h> {
void compare(char str1[],char str2[]); int i,flag=0;
void main() for (i = 0; str1[i] != '\0'; ++i){
{ if(str1[i] != str2[i])
char s1[100], s2[100]; {
int i,flag=0;
flag=1;
printf("Enter first string : "); break;
gets(s1); }
printf("Enter second string : "); }
gets(s2); if(flag==0)
compare(s1,s2); printf("Both Strings are Equal.");
getch(); else
} printf("Both Strings are Different.");
}
OUTPUT:
Enter first string : program
Enter second string : program
Both
32 Strings are
Lecture 34:Equal.
Practice Programs
WAP to check a number is prime or not using function.

#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);

printf ("Enter the elements of the matrix\n");


for (i = 0; i < row; i++) {
for (j = 0; j < col; j++)
{
scanf ("%d", &a[i][j]);
}
}
34 Lecture 34: Practice Programs
WAP to check whether given matrix is an identity matrix or not.
int Identity(int m[10][10],int r,int c)
flag=Identity(a,row,col);
{ int f=0;
int i,j;
if (flag == 0)
for (i = 0; i < r; i++) {
{ printf ("It is an IDENTITY MATRIX\n");
for (j = 0; j < c; j++) {
}
if (i == j && m[i][j] != 1)
else
{
{
f = -1;
printf ("It is NOT an identity matrix\n");
break;
}
}
else if (i != j && m[i][j] != 0)
return 0;
{
}
f = -1;
break;
}
}
}
return f;
}
35 Lecture 34: Practice Programs
Output

Enter the number of rows :3


Enter the number of columns :3
Enter the elements of the matrix
1
0
0
0
1
0
0
0
1
It is an IDENTITY MATRIX

36 Lecture 34: Practice Programs


Thank You
Subject Name: C Programming
Unit No:5
Functions and Parameter

Faculty Name : Dr. Gautam M Borkar


1
Index -

Lecture 35 – Recursion 3

Lecture 36 – Practice programs on recursion 11

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

Faculty Name : Dr. Gautam M Borkar


1
Index -

Lecture 37 – Introduction to Pointer 3

Lecture 38 – Pointer Arithmetic, Pointers to Pointers, Pointers and Array 15

Lecture 39 – Pointers and Function, Array of Pointers, Dynamic Memory Allocation 32

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

4 Lecture 37 – Introduction to Pointers 4


Computer Memory
• Computers store data in memory slots
• Each slot has an unique address
• If we have a variable var in the program, &var will give you its address in
the memory.
• We have used address numerous times while using the scanf() function.
• Variables store their values like this:

Addr Content Addr Content Addr Content Addr Content

1000 i: 37 1002 j: 46 1004 k: 58 1006 m: 74

1008 a[0]: ‘a’ 1009 a[1]: ‘b’ 1010 a[2]: ‘c’ 1011 a[3]: ‘\0’

5 Lecture 37 – Introduction to Pointers 5


Computer Memory (cont..)
• Altering the value of a variable is indeed
changing the content of the memory
– e.g. i = 40; a[2] = ‘z’;
Addr Content Addr Content Addr Content Addr Content

1000 i: 40 1002 j: 46 1004 k: 58 1006 m: 74

1008 a[0]: ‘a’ 1009 a[1]: ‘b’ 1010 a[2]: ‘z’ 1011 a[3]: ‘\0’

6 Lecture 37 – Introduction to Pointers 6


Example on getting address of variable :
#include <stdio.h>
void main()
{
int var = 5;
printf("var: %d\n", var);
// use of & before var gives the adress
printf("address of var: %p", &var);
}
Output :
var: 5
address of var: 2686778
Note : & is called as address-of or reference operator
7 Lecture 37 – Introduction to Pointers 7
Pointer Variables
• It is a variable that stores the memory address of
another entity.
OR
• It refers to or points to a memory locations.
OR
• Pointers contain memory addresses as their
values.

88 Lecture 37 – Introduction to Pointers


Declaring Pointer Variables
• Like ordinary variables, pointer variable must be declared before
they are used.
• Declaration form
– datatype *pointer_variable;
• The * tells the compiler that this is pointer variable.
• * is called the dereference operator.
• Pointer variable will point to the given datatype
• Declaration Style
– int* iptr;
– int *iptr;
– int * iptr;
• It operates on a pointer and gives the value stored in that pointer.

99 Lecture 37 – Introduction to Pointers


What actually ptr is?
• ptr is a variable storing an address
• ptr is NOT storing the actual value of i

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
}

11 Lecture 37 – Introduction to Pointers 11


Pointer Concepts 3 :
#include<stdio.h> c 5
void main()
{
int* ptr, c, d; pt address of d
c
c = 5;
d = -15;
r
ptr = &c; d -15
printf("%d\n", *ptr);
ptr = &d;
printf("%d\n", *ptr); Output:
} 5
-15

13 Lecture 37 – Introduction to Pointers 13


Pointer Arithmetic

• What’s ptr + 1?

The next memory location!

• What’s ptr - 1?

The previous memory location!

• What’s ptr * 2 and ptr / 2?

Invalid operations!!!

Lecture 38 – Pointer Arithmetic, Pointers to Pointers,


16 16
Pointers and Array
Program on Pointer Arithmetic :
#include<stdio.h>
void main() Output:
{ 1 1
int i, j, k; 2358840 2358836
int *a, *b; 1 2 2
i=1;
j=1;
printf("%d\t%d\n", i, j);
a = &i;
b = &j;
printf("%d\t%d\n", a, b);
k = *a;
*b=++k;
printf("%d\t%d\t%d\n", i, j, k); }
Lecture 38 – Pointer Arithmetic, Pointers to Pointers,
17 17
Pointers and Array
Pointer to Pointer
• A pointer is used to store the address of a variable in C.
• We can also define a pointer to store the address of another pointer.
• Such pointer is known as a double pointer (pointer to pointer).
• The first pointer is used to store the address of a variable whereas the
second pointer is used to store the address of the first pointer.

•Syntax :
int **p; // pointer to a pointer which is pointing to an integer

Lecture 38 – Pointer Arithmetic, Pointers to Pointers,


18 18
Pointers and Array
Program on Pointer to Pointer :
#include<stdio.h> Output:
void main () address of a: 23fe44
{ address of p: 23fe38
int a = 10; value stored at p: 10
int *p; value stored at pp: 10
int **pp;
p = &a;
pp = &p;
printf("address of a: %x\n",p);
printf("address of p: %x\n",pp);
printf("value stored at p: %d\n",*p);
printf("value stored at pp: %d\n",**pp);
}
Lecture 38 – Pointer Arithmetic, Pointers to Pointers,
19 19
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) ?
ptr++;
a[3] float float array element (variable) ?
*ptr = 9.0;
ptr float * float pointer variable
ptr = ptr - 3; *ptr float de-reference of float pointer variable ?
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Lecture 38 – Pointer Arithmetic, Pointers to Pointers,
20 20
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) ?

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 ?

*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 = &(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[3]

ptr = ptr - 3; *ptr float de-reference of float pointer variable ?


*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Lecture 38 – Pointer Arithmetic, Pointers to Pointers,
23 23
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) 9.0
*ptr = 9.0;
ptr float * float pointer variable address of a[3]
ptr = ptr - 3;
*ptr float de-reference of float pointer variable 9.0
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Lecture 38 – Pointer Arithmetic, Pointers to Pointers,
24 24
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) 9.0
*ptr = 9.0;
ptr float * float pointer variable address of a[0]
ptr = ptr - 3;
*ptr float de-reference of float pointer variable ?
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Lecture 38 – Pointer Arithmetic, Pointers to Pointers,
25 25
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 = &(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) 9.0
*ptr = 9.0;
ptr float * float pointer variable address of a[0]
ptr = ptr - 3;
*ptr float de-reference of float pointer variable 6.0
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Lecture 38 – Pointer Arithmetic, Pointers to Pointers,
26 26
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 = &(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) 9.0

*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,
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 = &(a[2]); a[1] float float array element (variable) ?

*ptr = 3.14; a[2] float float array element (variable) 7.0

ptr++; a[3] float float array element (variable) 9.0

*ptr = 9.0; ptr float * float pointer variable address of a[2]

ptr = ptr - 3; *ptr float de-reference of float pointer variable 7.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 39 – Pointers and Function, Array of Pointers, Dynamic


31
Memory Allocation
Call By Value Mechanism

• In call by value, a copy of the data is made and the copy is


sent to the function.

• The copies of the value held by the actual arguments are


passed by the function call.

• As only copies of the values held in the actual arguments


are sent to the formal parameters, the function cannot
directly modify the actual arguments passed.

Lecture 39 – Pointers and Function, Array of Pointers, Dynamic


36
Memory Allocation
Program : WAP to swap two no.’s using call by value
mechanism
#include<stdio.h> void swap(int x,int y)
void swap(int,int); {
void main()
{ int z;
int a,b; z=x;
printf(“Enter two no.’s”); x=y;
scanf(“%d%d”,&a,&b);
y=z;
swap(a,b);
printf(“After swap, inside main printf(“After swap, inside
function--->”); swap function--->”);
printf(“a=%d\tb=%d”,a,b); printf(“x=%d\ty=%d”,x,y);
}
}
Lecture 39 – Pointers and Function, Array of Pointers, Dynamic
37
Memory Allocation
Output
enter two no.’s
10 20
After swap, inside swap function--->x=20 y=10
After swap, inside main function--->a=10 b=20

Lecture 39 – Pointers and Function, Array of Pointers, Dynamic


38
Memory Allocation
Call By Reference Mechanism
• In call by reference, an address or reference of the actual
arguments is passed by function call.
• The address or reference of the actual arguments is sent
to/assigned to formal parameters.
• Hence the same set of values are accessed in calling and
called function
• Function can directly modify the actual arguments passed.

Lecture 39 – Pointers and Function, Array of Pointers, Dynamic


39
Memory Allocation
Program : WAP to swap two no.’s using call by
reference mechanism
void swap(int *,int *); void swap(int *x,int *y)
void main() {
{
int z;
int a,b;
z=*x;
printf(“enter two no.’s”);
scanf(“%d%d”,&a,&b); *x=*y;
swap(&a,&b); *y=z;
printf(“After swap, inside main printf(“After swap, inside
function--->”); swap function--->”);
printf(“a=%d\tb=%d”,a,b); printf(“x=%d\ty=%d”,*x,*y);
}
}
Lecture 39 – Pointers and Function, Array of Pointers, Dynamic
40
Memory Allocation
Output
enter two no.’s
10 20

After swap, inside swap function--->x=20 y=10


After swap, inside main function--->a=20 b=10

Lecture 39 – Pointers and Function, Array of Pointers, Dynamic


41
Memory Allocation
Difference between call by value and call by reference

Call by value Call by reference

Values of actual arguments Addresses of actual


are passed arguments are passed
Another Copy of value is Same copy is referred
created
No update to original Updates original arguments
arguments
Example Example

Lecture 39 – Pointers and Function, Array of Pointers, Dynamic


42
Memory Allocation
Output
Enter no. of elements:5
12
14
5
8
24
Total sum= 63

Lecture 39 – Pointers and Function, Array of Pointers, Dynamic


44
Memory Allocation
Dynamic Memory Allocation
• An array is a collection of a fixed number of values. Once the size of an
array is declared, we cannot change it.
• Sometimes the size of the array declared may be insufficient.
• To solve this issue, we can allocate memory manually during run-
time.
• This is known as dynamic memory allocation in C programming.
• Functions used for Dynamic Memory Allocation :
– malloc()
– calloc()
– free()
• These functions are defined in the <stdlib.h > header file

Lecture 39 – Pointers and Function, Array of Pointers, Dynamic


46 46
Memory Allocation
malloc() Function
• The name "malloc" stands for memory allocation.
• The malloc() function reserves a block of memory of the
specified number of bytes. And, it returns a pointer of void which
can be casted into pointers of any form.
• Syntax :
ptr = (castType*) malloc(size);
• Example :
ptr = (float*) malloc(100 * sizeof(float));
 Allocates 400 bytes of memory. It's because the size of float is
4 bytes.
 The pointer ptr holds the address of the first byte in the
allocated memory.
• The expression results in a NULL pointer if the memory cannot
be allocated.

Lecture 39 – Pointers and Function, Array of Pointers, Dynamic


47
Memory Allocation
Example on malloc() Function :
#include<stdio.h>
Output :
#include<conio.h>
#include<stdlib.h> 1442
void main() 20
{
int *ptr;
ptr=(int*)malloc(sizeof(int));
*ptr=20;
printf("%u\n",ptr);
printf("%d\n",*ptr);
getch();
}
Lecture 39 – Pointers and Function, Array of Pointers, Dynamic
48
Memory Allocation
calloc() Function
• The name "calloc" stands for contiguous allocation.
• The malloc() function allocates memory and leaves the memory
uninitialized, whereas the calloc() function allocates memory
and initializes all bits to zero.
• Needs two arguments
- number of variables to allocate in memory
- size in bytes of a single variable
• Syntax :
ptr = (castType*)calloc(n, size);
• Example:
ptr = (float*) calloc(25, sizeof(float));
 Allocates contiguous space in memory for 25 elements of type
float.

Lecture 39 – Pointers and Function, Array of Pointers, Dynamic


49
Memory Allocation
Example on calloc() Function :
#include<stdio.h> Output :
#include<conio.h> 1446 10
#include<stdlib.h> 1448 20
void main()
{
int *ptr, i;
ptr=(int*)calloc(2,2);
*ptr=10;
printf("\n%u \t %d",ptr,*ptr);
*(ptr+1)=20;
printf("\n\n%u \t
%d",ptr+1,*(ptr+1));
getch();
Lecture 39 – Pointers and Function, Array of Pointers, Dynamic
} 50 50
Memory Allocation
free() Function
• Dynamically allocated memory created with either calloc()
or malloc() doesn't get freed on their own.
• We must explicitly use free() to release the space.
• Syntax :
free(ptr);
 statement frees the space allocated in the memory
pointed by ptr.

Lecture 39 – Pointers and Function, Array of Pointers, Dynamic


51
Memory Allocation
Module No:5

Lecture No:
Storage Classes –Auto , Extern
, Static,Register
Scope Rules

The region of the program over which the declaration of an


identifier is accessible is called the scope of the identifier.
The scope relates to
what is the initial value of variable
where it is stored
where it is available
how long it is available to use
Scopes can be of three types.
Block
Function
Program
STORAGE CLASSES

Storage Keyword Initial Storage Scope life


class used value location

Automatic auto garbage memory Within a Till the end of the


block or block or function
function
Register register garbage CPU register Within a Till the end of the
block or block or function
function
Static static Zero memory Within a Value persists
block or between different
function function calls
External extern zero memory Within a Till the end of the
program program
Example : auto

void main() Output


{ a=10 b=1278
int a=10,c; c=3454
auto int b;
printf(“a=%d\tb=%d\tc=%d
”,a,b,c);
}
Example: register

void main() Output


{ 1
2
register int i; 3
4
for(i=1;i<=5;i++) 5
{
printf(“%d\n”,i);
}
}
Example

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

int x,y,z; y++;


a();
void a(); getch();
void main() }
{ void a()
{
extern int y; printf("\n Inside a:");
int x; printf("\tx=%d",x);
int z; printf("\ty=%d",y);
printf("\tz=%d",z);
clrscr(); }
printf("inside main:");
printf("\tx=%d",x); //local value output
printf("\ty=%d",y); //global value inside main: x=1234 y=0 z=0
inside a: x=0 y=1 z=0
printf(“\tz=%d",::z); //global value
Thank You

You might also like