You are on page 1of 113

Program Development

Using C Language

ELTP-CAMPUS
EXCELLENT CAMPUS PLACEMENTS 1 ELTP-GROUP
Problem Solving & Programming Fundamentals using C

1. Problem Solving using flowchart

2 Introduction
2. I t d ti to t C Language
L

3. Data Type
yp

4. Input / Output Statements

5. Type Conversion

6 Operator
6. O t

7. Control Statements
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 2
Problem Solving using flowchart

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 3
Representation of Computation
Using Flowchart

 A fl
flowchart
h t is
i a diagrammatic
di ti representation
t ti off computation
t ti

 A flowchart is an organized
g combination of shapes,
p , lines and

text that graphically illustrates a computation process

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 4
Flowcharting Symbols

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 5
Basic Program Control

1 Sequential
1.
2. Selection
3. Iteration

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 6
Sequential Control

• In sequence
• One-after-the-other
Statement 1

Statement 2

Statement 3

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 7
Selection Control

Statement 1

Decision

Statement 2a Statement 2b

Statement 3

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 8
Iteration(Loop) Control

1.
Initialization initialization
of loop index
of loop index

Modify
y Loop
p 4. Update of
Index loop index
T
cond_expr

2. loop F
condition

Loop body
(S) 3. Task
Repeat

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 9
Example-1
Draw a flow chart to sum of given two integer numbers
Start

Get a

Input
Get b

Sum = a + b

Output
p Process
Put Sum

End

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 10
Example-2

Draw a flowchart to check whether a year is Leap year or not?

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 11
Draw a flowchart to check whether a year is Leap year or not?

Solution Start

Get year

If (year % 400 = = 0) OR F
( year % 100 ! = 0 AND year % 4 = = 0)

Put “year is not leap year”


T

Put “year is leap year”

End

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 12
Example-3
Draw a flowchart to sum of given N integer numbers

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 13
Draw a flowchart to sum of given N integer numbers
Start

Get N

I=1 S
Sum =0 loop
(initialization I=1 condition
of loop
index))
If
F
I<=N
? Put Sum
T

Get temp End

Modification
Sum = Sum + temp
of loop
index
Loop
I=I+1
Body

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 14
General C Program Structure
Pre-Processor Directives

functions declarations

void main()

local variables to function main (Declaration and


initialization)

statements associated with function main ;


}
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 15
C program structure

#include <stdio.h> Pre processor directive

void main()
Entry point for
{ /* start of main function*/ program execution

printf(“Hello World”);
Each instruction in a C
} /* end of main function*/ program terminates with a
semicolon (;)

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 16
Example-1
Draw a flow chart to sum of given two integer numbers
Start

Get a

Input
Get b

Sum = a + b

Output
p Process
Put Sum

End

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 17
C program to sum of given two integer numbers.
#include <stdio.h> /* Pre-processor
p command */
void main(){ /* Start execution of program */

int a,
a b,
b sum;/
sum;/* Declaration of local variable *//

printf(“Enter First Number:“);/* Message to display on screen */

scanf(“%d“, &a); /* Input from keyboard */

printf(“Enter Second Number: “);

scanf(“%d“, &b);

sum = a + b;; /* Processing


g */

printf(“Sum of two numbers is : %d”,sum); /* To display Output */

} /* End of execution of program */


ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 18
Home Assignment

1. Draw a flowchart to Sum of first N natural numbers

2. Draw a flowchart to find the Sum of Series

1 + 1/2 + 1/3 + 1/4 + … + 1/N

3. Draw a flowchart to Sum of first N even numbers.

4. Draw a flowchart to Sum of first N odd numbers.

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 19
Home Assignment
Draw a flowchart to Sum of the following series of N terms:-

5 20 + 21 + 22 + 23 …………..
5.

6. 0 + 3/4 + 8/9 + 15/16 + 24/25 + 35/36

7. 1+ x2/2! + x4/4! + ......... [0 < x < 1]

8. Draw a flowchart to find sum of only positive number in


given N numbers

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 20
Home Assignment
9. Draw a flowchart to check whether a number is perfect
square or not

10. Draw a flowchart to print sum of digits of a given


positive integer accepted from the user.

11. Draw a flowchart to check whether a 3 digit number is


palindrome or not?

