0% found this document useful (0 votes)
5 views

CNotes 1

Uploaded by

ARSHIYA ASH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

CNotes 1

Uploaded by

ARSHIYA ASH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 105

The following symbols are used to represent the Flow Charts

Ellipse : To represent start or stop

Parellagram : To represent input/output

Rectangle : To represent the processing or calculations

Rhambus : To represent the conditional statements

Small Circle : To use as a connector

Arrows : For directions


Write an algorithm to calculate the addition of 2 numbers.

start

step 1: read a

step 2: read b

step 3: c := a+b

step 4: print a

step 5: print b

step 6: print c

stop
Draw the flow chart to calculate the addition of 2 numbers.

start

Read a

Read b

C:= a+b

Print a

Print b

Print c

stop
write an algorithm to calculate the addition of 3 numbers.

start

step 1: read a

step 2: read b

step 3: read c

step 4: d := a+b+c

step 5: print a

step 6: print b

step 7: print c

step 8: print d

stop

rewrite the above the algorithm to represent more input and output(read or
print) statements in a single line.

start

step 1: read a,b,c

step 2: d := a+b+c

step 3: print a,b,c,d

stop
Draw the flow chart for addition of 3 numbers.

start

Read a,b,c

D:= a+b+c

Print a,b,c,d

stop
Algorithm 3.

write an algorithm to calculate the total marks and average marks of 3


subjects(maths,physics and chemistry)

start

step 1: read maths,physics,chemistry

step 2: total := maths+physics+chemistry

step 3: avg := total/3

step 4: print maths,physics,chemistry,total,avg

stop
Draw the flow chart for the above algorithm

start

Read maths,
physics, chemistry

Total := maths + physics +


chemistry

Avg := total/3

Print maths, physics,


chemistry, total, avg

stop
Algorithm 4.

write an algorithm to calculate the area of a circle.

start

step 1: read radius

step 2: area_circle := 3.14 * radius * radius

step 3: print radius,area_circle

stop

Draw the flow chart for the above algorithm


start

Read radius

Area_circle := 3.14 *
radius * radius

Print radius,
araa_circle

stop
Algorithm 7.

write an algorithm to find the biggest of two numbers.

start

step 1: read num1,num2

step 2: if num1 > num2 then

print "num1 is big"

else

print "num2 is big"

stop

Draw the flow chart for above algorithm


start

Read num1,num2

false
If num1
> num2 Print “num2 is big”

true

Print “num1 is big”

stop
Algorithm 8.

write an algorithm to find the biggest of three numbers.

start

step 1: read num1,num2,num3

step 2: if num1 > num2 and num1 > num3 then

print "num1 is big"

else if num2 > num1 and num2 > num3 then

print "num2 is big"

else

print "num3 is big"

stop

Draw the flow chart for the above algorithm


start

Read num1,num2,num3

If num1>num2 and
num1>num3

true
flase

Print “num1 is big”


If num2>num1 and
num2>num3

flase
true

Print “num2 is big” Print “num3 is big”

stop
Introduction to C Programming Language

C Programming Language is Procedural Programming Language

It is developed by Dennis Ritchie in the year 1972

It is developed as system programming language to write operating systems


and compilers.

Features of C Programming Language:

Low level access to memory

rich set of keywords

Alphabets, Digits and Symbols

keywords

statements

programs

Alphabets :

a-z, A-Z
Digits :

0-9

Symbols :

~ tilde

! Exclamatory

@ at the rate

# Hash(preprocessor)

$ Dollar

% Percentage

^ carret

& ampersand

* star

( parenthesis open

) parenthesis close

- highfun/minus

_ underscore

+ plus

= equal

: colon
; semi colon

" Double Quotes

' Single Quote

< less than

> greater than

, comma

. dot

? question mark

/ slash or division

\ backward slash

| vertical bar

{ brace or curley brace open

} brace or curley brace close

[ bracket open

] bracket close

Keywords :

Keywords are the reserved words in the programming language.

Each keyword in c language is having its own specific purpose and meaning.

These keywords are not used for any other purpose.

All the keywords are written in lower case alphabets.


The following are the keywords of C language

auto

break

case

char

const or constant

continue

default

do

double

else

enum

extern

float

for

goto
if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while
Structure of C Programming Language

Link/Header File Include Section

Definition Section

Global Variable Decleration Section

main()
{
Decleration Section
Execution Section
}

user defined functions()


{
statements
.........
.........
}

Link/Header File Include Section:

In this section we can include the header libraries or we can link the other
programs with the current programs

We can include the header library using the preprocessor directive #include
in the program
Here # symbol is known as a preprocessor and #include is a preprocessor
directive

Example :

#include<stdio.h>

here stdio.h is a standard input/output header library.

here .h indicates and header library/file.

Definition Section:

In this section we define the macro's(constants) or user defined function


prototypes.

Global Variable Decleration Section:

Here we declare the global variables required in the program.

main function:

> main function is compulsory in all the c programs.

> The program execution always begins from the main function only.
(or)

> The starting point of C program execution is from main only.

We can write the main function as follows.

main()

: main followed by open parenthesis and closed parenthesis then


immediately continued with open brace and closed brace.

We cannot write anything between the closed parenthesis and the open
brace of main function.