12 Draw a flowchart to print Fibonacci Series.


12. Series

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 21
Home Assignment

13 D
13. Draw a fl
flowchart
h t tto print
i t N rows off th
the ffollowing
ll i pattern:
tt
1
12
123
1234
12345
14. Draw a flowchart to print N rows of the following pattern:
1
22
333
4444
55555

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 22
Home Assignment

15. Draw a flowchart to print N rows of the following pattern:

12345
1234
123
12
1

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 23
Introduction of Function

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 24
What is a Function?
• A sub
b program th
thatt does
d a specific
ifi ttask.
k

• A unit of program code, as per syntax, to perform specific


and well defined task.

Function-1
u ct o in need
eed o
of service
se ce
from function 2

Function-1 requests Function-2

Function 1 Function 2
{ Tasks } { Tasks }

Function 2 services Functioa

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 25
Classification of Functions
1. Library functions

- provided along with the compiler

Ex: printf(), scanf()

2. User Defined functions

- written by the user

Ex: main()

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 26
Elements of a Function

 Function Declaration or Function Prototype :

- The function should be declared prior to its usage.

 Function Definition :

- Implementing
p g the function or writing
g the task of the function.

 Function Invocation or Function call:

- To utilize a function’s
function s service we have to invoke( call ) the
function.

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 27
Example – Function Terminologies
void
id display()
di l () ; Function Prototype