In between the open brace and closed brace of main function we write the
decleration section and execution section.

Decleration Section:
In the decleration section we can declare the variables required in the
program.

The first section of main function must be the declreration section.

Execution Section:

All the executable statements can be written under the execution section.

The executable statements like input, output and calculation statements.

The main function returns an integer value always, Hence we must write a
return statement at the end of main function.

We can write the return statement using the keyword return.

example:

return 0;

user defined functions:

We can write zero or n number of user defined functions in the C program.

Datatypes:

A datatype specifies the compiler that a type of value is stored in the


variable.
Datatypes:

1. Predefined Datatypes/Basic Datatypes

i. integer types

- short int

- int

- long int

ii. real types

- float

- double

- long double

iii. charecter types

- char

2. Derived Datatypes

i. arrays

ii. strings

iii. functions

iv. pointers

3. User Defined Datatypes

i. structures

ii. unions
iii. enumerations

Datatypes sizes and range:

Identifier:

An identifier is a name of variable,constant,pointer,array,string,


function,structure and union etc.,.

Rules for defining the identifiers:


1. we can use all the lower case alphabets from a to z,digits from 0 to 9 and
only one symbol underscore _ in defining the identifier name.

2. we can start with either any alphabet from lower case a to z or _ symbol.

3. we cannot start with any digit.

4. we cannot give any white spaces(space,tab or newline charecter) in the


identifier name.

5. The length of an identifier will be from one charecter to 36 charecters.

Ex:

student_name

gross_salary

_subject

result_1

Variable:

A variable is a named memory location to store the values.

We can declare the variables using the datatype as follows.

syntax:

datatype variablename;
ex:

int num1;

int num2;

int num3;

(or)

int num1,num2,num3;

num1=10;

num2=20;

num3=num1+num2;

Input/Output functions:

In C language the input/output functions are available in the stdio.h


(standard input/output header library).

The input/output functions are classified into 2 categories.

1. Formatted Input/Output Functions

2. Unformatted Input/Output Functions


1. Formatted Input/Output Functions:

In Formatted Input/Output functions we should specify the format specifier


to make the compiler to understad the type of values used to read/write.

The following are the Formatted input/output functions

1. printf()

2. scanf()

3. fprintf()

4. fscanf()

1. printf():

This function used to display the output on the console.

The following the is the syntax to write the printf() function.

syntax:

printf("Formatstring",list of variables);

Format string is divided into 2 parts they are


i. Text or Message : Some message or text to be displayed on console. If no
text to be displayed then we cannot write any text.

ii. Format specifiers : Format specifiers of corresponding datatype will be


written.

List of Variables: The variables list to be displayed on the console. When


there is more than one variable to be displayed, each variable should be
separted by comma (,) operator.

ex:1

int a; => %d

float b; => %f

char c; => %c

printf("the values are %d%f%c",a,b,c);

printf("the values are %d%f%c",b,c,a); <= Its incorrect [Mismatch of


datatypes]

printf("the values are %d%f%c",a,b); <= Its incorrect [Mismatch of


Format specifiers and variables number]
Note:

> When we give different types of variables we must follow the order of
format specifiers with the order of variables list.

> The number of variables must be matched with the number of format
specifiers.

ex:2

int a,b;

printf("%d%d",a,b);

2. scanf():

This function will read the input from the standard input device(key board)
to the variables.

syntax:

scanf("Format Specifiers",List of variables);

Ex:1
int a,b;

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

Here the variables must preceed with address(&) operator.

All the rules of printf() are applicable here.

Ex:2

int a;

float b;

char c;

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

3. fprintf():

This function will writes the data to the file.

syntax:
fprintf(filepointer,"Format String",List of variables);

Ex:

fprintf(stdout,"%d",a);

Here stdout is standard output device

You can also specify any other file pointer

4. fscanf():

This function will read the data from a file.

syntax:

fscanf(filepointer,"Format Specifiers",List of variables);

Ex:

fscanf(stdin,"%d",&a);

Here stdin is a standard input device(keyboard)

You can also specify any other file pointer.

2. Unformatted Input/Output Functions:


These functions does not required to specify the format specifier.

The following are the unformatted input/output functions.

1. getchar()

2. putchar()

3. getc()/fgetc()

4. putc()/fputc()

5. gets()

6. puts()

1. getchar():

This function will read a single charecter from the keyboard.

ex:

char ch;

ch=getchar();

2. putchar():

This function will display a single charecter on the console.

ex:
putchar(ch);

3. getc():

This function will read a single charecter from the file.

ex:

char ch;

ch=getc(fp);

here fp is a file pointer from which we need to read a single charecter.

4. putc():

This function will write a single charecter to the file.

ex:

putc(ch,fp);

here fp is file pointer to which we need to write a single charecter.

5. gets():

This function will read a string.

A string is a collection of charecters.


ex:

gets(str);

here str is a string variable.

6. puts()

This function will display the string on the console.

ex:

puts(str);

here str is a string variable.

Comment lines:

Comment lines are ignored by the compiler.

These are for the information purpose to the programmer

The comment lines can be written as a single line or multiple lines as per the
need.

We can write the comment line in C Program between /* and */ symbol

Ex:

/* its a declerative statement */


Note:

1. All the statements in C language should be written in lower case