void main() {
di l ()
display(); Calling Function Definition

void display() {
printf(“Hello World”); Function Call Statement
}

Called Function Definition

Called Function

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 28
C program structure

stdio.h file include function


#include <stdio.h>
declaration of library function
void main() printf( ) and scanf () etc.

{ Function Definition of
main() function
printf(“Hello World”);

} Call function printf()

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 29
Phases of C/C++ Programs:

Editor

Source Header Files

Preprocessor

Compiler

Object File

Linker Libraries

Executable File (Binary File)

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 30
C Files (Source Code) Header Files

Phases of
C/C P
C/C++Programs prog.c help.c strtest.c stdio.h func.h

Text Editor

C COMPILER

Pre-Processor

COMPILER
Windows: cl.exe
Intermediate UNIX: cc
C d
Code LINUX: gcc

Software Developer

Compiler

1011 101101
0101
Object Files 010101 11
101
101010
011101 10101 010
110 1010101 101
prog.obj help.obj strtest.obj 10011 111

Runtime
Libraries
LINKER:
Windows: link.exe Linker
UNIX: ld
LINUX: ld

ELTP-CAMPUS Executable File


(prog.exe) ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 31
Program is created in
Phases of Editor Disk the editor and stored
on disk.

C/C++Programs Preprocessor Disk


Preprocessor program
processes the code.
Compiler creates
1. Edit Compiler
p Disk object
j code and stores
it on disk.
Linker links the object
2. Preprocess Linker Disk code with the libraries,
creates exe file and
Primary
Primar stores it on disk
3. Compile Loader
Memory

4. Link Loader puts program


in memory.
Disk
..
5. Load ..
..
Primary

6. Execute CPU
Memory
CPU takes each
instruction and
executes it, possibly
storing
sto g new
e data
.. values as the program
..
ELTP-CAMPUS ..
executes.
ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 32
Data Types

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 33
Data Types

Data types determine the following:

– Type of data stored

– Number of bytes it occupies in memory

– Range of data

– Operations that can be performed on the data

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 34
Data Types(Cont’d)
D t ttypes
Data

User defined types Derived types


Structure Array
Union Fundamental types Function
Enumeration Pointer

integer type void floating type

int char float double

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 35
Data Types(Cont’d)
C supports the
h following
f ll i P i i i Data
Primitive D Types:
T
– int – for storing whole numbers

– char – for storing character values, represents a single


character

– float

– Double

Note: float and double data types are used to store fractional
values and also Integer.

float can store upto 6 digits of precision

double can store upto 12 digits of precision

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 36
Data Types (Continued…)

• Modifiers alter the meaning of the base type to more precisely fit a
specific need.

• The modifiers define the amount of storage allocated to the variable.

• All modifiers short, long, signed and unsigned can be used along
with int data type.

• C does not have a Boolean data type.

In C, a true value is any non zero value including negative numbers.

A false value is zero.


zero

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 37
Literals
• Literals refer to fixed values that the program does not alter.

• The way each literals is represented depends upon its type.

Ch
Character
t lit
literals
l are enclosed
l d iin single
i l quotes
t

Ex: ‘A’, ‘*’

Integer literals are specified as numbers without the fractional part.

Ex: 10, 456

Floating point literals are of double data type by default and is


represented along with the decimal point.
This is
Ex: 10.24 is of double data type What is this? string
literal
yp
10.24F is of float data type
“Hello World”
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 38
Variables

• Hold the data in your program


• Aq
quantity
y that can change
g during
g p
program
g execution
• Is a location (or set of locations) in memory where a value
can be stored for use byy a p program
g

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 39
Variable Names in C programming language
• A variable name can either begin with an alphabet or
underscore
• No other special character except underscore is allowed
• Variable names are case sensitive
• Keywords cannot be used as variable names

 amount_in$
$
Which of these
 2many variable names
 if are valid ones?
 _iTotal

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 40
Declaration of variables
Syntax:
data-type [variable-name list] Initial
value of
data-type variable-name1 , variable-name2, … ;
variable
Ex: iNum
int iNum ;
Address
declares a variable off int data type off iNum
iN
in
The variables will contain some garbage value when they are declared.
memory
A variable can be initialized when it is declared
int iNum = 10; 10
22FA06
float fData = 2.3F ;
iNum
char cChoice = ‘Y’;

All variables must be declared in the beginning


g g of the block

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 41
Input / Output Library Functions

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 42
Output Statement
Writes onto screen (Standard Output)
Syntax:
printf (“conversion specifier or string”, variables if any);
Ex:
printf(“Hello World”);
printf(“Hello World\n Welcome”);
printf(“%d”, a);
printf(“%f” x);
printf(“%f”,
printf(“%c”, y);
printf(“%d%d%f”,
printf( %d%d%f , j, k, a);
printf(“The sum of %d and %d is %d”, a, b, c);

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 43
Output Statement (Continued…)
Conversion Specifier
• These characters tell the input or output functions as to what
t
type off data
d t is
i being
b i read
d or written.
itt

• Few Format Specifiers that can be used in a printf statement:


– %d signed decimal integers

– %u unsigned decimal integers

– %f decimal floating point

– %c character

– %s string

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 44
Input statement
We can perform
W f the
th input
i t operation
ti in
i C using
i the
th function
f ti scanff
Syntax:
scanf (“conversion specifier(s)”, variable(s))
Format specifier’s in c:
%d- for int When user enters 10
%l - for long
g 0A
%f - for double and float datatype
&iNum 12FF78
%c - for characters returns the
%s - for strings address

Ex: scanf(“%d%d%f”, &iNum, &iMarks, &fData);


scanf(“%c”
scanf( %c , &cChoice);
Common programming error:
Here & is the address operator
Forgetting ‘&’ before the
variable name
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 45
Type Conversion and Type Casting

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 46
Type Conversion (1 of 2)
• When variables off one type are mixed with variables off
another type, type conversion will occur.
• A variable of one type can receive the value of another
type.
• Type Conversion can be of two types:
■ Widening Conversion
■ Narrowing
N i C Conversion
i

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 47
Type Conversion (2 of 2)
 Widening Conversion
int i = 10;
d bl d;
double d
d = i;
printf(“%d” d);
printf(“%d”, d)

 Narrowing conversion

doubled = 10.856;
int i;
i = d;
printf(“%d”
printf( %d , i);
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 48
Arithmetic Conversions

char

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 49
What is the output of the following code snippet?

#include <stdio.h>
main() {
int i = 17;
char c = 'c'; /* ASCII value is 99 */
float sum;
sum = i + c;;
printf("Value of sum : %f\n", sum );
}

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 50
Type Casting
we have to explicitly specify the type cast operator

■ This prevents accidental loss of data

int i = 5;;
double d = 10.85;
d = i + ((int)) d;;

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 51
What is the output of the following code snippet?

#include<stdio.h>

void main(){

int i = 5, j = 2,k = 3,total;

fl t avg;
float

total = i + j + k;

avg = total/3;

printf("%.2f",avg);

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 52
What is the output of the following code snippet?

#include<stdio.h>

void main(){

int i = 5, j = 2,k = 3,total;

fl t avg;
float

total = i + j + k;

avg = total/3.0;

printf("%.2f",avg);

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 53
What is the output of the following code snippet?

void main() {

float a=12
a=12.25;
25;

printf(" %f %d %f ", a, (int)a, a - (int)a);

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 54
Operators In C

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 55
Operators In C
O
Operators are predefined
d fi d symbol
b l iin llanguage to
perform specific operation on operands.
Classification of Operators:
(1) Based on the number of operands:
(1) Unary operators ++, --
(2) Binary operators +,-,*,/,%,==,<,>,>=,<=,!=,&&,||
(3) Ternary operators ? :
(2) Based on the operations performed:
(1) Arithmetic operators
(2) Relational operators
(3) Logical operators

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 56
What is the output of the following code snippet?
main() {

int a = 5, b = 3, c = 8, d = 7;

printf(“%d”, b + c / 2 - d * 4 % a);

}
How to find out order in which operators
p p
perform in expr?
p
Operator Table
Operators in order of precedence (highest to lowest).
Their associativity indicates in what order operators of
equal precedence in an expression are applied.
applied
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 57
Operator Description Associativity
() Parentheses left-to-right
[] Brackets (array subscript)
. Member selection via object
j name
-> Member selection via pointer
++ , -- Prefix increment/decrement right-to-left
+, - Unary plus/minus
!, ~ Logical
g negation/bitwise
g complement
p
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation
* ,/, % Multiplication/division/modulus left-to-right
+ ,- Addition/subtraction left-to-right
<< , >> Bitwise shift left, Bitwise shift right left-to-right
< , <= Relational
R l ti l less
l than/less
th /l than
th or equall to
t l ft t i ht
left-to-right
> , >= Relational greater than/greater than or equal to
== , != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
ELTP-CAMPUS
= Assignment ELTP-GROUP
right-to-left
EXCELLENT
, CAMPUS
Comma (separatePLACEMENTS
expressions)
58
left-to-right
Operator Description Associativity
() Parentheses left-to-right
++ , -- Prefix increment/decrement right to left
right-to-left
+, - Unary plus/minus
! Logical negation
(type) Cast (convert value to temporary value of type)
& Address (of operand)
sizeof Determine size in bytes on this implementation
* ,/, % Multiplication/division/modulus left-to-right
+ ,- Addition/subtraction left-to-right
< , <= R l ti
Relational
l less
l than/less
th /l than
th or equall to
t l ft t i ht
left-to-right
> , >= Relational greater than/greater than or equal to
== , != Relational is equal to/is not equal to left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
right to left
= Assignment
ELTP-CAMPUS right-to-left
ELTP-GROUP
EXCELLENT
, CAMPUS
Comma PLACEMENTS
(separate expressions) 59 left-to-right
What is the output of the following code snippet?

main()

char ch = 'A'; /* ASCII value is 65 */

int b = 3, c = 5,d = 4;

float g = 2.5;

printf ("%c", ch + c / d + (int) g * b);

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 60
What is the output of the following code snippet?

#include<stdio.h>

main(){

char ch = 'A'; /* ASCII value is 65 */

int a = 3, c = 5;

float d = 2.5, e = 7.5, f = 7.5;

ch = a + e * (int) f + d * c;

printf("%c", ch);

}
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 61
What is the output of the following code snippet?
#include<stdio.h>
# c ude std o
main()
{
int x = 0;
int y = 0;
if ((++x || ++y))
{
x++;;
}
printf("%d %d\n",x, y);
}
a) 1 0 b) 1 1 c) 2 1 d) 2 0

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 62
What is the output of the following code snippet?

#include<stdio.h>
main()
{
int x = 0;
int y = 0;
if (!(x++ && ++y))
{
++x;
}
printf("%d
printf( %d %d\n"
%d\n ,x,
x y);
}
a) 0 0 b) 1 0 c) 2 0 d) 2 1

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 63
What is the output of the following code snippet?

#include<stdio.h>
main()
{
int x = 0;
int y = 0;
if (!x++ && ++y)
{
++x;
}
printf("%d
printf( %d %d\n"
%d\n ,x,x y);
}
a) 0 0 b) 1 0 c) 2 0 d) 2 1

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 64
Program Development Using C Language