alphabets only. C language is a case sensitive language.
2. All the statements must be terminated with semi colon.

write a program to display a welcome message

first.c

#include<stdio.h>

main()

printf("Welcome");

return 0;

output:

Welcome

To erase the previous output on the console we can use clrscr() function in
the program.

#include<stdio.h>
main()

clrscr()

printf("Welcome");

return 0;

output:

Welcome

Operators in C language:

1. Assignment Operator =

This operator will evaluate the value/expression written at the right side and
assigns to the variable at left side.

ex:

a=10;

a=10+20;

2. Arithmatic Operators:

These operators will perform the arithmatic operations.


There are 2 types arithmatic operators.

i. Binary Arithmatic Operators

ii. Unary Arithmatic Operators

i. Binary Arithmatic Operators:

In this operation there will atleast 2 operands with the operator to perform
the operation.

The following are the binary arithmatic operators

1. Addition + Ex. 10+20 => 30

2. Subtraction - Ex. 10-4 => 6

3. Multiplication * Ex. 10*5 => 50

4. Division / Ex. 10/2 => 5

5. Modulus(Mod) % Ex. 10%3 => 1

Write a program to demonstrate binary arithmatic operators.

#include<stdio.h>

main()

int a,b,c;

clrscr();

printf("Enter a value : ");


scanf("%d",&a);

printf("Enter b value : ");

scanf("%d",&b);

c=a+b;

printf("a value is %d\n",a);

printf("b value is %d\n",b);

printf("Addition is %d\n",c);

return 0;

output:

Enter a value : 10

Enter b value : 20

a value is 10

b value is 20

Addition is 30
ii. Unary Arithmatic Operators:

This operator will perform the operation on a single operand.

The following are the unary arithmatic operators.

1. Unary Minus -

2. Increment/Decrement Operators ++/--

Unary Minus Operator:

It converts a positive value to negative and vice versa.

Ex:

int a,b;

a=10;

-a;

(or)

b=-a;

Write a program to demonstrate the unary minus operator


Ex:

deducting one to the variable:

int a=10;

printf("a is %d",a); => 10

a=10-1;

printf("a is %d",a); => 9

(or)

a=a-1;

printf("a is %d",a); => 9

adding one to the variable:

int a=10;

printf("a is %d",a); => 10

a=10+1;

printf("a is %d",a); => 11

(or)

a=a+1;
printf("a is %d",a); => 11

note : When the left hand side variable and the first variable in the right
hand side is same we can write short hand notation.

short hand notation is

a+=1; => a=a+1;

a-=1; => a=a-1;

2. Increment/Decrement Operators(++/--):

The Increment/Decrement Operator will increase/decrease the value of a


variable by one.

These operators are written in two ways:

1. Pre Increment/Decrement Operator

2. Post Increment/Decrement Operator

1. Pre Increment/Decrement Operator:

> Here we will write the operator first and the operand next
syntax:

operator operand;

++a;

--a;

>In this first the value of a variable is increased/decreased by one and the
expression is evaluated second.

int a;

a=10;

printf("a is %d",a); => 10

printf("a is %d",++a); => 11

printf("a is %d",--a); => 9

Write a program to demonstrate the pre increment operator.

preinc.c

#include<stdio.h>

main()

int a;
clrscr();

a=10;

printf("a is %d\n",a);

printf("a is %d\n",++a);

return 0;

output:

a is 10

a is 11

HW1:

Write a program to demonstrate the pre decrement operator.

2. Post Increment/Decrement Operator:

> Here we will write the operand first and the operator next.

syntax:

operand operator

a++
a--

>In this first the expression is evaluated and value of a variable is


increased/decreased by one second.

int a;

a=10;

printf("a is %d",a); => 10

printf("a is %d",a++); => 10

printf("a is %d",a); => 11

Write a program to demonstrate the post increment operator.

postinc.c

#include<stdio.h>

main()

int a;

a=10;

clrscr();
printf("a is %d\n",a);

printf("a is %d\n",a++);

printf("a is %d\n",a);

return 0;

output:

a is 10

a is 10

a is 11

HW2:

Write a program to demonstrate the post decrement operator.


3. Relational Operators:

These operators will verifies the relationship between two operands.

If the relationship is true it gives the result 1 and 0 otherwise.

The following are the relational operators in c language.

1. Greater than >

2. Greater than or equal >=

3. Less than <

4. Less than or equal <=

5. Equal ==

6. Not Equal !=

Ex :

10 > 20 0

10 > 5 1

5 < 100 1

56 < 25 0
47 <= 50 1

47 <= 47 1

47 <= 23 0

67 >= 67 1

45 >= 34 1

45 >= 56 0

90 == 90 1

90 == 121 0

100 != 100 0

123 != 121 1

write a program to demonstrate the relational operators

rel.c

#include<stdio.h>

main()

printf("10 > 20 %d\n",10>20);

printf("10 > 5 %d\n",10>5);


printf("5 < 100 %d\n",5<100);

printf("5 < 3 %d\n",5<3);

printf("6 >= 6 %d\n",6>=6);

printf("8 >= 20 %d\n",8>=20);

printf("5 <= 100 %d\n",5<=100);

printf("56 <= 20 %d\n",56<=20);