Control statements

ELTP-CAMPUS
EXCELLENT CAMPUS PLACEMENTS 65 ELTP-GROUP
Control statements

• Control statements specify the order of the execution


of the statements in the program.

• Control statements are of 2 types:

1. Selectional

2. Iterational

• Selectional and Iterational statements are of 2 types:

1 unconditional
1. diti l control
t l statements
t t t

2. conditional control statement

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 66
Selectional Statement

Used for deciding on which action to take

if (expr)
( )
if (expr) if (expr) stmt1;
stmt1; stmt1; else if (expr)
else stmt2;
stmt2; else if (expr)
……
else
stmtn;

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 67
Selectional Statement

if (expr)
stmt1;
F
expr

stmt1;
t t1

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 68
WAP to find the largest of three numbers using if statement

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 69
WAP to find the largest of three numbers using if statement
#include <stdio.h>
void main() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d
f("%d %d %d"
%d", &
&a, &b
&b, &
&c);
)
if( a >= b && a >= c )
printf("%d
printf( %d is the largest number
number.", a);
if( b >= a && b >= c )
printf("%d
p ( is the largest
g number.",, b);
);
if( c >= a && c >= b )
printf("%d is the largest number.", c);}

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 70
Selectional Statement
if (expr)
stmt1;
else expr F
stmt2;

stmt1;
t t1 stmt2;
t t2

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 71
Write C program to find the largest of three numbers using
nested of if...else statement

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 72
Write C program to find the
int a, b, c;
printf("Enter three numbers: "); largest of three numbers using
scanf("%d %d %d", &a, &b, &c);
nested if and if...else statement
if (a>=b)
{
if(a>=c)
printf("%d is the largest number.", a);
else
l
printf("%d is the largest number.", c);
}
else{
if(b>=c)
printf("%d
printf( %d is the largest number.",
number. , b);
else
printf("%d is the largest number.",c);
}
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 73
Selectional Statement

if (expr)
F
stmt1; expr
else if (expr)
stmt2; T expr F
else
stmt3; T
stmt1;
t t1 stmt2; stmt3;
t t3

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 74
Write program that reads marks of a student and
computes displays grade
computes,

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 75
Selectional Statement
if (mark >=> 90)
printf(“Grade A”);
F
else if (mark >= 80) mark >= 90
printf(“Grade B”);
else T F
mark >= 80
printf(“Grade
printf( Grade C”);
C );
T
P t ‘A’
Put Put ‘B’ P t ‘C’
Put

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 76
Write program that reads marks of a student and computes and displays grade

int mark;

scanf(“ %d”, &mark);

If( mark >= 90)

printf("The Grade of student is = ‘A’”);

elseif( mark >= 80)

printf("The Grade of student is = ‘B’”);

elseif( mark >= 70)

printf("The Grade of student is = ‘C’”);

elseif( mark >= 60)

printf("The Grade of student is = ‘D’”);

else

printf("The
i tf("Th Grade
G d off student
t d t is
i = ‘E’”);
‘E’”)
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 77
Write c program to find the largest of three numbers
using if...elseif…else statement

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 78
Write c program to find the largest of three numbers using if...elseif…else
statements
int a, b, c;

printf("Enter three numbers: ");

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

if( a>=b && a>=c)

printf("%d is the largest number.", a);

else
l if (b>=a
(b> && b>
b>=c))

printf("%d is the largest number.", b);

else

printf("%d
printf( %d is the largest number
number.", c);
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 79
Looping Statements:– for loop statement
Repeat
p an action specified
p number of times

initialization
Syntax for loop stmt:
(expr1)

for(expr1;expr2;expr3) Modify Loop Index


{ (expr3)
S; expr2
p
T
} F

Loop body
(S)

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 80
Write a C p
program
g to find the sum of first N natural numbers

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 81
Write a C program to find the sum of first N natural numbers

#include<stdio.h>

main(){

int n, sum=0, i;

scanf(“
f(“ %d”
%d”, &n);
& )

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

sum = sum + i;

printf("The Sum of first %d natural number is = %d", n, sum);

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 82
Write a C program to sum of given N numbers.
#include<stdio.h>
void main(){
unsigned int n, i;
int temp;
long int sum =0;
printf("Enter Number Count (Positive Decimal Value from 0 to 65535):");
scanf("%u", &n);
for (i=1;i<=n; i++){
printf("Enter
i tf("E t %d number:",i);
b " i)
scanf("%d", &temp);
sum = sum + temp;
}
printf ("\n\nSum of %u Numbers is = %ld", n, sum);
}
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 83
Write a C program to find the multiplication of two
unsigned integer without using multiplication operator

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 84
Write a C program to find the multiplication of two
g
unsigned integer
g without using
g multiplication
p operator
p

#include<stdio.h>

main(){

unsigned int a, b, loopindex;

unsigned long int muti = 0;

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

for(loopindex = b; loopindex >= 1; loopindex--)

muti = muti + a; /* end of for loop body*/

printf("The Multiplication of %u and %u is = %u", a, b, muti);

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 85
Looping Statements – while
Repeat an action till the expression evaluates to false

while(expr){
hil ( ){
S;
} expr

Loop Body
(S)

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 86
W it a C program to
Write t find
fi d the
th average marks
k off three
th
subjects of each student in a class

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 87
Write a program to find the average marks of three subjects of
each student in a class
fl t Avg;
float A

int Mark1, Mark2 , Mark3, Sum;

char
h Choice
Ch i = 'y';
' '

while( (Choice == 'Y') || (Choice == 'y') ) {

scanf("%d%d%d",
f("%d%d%d" &Mark1,
&M k1 &Mark2,
&M k2 &Mark3);
&M k3)

Sum = Mark1 + Mark2 + Mark3;

A =S
Avg Sum/3.0;
/3 0

printf("The Avg. Marks is = %f\n", Avg);

printf("Do you wish to continue? Enter Y/N or y/n :");

scanf("%c", &Choice);

} /* end of while loop*/


ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 88
Write a C program to find the quotient and remainder
to divide two unsigned integers without using
division and remainder operator.

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 89
Write a C program to find the quotient and remainder to divide two
unsigned integers without using division and remainder operator.
#include<stdio.h>
main(){
unsigned int a, b, rem, quot=0;
scanf("%u %u", &a, &b);
rem = a;
while(rem >= b){
rem = rem - b;;
quot++;
} // End of while loop
printf("Divide %u by %u : ", a, b);
printf("quotient = %u and remainder = %u", quot, rem);
}
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 90
Looping Statements : do - while

do-while: (post-test) Loop Body


(S)

do{
S; expr
}while(expr);

Exit control loop

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 91
C Program to add numbers until user enter 0 from keyboard

using do while loop

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 92
C Program to add numbers until user enter 0 from keyboard
using do while loop
#include<stdio.h>
void main() {
int number, sum = 0;
do {
printf("do
i tf("d you wantt tto stop
t addition
dditi enter
t 0 otherwise
th i enter
t number:");
b ")
scanf("%d", &number);
sum = sum + number;
} while(number != 0); /* end of do while loop*/
printf("Sum
p ( = %d",, sum);
);
}

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 93
C Program to add numbers until user enter 0 from keyboard

using while loop

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 94
C Program to add numbers until user enter 0 from keyboard
using while loop
#include<stdio.h>

void main() {

int number = 1, sum = 0;

while(number
( != 0){
){

printf("do you want to stop addition enter 0 otherwise enter number:");

scanf("%d"
scanf( %d , &number);

sum = sum + number;

}/* End of while loop*/

printf("Sum = %d", sum);

}
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 95
break Statement:
The break statement is used to:

Force the termination of a loop.

When a break statement is encountered in a loop, the loop


terminates immediately and the execution resumes the
next statement following the loop.
Note:

• Break statement can be used in an if statement only when the if


statement
t t t is
i written
itt ini a loop.
l

• Just an if statement with break leads to compilation error in C.

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 96
What is the output of the following code snippet?
main()
{
i t j;
int j

for (j = 0; j < 5; j++)

printf(“ %d \t ", j);


}

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 97
What is the output of the following code snippet?
main()
{
i t j;
int j

for (j = 0; j < 5; j++) {

printf(“ %d \t ", j);

if( j == 2)

break;

}
}

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 98
Write a C Program for the following flowchart

Start

Sum = 0

Get temp

If temp == 0 T

Put Sum
F

Sum = Sum + temp


End

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 99
Write a C Program for the following flowchart
main()
{
int sum = 0;;

do {

scanf(“%d”, &temp);

if(temp ==0) break;

sum = sum + temp;

} while
hile (1)
(1);
printf(“%d”, sum);
}
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 100
WAP in C Language to add given N integer numbers. If any time sum >=100,
stop and display sum Start

Get N

I = 1,
1 sum =0

F
If (I < =N)

Get temp
I=I+1

sum = sum + temp

F T
If (sum >= 100) Put sum

End
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 101
WAP in C Language to add given N integer numbers. If any time sum >=100,
stop and display sum

#include<stdio.h>
void main(){
unsigned int n, i;
int sum=0, temp;
scanf("%u",&n);
f("% " & )
for (i=1;i<=n; i++){
scanf("%d"
scanf( %d ,&temp);
&temp);
sum = sum + temp;
if(sum
( >= 100)) break;;
}
printf("The sum is = %d", sum);
}
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 102
‘continue’ Statement
• ‘continue’ statement forces
f the next iteration off the loop
to take place and skips the code between continue
statement and the end of the loop

• In case of for loop, continue makes the execution of the


modification of loop index (expr3) of the statement and
then evaluates the conditional part.
p

• In case of while and do-while loops, continue makes the


conditional statement to be executed.
executed

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 103
What is the output of the following code snippet?

main() {

int i;

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

printf(“%d”, i );

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 104
What is the output of the following code snippet?
main() {

int i;

for( i = 0 ; i < 10; i++) {

if ( i == 4))

continue;

printf(“%d”, i );

} /* End of for loop*/

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 105
Write a C Program for the following flowchart
Start

Get n

sum = 0
i=1

If
F
i<=N
? Put sum
T
sum = sum + temp
i=i + 1 End

Get temp

If
T
temp % 2 != 0
?
ELTP-CAMPUS F
ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 106
Write a C Program for the following flowchart
main(){
int sum = 0, i=1;

scanf(“%d”,
( &n);
)

while(i <= n) {

i = i + 1;

scanf(“%d”, &temp);

if(t
if(temp %2 !=0)
! 0) continue;
ti

sum = sum + temp;

}
printf(“%d”, sum);
}
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 107
WAP in C Language to count even integer numbers in
given N numbers
g Start

Get N

I=1

count= 0

F
I<=N

T put count
Get temp

E d
End
F T
I=I+1 If temp %2
== 0
count = count + 1

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 108
WAP in C Language to count even integer numbers in
given N numbers
g
#include<stdio.h>

void main(){
(){

unsigned int n, i;

int temp
temp, count =0;
0;

scanf("%u", &n);

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

scanf("%d", &temp);

if( ttemp %2 !!= 0) continue;


ti

count++;}

printf ("Count is = %d",count);}


ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 109
Switch Statement
switch (expr) {
case value1: F
expr == value1
[ stmt1;; ]
break;
T F
case value2 : expr == value2

[ stmt2; ]
T
break;
stmt1;
t t1 stmt2; stmt3;
t t3
default :
[ stmt3; ]
break;
}

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 110
Write a C p
program
g to check given
g alphabet
p is vowel or
not vowel

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 111
Write a C program to check given alphabet is vowel or
not vowel main(){
char ch;
scanf(“%c”, &ch);
switch(ch)
( ){
case ‘a’ : printf(“Vowel”);
break;
case ‘e’
e : printf(
printf(“Vowel”);
Vowel );
break;
case ‘i’ : printf(“Vowel”);
break;
case ‘o’ : printf(“Vowel”);
break;
case ‘u’ : printf(“Vowel”);
break;
default : printf(“Not a vowel”);} // End of switch case
}//End of main function
ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 112
Write a program to check given alphabet is vowel or
not vowel main(){
char ch;
scanf(“%c”, &ch);
switch(ch) {
case ‘a’ :
case ‘e’
e :
case ‘i’ :
case ‘o’ :
case ‘u’
‘ ’ : printf(“Vowel”);
i tf(“V l”)
break;
default : printf(“Not a vowel”);
}
}

ELTP-CAMPUS ELTP-GROUP
EXCELLENT CAMPUS PLACEMENTS 113

You might also like