printf("100 == 100 %d\n",100==100);

printf("100 == 90 %d\n",100==90);

printf("100 != 90 %d\n",100!=90);

printf("90 != 90 %d\n",90!=90);

return 0;

Output:

10 > 20 0
10 > 5 1
5 < 100 1
5<30
6 >= 6 1
8 >= 20 0
5 <= 100 1
56 <= 20 0
100 == 100 1
100 == 90 0
100 != 90 1
90 != 90 0
4. Logical Operators:

Logical Operators will checks the logical relationship of the two expressions.

If the logical relationship is true then the result is 1 and 0 otherwise.

The following are the logical operators in C language.

1. Logical And &&

2. Logical Or ||

3. Logical Not !

Truth Table of Logical And

X Y X&&Y

----------------------

1 1 1

1 0 0

0 1 0

0 0 0

Truth Table of Logical Or


X Y X||Y

----------------------

1 1 1

1 0 1

0 1 1

0 0 0

Truth Table of Logical Not

X !X

-----------

1 0

0 1

(10 > 20) && (10 < 25) => 0

(10 > 3) && (100 < 125) => 1

(4 > 3) || (5 < 3) => 1

(4 > 100) || (5 < 3) => 0


!(10>5) => 0

!(5 < 3) => 1

Write a program to demonstrate Logical Operators

Logical.c

#include<stdio.h>

main()

{ clrscr();

printf("(10 > 20) && (10 < 25) %d\n",(10>20) && (10<25));

printf("(10 > 3) && (100 < 125) %d\n",(10>3) && (100<125));

printf("(4 > 3) || (5 < 3) %d\n",(4>3) || (5<3));

printf("(4 > 100) || (5 < 3) %d\n",(4>100) || (5<3));

printf("!(10 > 5) %d\n",!(10>5));

printf("!(5 < 3) %d\n",!(5<3));

return 0;

Output:

(10 > 20) && (10 < 25) 0


(10 > 3) && (100 < 125) 1
(4 > 3) || (5 < 3) 1
(4 > 100) || (5 < 3) 0
!(10 > 5) 0
!(5 < 3) 1
5. Bitwise Operators:

These operators will works on the bit system(binary bits) of a number.

The following are the bitwise operators in C language.

1. Bitwise And &

2. Bitwise Or |

3. Bitwise Xor(Exclusive Or) ^

4. Bitwise Left Shift <<

5. Bitwise Right Shift >>

Truth Table of Bitwise And

X Y X&Y

----------------------

1 1 1

1 0 0

0 1 0

0 0 0
Truth Table of Bitwise Or

X Y X|Y

----------------------

1 1 1

1 0 1

0 1 1

0 0 0

Truth Table of Bitwise XOr

X Y X^Y

----------------------

1 1 0

1 0 1

0 1 1

0 0 0

Bitwise Left Shift(<<):


This operator will moves the specified number of bits to left side.

Ex: a<<3

It is moving the bits of a 3 positions to left side

Bitwise Right Shift(>>):

This operator will moves the specified number of bits to right side.

Ex: a>>2

It is moving the bits of a 2 positions to right side

Example:
a=34
b=49
a 1 0 0 0 1 0
b 1 1 0 0 0 1
a&b 1 0 0 0 0 0 32 a&b=32
32 0 0 0 0 0

a 1 0 0 0 1 0
b 1 1 0 0 0 1
a|b 1 1 0 0 1 1 51 a|b=51
32 16 0 0 2 1

a 1 0 0 0 1 0
b 1 1 0 0 0 1
a^b 0 1 0 0 1 1 19 a^b =19
0 16 0 0 2 1
Bitwise
Left Shift
Operator

a<<3 a 1 0 0 0 1 0

1 0 0 0 1 0 0 0 0
256 0 0 0 16 0 0 0 0 272

Bitwise
Right
Shift
Operator

a>>2 a 1 0 0 0 1 0

0 0 1 0 0 0
0 0 8 0 0 0 8

Write a program to demonstrate bitwise operators

Bitwise.c

#include<stdio.h>

main()

int a,b;

clrscr();

a=34;

b=49;

printf("a & b %d\n",a&b);

printf("a | b %d\n",a|b);
printf("a ^ b %d\n",a^b);

printf("a << 3 %d\n",a<<3);

printf("a >> 2 %d\n",a>>2);

return 0;

Output:

a&b 32
a|b 51
a^b 19
a << 3 272
a >> 2 8

Example:

int a,b,c,d;

a=10;

b=5;

c=20;

d= a+b*c; 10+5*20 = 110 correct

d=? 10+5*20 = 300


110

300

Precedence and Associativity of Operators:

Precedence Operators Operation Associativity

() Parentheses (function call)


[] Brackets (array subscript)
1 . Member selection via object name
-> Member selection via pointer
++ — Postfix increment/decrement left-to-right

Prefix increment/decrement
Unary plus/minus
++ — Logical negation/bitwise complement
+– Cast (convert value to temporary value
2 !~ of type)
(type) Dereference
* Address (of operand)
& Determine size in bytes on this
sizeof implementation right-to-left

3 * / % Multiplication/division/modulus left-to-right

4 + – Addition/subtraction left-to-right

5 << >> Bitwise shift left, Bitwise shift right left-to-right

Relational less than/less than or equal to


6 < <= Relational greater than/greater than or
> >= equal to left-to-right

7 == != Relational is equal to/is not equal to left-to-right

8 & Bitwise AND left-to-right


9 ^ Bitwise exclusive OR left-to-right

10 | Bitwise inclusive OR left-to-right

11 && Logical AND left-to-right

12 || Logical OR left-to-right

13 ?: Ternary conditional right-to-left

= Assignment
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
14
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment right-to-left

15 , Comma (separate expressions) left-to-right

6. Conditional Operator(Ternary Operator) (?:):

This operator will takes an expression/condition before the question mark if


condition is true it executes the expression written after question mark and
executes the expression written after colon symbol if the condition is false.

syntax:

condition ? expression1 : expression2 ;

a>b ? a-b : b-a;


Write a program to demonstrate the conditional operator

Condition.c

#include<stdio.h>

main()

int a,b,c;

clrscr();

printf("Enter a,b values\n");

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

c=a>b?a-b:b-a;

printf("C value is %d\n",c);

return 0;

Output:

Type Conversion:

Converting one datatype value to other datatype value is known as type


conversion
1. Implicit Type Conversion

2. Explicit Type Conversion

1. Implicit Type Conversion:

Implicit conversion is automatically done by the compiler.

Ex:

int a;

float b;

a=10;

b=a;

2. Explicit Type Conversion:

In this conversion the programmer needs to specify the type conversion


explicitly.

syntax:

variable=(desitination datatype)variable/value;

int a;
float b;

a=10;

b=(float)a;

char => 1 byte

short => 2 bytes

int => 2 bytes

long int => 4 bytes

float => 4 bytes

double => 8 bytes

long double => 10 bytes

Note: When we are converting the lower datatypes to upper datatypes


there is no problem of loosing data, but more memory may utilised more

When we are converting the upper datatypes to lower datatypes there


chance of loosing the data.

Write a program to demonstrate the type conversion

Type_con.c
#include<stdio.h>

main()

int a;

float b;

clrscr();

printf("Enter b value");

scanf("%f",&b);

printf("b is %.2f\n",b);

a=(int)b;

printf("a is %d\n",a);

return 0;

Output:
Conditional Branching and Loops:
--------------------------------
1. Conditional Statements
2. Looping Statements

1. Conditional Statements
-------------------------
These statements will checks the condition and executes the selected
statements based on the truthfullness of the condition.

The following are the condtional statements in c language


i. if
ii. if-else
iii. nested if
iv. switch

i. if :
if statement will check the condition and executes the statements written
after it if the condition is true only.

syntax:
if <condition>
statement
(or)
if <condition>
{
statments
........
........
}

Write a program to demonstrate if statement to check a person is eligible to


vote or not

c1.c
#include<stdio.h>
main()
{
int age;
clrscr();
printf("Enter age value\n");
scanf("%d",&age);
if(age>=18)
{
printf("The person is eligible to vote");
}
return 0;
}

output:

ii. if-else:
if else statement will check the condition and executes the statements
written after if when the condition is true and executes the statements
written after else when the condition is false.

syntax:

if <condition>
{
statements
........
........
}
else
{
statements
.........
........
}

write a program to check whether a person is eligible to vote or not using if-
else statement

c2.c

#include<stdio.h>
main()
{
int age;
clrscr();
printf("enter age value\n");
scanf("%d",&age);
if(age>=18)
{
printf("Eligible to vote\n");
}
else
{
printf("Not eligible to vote\n");
}
return 0;
}
output:
write a program to check biggest of 2 numbers using if-else statement.

c3.c

#include<stdio.h>
main()
{
int a,b;
clrscr();
printf("Enter a and b values\n");
scanf("%d%d",&a,&b);
if(a>b)
{
printf("a is big\n");
printf("a value is %d\n",a);
}
else
{
printf("b is big\n");
printf("b value is %d\n",b);
}
return 0;
}
Output:

write a program to check the biggest of 3 numbers using if-else statement.


(a,b,c)

syntax for more than one condition is there


if <condition>
{
statements
.........
.........
}
else if <condition>
{
statements
.........
.........
}
else
{
statements
..........
..........
}

Note: The above structure is called else if ladder

c4.c

#include<stdio.h>
main()
{
int a,b,c;
printf("Enter a,b,c values\n");
scanf("%d%d%d",&a,&b,&c);
if((a>b) && (a>c))
{
printf("a is big");
}
else if((b>a) && (b>c))
{
printf("b is big");
}
else
{
printf("c is big");
}
return 0;
}
output:

write a program to display the grade of a student result by taking 3


subjects(maths,physics,chemistry) marks.
avg. range grade
---------- -----
>=90 O
>=80 and <90 A+
>=70 and <80 A
>=60 and <70 B+
>=50 and <60 B
>=40 and <50 C
<40 Failed

c5.c

#include<stdio.h>
main()
{
int maths,physics,chemistry;
int total;
float avg;
clrscr();
printf("Enter maths,physics and chemistry marks\n");
scanf("%d%d%d",&maths,&physics,&chemistry);
total=maths+physics+chemistry;
avg=total/3.0;
if(avg>=90)
{
printf("Grade is O");
}
else if((avg>=80) && (avg<90))
{
printf("Grade is A+");
}
else if((avg>=70) && (avg<80))
{
printf("Grade is A");
}
else if((avg>=60) && (avg<70))
{
printf("Grade is B+");
}
else if((avg>=50) && (avg<60))
{
printf("Grade is B");
}
else if((avg>=40) && (avg<50))
{
printf("Grade is C");
}
else
{
printf("Failed");
}
return 0;
}

output:

iii. nested if:


writing one if statement inside the other if statement is known as nested if
statements

syntax:
if <condition>
{
if <condition>
{
statements
..........
}
else
{
statements
..........
}
}
else
{
if <condition>
{
statements
..........
}
else
{
statements
..........
}
}

write a program to demonstrate the nested if statement to check whether a


person is eligible for marriage or not.

gender and age


Male >=21
Female >=18

c6.6

#include<stdio.h>
main()
{
int age;
char gender;
clrscr();
printf("enter the gender m-male and f-female\n");
scanf("%c",&gender);
printf("enter the age \n");
scanf("%d",&age);
if(gender=='m')
{
if(age>=21)
{
printf("The person is eligible for marriage\n");
}
else
{
printf("The person is not eligible for marriage\n");
}
}
else
{
if(age>=18)
{
printf("The person is eligible for marriage\n");
}
else
{
printf("The person is not eligible for marriage\n");
}
}
return 0;
}
output:

iv. switch:
it is a multiway conditional statement. It takes an expression and compares
with the cases written with in switch block. If any case is matched with the
expression then it executes the corresponding matched case statements, if
no case is matched with the expression then it executes default case
statements.

syntax:
switch(expression)
{
case constant1:
statements
..........
case constant2:
statements
..........
case constant3:
statements
..........
.
.
.
.
case constantn:
statements
..........
default:
statements
..........
}

write a program to demonstrate the switch statement to display given


number in words

#include<stdio.h>
main()
{
int num;
clrscr();
printf("Enter number between 1 and 5\n");
scanf("%d",&num);
switch(num)
{
case 1:
printf("One\n");
case 2:
printf("Two\n");
case 3:
printf("Three\n");
case 4:
printf("Four\n");
case 5:
printf("Five\n");
default:
printf("The number not between 1 and 5\n");
}
return 0;
}
output:

Note:
In switch statement if any case is matched with the given expression then
the cases after the matched case will be executed. To eliminate this problem
we should use the break in each case in the switch statement.

Rewrite the above program to get the proper output using break

#include<stdio.h>
main()
{
int num;
clrscr();
printf("Enter number between 1 and 5\n");
scanf("%d",&num);
switch(num)
{
case 1:
printf("One\n");
break;
case 2:
printf("Two\n");
break;
case 3:
printf("Three\n");
break;
case 4:
printf("Four\n");
break;
case 5:
printf("Five\n");
break;
default:
printf("The number not between 1 and 5\n");
}
return 0;
}
output:

Write a program to take an alphabet and display whether it is vowel or


consonant using switch statement
c8.c

#include<stdio.h>
main()
{
char alpha;
clrscr();
printf("Enter an alphabet\n");
scanf("%c",&alpha);
switch(alpha)
{
case 'a':
case 'A':printf("Vowel");
break;
case 'e':
case 'E':printf("Vowel");
break;
case 'i':
case 'I':printf("Vowel");
break;
case 'o':
case 'O':printf("Vowel");
break;
case 'u':
case 'U':printf("Vowel");
break;
default:
printf("Consonant");
}
return 0;
}
output:

c9.c
#include<stdio.h>
main()
{
char alpha;
clrscr();
printf("Enter an alphabet\n");
scanf("%c",&alpha);
switch(alpha)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':printf("Vowel");
break;
default:
printf("Consonant");
}
return 0;
}
output:

write a program to display the grade of a student result by taking 3


subjects(maths,physics,chemistry) marks by using switch statement.
avg. range grade
---------- -----
>=90 O
>=80 and <90 A+
>=70 and <80 A
>=60 and <70 B+
>=50 and <60 B
>=40 and <50 C
<40 Failed

c10.c

#include<stdio.h>
main()
{
int maths,physics,chemistry;
int total;
float avg;
int grade;
clrscr();
printf("Enter maths,physics and chemistry marks\n");
scanf("%d%d%d",&maths,&physics,&chemistry);
total=maths+physics+chemistry;
avg=total/3.0;
grade=avg/10;
switch(grade)
{
case 9:printf("Grade O");
break;
case 8:printf("Grade A+");
break;
case 7:printf("Grade A");
break;
case 6:printf("Grade B+");
break;
case 5:printf("Grade B");
break;
case 4:printf("Grade C");
break;
default:
printf("Failed");
}
return 0;
}

output:

2. Looping Statements(Repetative Statements/Iterative Statements):

These statements will executes the programming statements repetatively


for the specified number of times.

The following are the looping statements in C language


1. while loop
2. do while loop
3. for loop

1. while loop:
While loop is a pre condition checking(pre-test) looping statement, which
checks the condition first, if the condition is true it enters into looping block
to execute the statements repetatively until the condition becomes false.

syntax:
while <condition>
{
statements
statements
..........
..........
}
Note:
1. We cannot terminate the while condition with semi colon in while loop.
2. While loop is also known as entry control looping statement.

Write a program to display your name for 5 times by using while loop

loop1.c

#include<stdio.h>
main()
{
int i;
clrscr();
i=1;
while(i<=5)
{
printf("Prashanth\n");
i++;
}
return 0;
}
output:

Write a program to display the numbers from 1 to 5 using while loop

loop2.c

#include<stdio.h>
main()
{
int i;
clrscr();
i=1;
while(i<=5)
{
printf("%d\n",i);
i++;
}
return 0;
}
output:

Write a program to display the odd numbers from 1 to 20 by using while


loop.

loop3.c

#include<stdio.h>
main()
{
int i;
clrscr();
i=1;
while(i<=20)
{
if(i%2==1)
{
printf("%d\n",i);
}
i++;
}
return 0;
}

output:

HW1
Write a program to display the even numbers from 1 to 20 by using while
loop.

Write a program to display the sum of individual digits of a given number by


using while loop.

loop4.c

#include<stdio.h>
main()
{
int n,sum,digit;
clrscr();
printf("Enter n value\n");
scanf("%d",&n);
sum=0;
while(n!=0)
{
digit=n%10;
sum=sum+digit;
n=n/10;
}
printf("Sum is %d\n",sum);
return 0;
}
output:

HW2
Write a program to display the reverse of a given number using while loop.
123 => 321

loop5.c

#include<stdio.h>
main()
{
int n,rev,digit;
rev=0;
clrscr();
printf("Enter a number\n");
scanf("%d",&n);
while(n!=0)
{ digit=n%10;
rev=(rev*10)+digit;
n=n/10;
}
printf("The Reverse Number is %d\n",rev);
return 0;
}
output:

Write a program to check whether the given number is polindrome or not.


1221 <=> 1221

loop6.c

#include<stdio.h>
main()
{
int n,rev,digit,n1;
rev=0;
clrscr();
printf("Enter a number\n");
scanf("%d",&n);
n1=n;
while(n!=0)
{ digit=n%10;
rev=(rev*10)+digit;
n=n/10;
}
if(n1==rev)
{
printf("The Number is Polindrome %d\n",rev);
}
else
{
printf("The Number is not Polindrome\n");
}
return 0;
}
output:

Write a program to check whether the given number is prime number or


not.

loop7.c

#include<stdio.h>
main()
{
int n,i,count=0;
clrscr();
printf("Enter n value\n");
scanf("%d",&n);
i=2;
while(i<=n)
{
if(n%i==0)
{ count++;
}
i++;
}
if(count==1)
{
printf("The number is prime number %d\n",n);
}
else
{
printf("The number is not prime number %d\n",n);
}
return 0;
}

output:

Write a program to display the multiplication table for a given number

Ex:
5
5x1=5
5 x 2 = 10
5 x 3 = 15
....
....
5 x 10 = 50

loop8.c

#include<stdio.h>
main()
{
int n,i;
clrscr();
printf("Enter n value\n");
scanf("%d",&n);
i=1;
while(i<=10)
{
printf("%d x %d = %d\n",n,i,n*i);
i++;
}
return 0;
}

output:

HW1.
Write a program to check whether a given number is arm strong number or
not.

2. do while loop:
do while loop is a post condition checking(post-test) looping statement. It
enters into the loop block without checking a condition and executes the
statements of loop block once and at the exit it checks the condition, if the
condition is true it repeats loop execution, if false execution will be stopped.

syntax:

do
{
statements
..........
..........
}while<condition>;

Note:
1. We should terminate the while condition with semi colon in the do while
loop.
2. Even the condition may be false the statements of loop will be executed
atleast once.
3. do while loop is also known as exit control looping statement.

Write a program to display your name for 5 times using do while loop.

loop9.c

#include<stdio.h>
main()
{
int i;
clrscr();
i=1;
do
{
printf("Prashanth\n");
i++;
}while(i<=5);
return 0;
}
output:

Write a program to display the numbers from 1 to 20 using do while loop.

loop10.c

#include<stdio.h>
main()
{
int i;
clrscr();
i=1;
do
{
printf("%d\n",i);
i++;
}while(i<=20);
return 0;
}
output:

Write a program to calculate the sum of individual digits of a given number


using do while loop.

loop11.c

#include<stdio.h>
main()
{
int n,digit,sum;
sum=0;
clrscr();
printf("Enter n value\n");
scanf("%d",&n);
do
{ digit=n%10;
sum=sum+digit;
n=n/10;
}while(n!=0);
printf("Sum of individual digits is %d\n",sum);
return 0;
}
output:

HW:
Write all the remaining programs discussed in while loop using do while
loop.

Differences between while loop and do while loop

S.No. While Loop S.No. Do while loop


1 Pre Test Looping statement 1 Post Test Looping statement
2 Checks condition and enters into the 2 Enters into loop block first and executes
loop block if the condition is true block then checks condition at the end
3 If condition false it wont executes 3 If condition is false still it executes loop block
loop block even once atleast once
4 Condition written at beginning 4 Condition written at end

5 Entry control loop 5 Exit control loop


3. for loop:

for loop is a compact looping statement in which we write initialization,


condition and updation/increment/decrement together at the begining of
the loop. It checks the condition first and enters into the loop it the
condition is true.

syntax;
for(initialization; condition; updation)
{
statements
..........
..........
}

write a program to display your name for 5 times using for loop

loop12.c

#include<stdio.h>
main()
{
int i;
clrscr();
for(i=1;i<=5;i++)
{
printf("Prashanth\n");
}
return 0;
}
output:
Write a program to check whether a given number is prime or not using for
loop.

loop13.c

#include<stdio.h>
main()
{
int n,i,count=0;
printf("Enter n value\n");
scanf("%d",&n);
for(i=2;i<=n;i++)
{
if(n%i==0)
{ count++;
}
}
if(count==1)
{
printf("the number is prime\n");
}
else
{
printf("The number is not prime\n");
}
return 0;
}
output:

write a program to check whether a given number is polindrome or not


using for loop
loop14.c

#include<stdio.h>
main()
{
int n,n1,rev=0,digit;
clrscr();
printf("Enter n value\n");
scanf("%d",&n);
for(n1=n;n1!=0;n1=n1/10)
{
digit=n1%10;
rev=(rev*10)+digit;
}
if(n==rev)
{
printf("The number is polindrome\n");
}
else
{
printf("The number is not polindrome\n");
}
return 0;
}
output:

Nested Loops:
Writing one loop inside the other loop is known as nested loops
syntax:
Nested While loop:
while <condition>
{
...............
while<condition>
{
statements
..........
..........
}
...............
}

Nested do while loop:

do
{
.............
do
{
statements
..........
..........
}while<condition>;
.............
}while<condition>;

Nested for loop:

for(initialization;condition;updation)
{
..................
for(initialization;condition;updation)
{
statements
.........
.........
}
}

Write a program to demonstrate the nested loops to display the following


format

*
**
***
****
*****

loop15.c (Nested While loop)


#include<stdio.h>
/*nested while loop*/
main()
{
int i,j;
i=1;
while(i<=5)
{
j=1;
while(j<=i)
{
printf("*");
j++;
}
printf("\n");
i++;
}
return 0;
}
output:
loop16.c (Nested do while loop):
#include<stdio.h>
/*nested do while loop*/
main()
{
int i,j;
i=1;
do
{
j=1;
do
{
printf("*");
j++;
}while(j<=i);
printf("\n");
i++;
}while(i<=5);
return 0;
}
output:

loop17.c (Nested for loop):


#include<stdio.h>
/*nested for loop*/
main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
output:

Write a program to display the following format using nested loops

1
12
123
1234
12345

loop18.c

#include<stdio.h>
/*nested for loop*/
main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d ",j);
}
printf("\n");
}
return 0;
}

output:

Write a program to display the following format using nested loops

1
22
333
4444
55555

loop19.c

#include<stdio.h>
/*nested for loop*/
main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d ",i);
}
printf("\n");
}
return 0;
}
output:

HW:
1. Write a program to display the following format using nested loops
12345
1234
123
12
1

2. Write a program to display the following format using nested loops


55555
4444
333
22
1
Write a program to display the prime numbers between 2 and 100.
loop20.c

#include<stdio.h>
main()
{
int i,j,count;
for(i=2;i<=100;i++)
{ count=0;
for(j=2;j<=i;j++)
{
if(i%j==0)
{
count++;
}
}
if(count==1)
{
printf("%d\t",i);
}
}
return 0;
}
output:

Write a program to display the factorial of a given number.


5 factorial => 120
5*4*3*2*1

loop21.c
#include<stdio.h>
main()
{
long unsigned int n,i,fact;
fact=1;
clrscr();
printf("Enter n value\n");
scanf("%lu",&n);
for(i=1;i<=n;i++)
{
fact=fact*i;
}
printf("The factorial of %lu is %lu\n",n,fact);
return 0;
}
output:

loop control statements:


These statements will control the loop execution, they are
1. break
2. continue

1.break:
break statement will stops the execution of loop or block and comes out of
loop or block.

2. continue:
continue statement will stops executing the statements written after it
inside the loop or block and repeats from begining.

write a program to demonstrate the break.


loop22.c

#include<stdio.h>
main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i>5)
{
break;
}
printf("%d\n",i);
}
return 0;
}
output:

write a program to demonstrate the continue[print the numbers from 1 to


10 and skip multiple of 3].
loop23.c

#include<stdio.h>
main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i%3==0)
{
continue;
}
printf("%d\n",i);
}
return 0;
}
output:

goto:

goto statement will takes the execution control to the specified label and
executes the statements written under the label.

syntax:

goto labelname;

......
......
......
......
labelname:
statements
..........
..........
write a program to demonstrate the goto statement to display 1 to 10
numbers.

goto1.c

#include<stdio.h>
main()
{
int i;
clrscr();
i=1;

dis:
printf("%d\n",i);
i++;
if(i<=10)
goto dis;

return 0;
}
output:

write a program to display the biggest of 2 numbers using goto statement.

goto2.c

#include<stdio.h>
main()
{
int a,b;
clrscr();

printf("Enter a,b values\n");


scanf("%d%d",&a,&b);
if(a>b)
goto biga;
else
goto bigb;
biga:
printf("a is big");
goto end;
bigb:
printf("b is big");
end:

return 0;
}
output:

You might also like