Sie sind auf Seite 1von 140

INTRODUCTION TO C

Noornilo Nafees 1
Steps in learning C

Character
Tokens Instructions Programs
Set

Noornilo Nafees 2
C Character Set

C Character Set

Source Execution
Character Set Character Set

Alphabets Digits Special White Escape


Characters Spaces Sequence

Noornilo Nafees 3
C Character Set (Cont)
• Source Character Set
– It is used to construct the statements in the
program.
• Executable Character Set
– These characters are employed at the time of
execution i.e. they have effects only when the
program is being executed.

Noornilo Nafees 4
Source Character Set
Letters a to z ,A to Z
Digits 0 to 9
Special Characters !@#$%^&*()_-+
= \ | { } [ ] etc,.
White Spaces Blank Space ,Horizontal
tab, New line, Vertical
tab etc,.

Noornilo Nafees 5
Special characters
• Comma ,
• Period or dot .
• Semicolon ;
• Colon :
• Apostrophe ‘
• Quotation mark “
• Exclamation mark !
• Vertical bar |
• Back Slash \
• Tilde ~
• Underscore -
• Dollar $
• Question mark Noornilo Nafees? 6
• Ampersand &
• Caret ^
• Asterisk *
• Minus -
• Addition +
• Lesser than <
• Greater than >
• Parenthesis ()
• Bracket []
• Braces {}
• Percentage %
• Hash #
• Equal to =
• At the rate Noornilo Nafees
@ 7
Executable Character Set
Characters Escape Sequence
Back Space \b
Horizontal Space \t

Vertical Space \v

Newline \n

Noornilo Nafees 8
C Tokens
• The smallest element in the C language is
the token.
• It may be a single character or a sequence
of characters.

Noornilo Nafees 9
C Tokens (Cont)

C Tokens

Identifiers Keywords Constants Strings operators spI


symbol
Eg:main, Eg: int, Eg:17, Eg: “ab” Eg: + Eg: #
avg for 15.5 - $%

Noornilo Nafees 10
Executing a C Program

Creating the Program

Compilation

Linking

Execution
Noornilo Nafees 11
Executing a C Program (Cont)
• Enter the program in a C editor.
• Save the program (File  Save) or F2.
Use the extension .c for saving the file.
Eg: sample.c
• Compile the program(Compile  Compile)
or Alt+F9.
• Run the program(Run  Run) or Ctrl+F9.

Noornilo Nafees 12
Structure of C program
DOCUMENTATION SECTION
PREPROCESSOR SECTION
DEFINITION SECTION

GLOBAL DECLARATION SECTION

main()
{
Declaration part;
Executable Part;
}
sub program section
{
Body of the subprogram;
}
Noornilo Nafees 13
• Documentation Section
– It contains the comment lines.
• Preprocessor Section
– It is used to link library files.
• Global Declaration Section
– The Global declaration section comes at the
beginning of the program and they are visible
to all parts of the program.
• Declaration Section
– It describes the data to be used within the
function.
• Executable Part
– It contains the valid statements.
Noornilo Nafees 14
C Programs
 C program may have many functions.
 One and only one of the functions MUST BE
named main.
 main is the starting point for the program.
 main and other functions in a program are
divided into two sections, declaration
section and statement section.

Noornilo Nafees 15
Preprocessor Directives
• Special instructions to the preprocessor
that tells how to prepare the program for
compilation
• E.g: include : tells the processor to
include information from selected libraries
known as header files e.g. <stdio.h>

Noornilo Nafees 16
Comments (Program documentation)

 The compiler simply ignores comments


when it translates the program into
executable code.
 To identify a comments, C uses opening
/* and closing */ comment tokens.

Noornilo Nafees 17
Comments (Cont)
 Comments can appear anywhere in a
program.
 Comments are also found wherever it is
necessary to explain a point about a code.
 Comments cannot be nested in C i.e. you
cannot have comments inside comments.

Noornilo Nafees 18
C program
/* Example program in C*/ Comments
# include <stdio.h>Preprocessor Section
#include<conio.h>
Global Declaration

void main ()
{ Local declaration

printf (“Hello World! \n”); Statements


getch();
}
Output :
Hello World Noornilo Nafees 19
C Tokens
• Identifiers
• Keywords
• Constants
• Operators
• Special symbols

Noornilo Nafees 20
Identifiers
• Identifiers are names given to various
program elements such as variables,
functions and arrays etc,.
• Eg: #define N 10
#define a 15
Here N and a are user defined identifiers.

Noornilo Nafees 21
Rules for naming identifier
• First character must be alphabetic or
underscore.
• Must consist only of alphabetic characters,
digits, or underscores.
• Only the first 31 characters of an identifier are
significant and are recognized by the compiler.
• Cannot use a keywords or reserved word (e.g.
main, include, printf & scanf etc.).
• No space are allowed between the identifiers
etc,.
• C is case sensitive, e.g. My_name  my_name.
Noornilo Nafees 22
Examples of Valid and Invalid Names

Valid Names Invalid Names


a a1 $sum /* $ is illegal */

student_name stdntNm 2names /* Starts with 2 */

_aSystemName _anthrSysNm stdnt Nmbr /* no spaces */

TRUE FALSE int /* reserved word */

Noornilo Nafees 23
Variables
• Variable is an identifier that is used to
represent some specified type of
information.
• Eg: x=3
• Here x is variable.

Noornilo Nafees 24
Keywords
• It is a reserved words.
• Cannot be used for anything else.
• Examples:
– int
– while
– for etc,.

Noornilo Nafees 25
Keywords
Auto register Continue
Double typedef For
Int Char signed
Struct extern void
Break return Default
Else union Goto
Long Const sizeof
Switch Float do
Case short If
Enum unsigned
Static While
Noornilo Nafees 26
Constants
• It is an entity whose value does not
changes during the execution.
• Eg: x=3
• Here 3 is a constant.

Noornilo Nafees 27
Types
• Numeric constants
• Character constant

Noornilo Nafees 28
Constants

Constants

Numeric Constants Character Constants

Integer Real Single String


Constant Constant Character Constant
Constant

Noornilo Nafees 29
Numeric constants
Integer constants
• It is formed using a sequence of digits.
Decimal - 0 to 9 .
Octal - 0 to 7.
Hexa - 0 to 9 ,A to F

Eg: 10,75 etc.

Noornilo Nafees 30
Rules for defining Integer Constant
• It must have atleast one digit.
• Decimal point are not allowed.
• No blank space or commas are allowed.
• It can be either positive or negative. Etc,.

Noornilo Nafees 31
Numeric constants
Real constants
• It is formed using a sequence of digits but
it contain decimal point.
• length, height, price distance measured in
real number
Eg: 2.5, 5.11, etc.

Noornilo Nafees 32
Character constants
Single character constant
– A character constant is a single character
they also represented with single digit or a
single special symbol which is enclosed in
single quotes.
– Eg: ‘a’, ‘8’,’_’etc.

Noornilo Nafees 33
Character constants
String constants
• String constant are sequence of characters
enclosed with in double quote.
• Eg: “Hello” ,”444”,”a” etc,.

Noornilo Nafees 34
Operators
• An operator is a symbol that specifies an
operation to be performed on the
operands.
• Eg: a + b
+ is an operator.
a,b are operands.

Noornilo Nafees 35
Data Types
 A Data type is the type of data that are
going to access within the program.

Noornilo Nafees 36
DATA TYPES

DATA TYPES

USER
PRIMARY DERIVED
DERIVED

CHARACTER INTEGER REAL

short int, Array, Function, Structure, union


char
int, long int Pointer ….
Float,
double
longNoornilo
double Nafees 37
integer
 A number without a fraction part : integral
number.
 C supports three different sizes of the
integer data type :
 short int

 int

 long int

Noornilo Nafees 38
Floating Point
 A floating-point type is a number with a
fractional part, e.g. 56.78
 Floating point numbers are stored using
4 Byte.
 Types
 Float
 Double
 long double

Noornilo Nafees 39
character

• Character are generally stored using 8


bits(1 Byte) of the internal storage.

Noornilo Nafees 40
void
 The void type has no values and no
operations.
 Both the set of values and the set of
operations are empty.

Noornilo Nafees 41
Variable Declaration
 To create a variable, you must specify the type and
then its identifier :
 Integer
int a;
a=10;

int a=10;

int a,b;
a=10;
b=5;

int a=10,b=5;
Noornilo Nafees 42
Variable Declaration
 To create a variable, you must specify the type and
then its identifier :
 Float
float a;
a=10.5;

float a=10.5;

float a,b;
a=10.5;
b=5.5;

float a=10.5,b=5.5;
Noornilo Nafees 43
Variable Declaration
 To create a variable, you must specify the type and
then its identifier :
 Character
char a;
a=‘x’;

char a=‘x’;

char a,b;
a=‘x’;
b=‘y’;

char a=‘x’,b=‘y’;
Noornilo Nafees 44
Variable Declaration
 To create a variable, you must specify the type and
then its identifier :
 String
char a[6];
a=“NAFEES”;

char a[6]=“NAFEES”;

N A F E E S
a[0] a[1] a[2] a[3] a[4] a[5]

Representation of string a

Noornilo Nafees 45
Entire Data types in c:
Data type Size(bytes) Range Format string

Char 1 128 to 127 %c

Unsigned char 1 0 to 255 %c

Short or int 2 -32,768 to 32,767 %i or %d

Unsigned int 2 0 to 65535 %u

Long 4 -2147483648 to 2147483647 %ld

Unsigned long 4 0 to 4294967295 %lu

Float 4 3.4 e-38 to 3.4 e+38 %f or %g

Double 8 1.7 e-308 to 1.7 e+308 %lf


Noornilo Nafees 46
Long Double 10 3.4 e-4932 to 1.1 e+4932 %lf
Basic C programs
#include<stdio.h>//program to display given data
#include<conio.h>
void main()
{
OUTPUT
int a=10; Integer value : 10
float b=10.88; Float value : 10.88
char c=‘$’; Character :$
String : Nafees
char d[6]=“Nafees”;
clrscr();
printf(“Integer value : %d\n”,a);
printf(“Float value : %f\n”,b);
printf(“Character : %c\n”,c);
printf(“String : %s”,d);
getch();
} Noornilo Nafees 47
Basic C programs
#include<stdio.h>//program to display given data from user
#include<conio.h>
void main() printf(“Integer value : %d\n”,a);
{ printf(“Float value : %f\n”,b);
int a; printf(“Character : %c\n”,c);
printf(“String : %s”,d);
float b;
getch();
char c; }
char d[6];
clrscr();
OUTPUT
Enter a integer value :12
printf(“Enter a integer value : “); Enter a float value : 5.34
scanf(“%d”,&a); Enter a character : h
printf(“Enter a float value : “); Enter a string : Nafees
scanf(“%f”,&b); Integer value : 12
printf(“Enter a character : “); Float value : 5.34
Character :h
scanf(“%c”,&c); String : Nafees
printf(“Enter a string : “);
Noornilo Nafees 48
scanf(“%s”,d);
Types of Operator
1. Arithmetic operator
2. Relational operator
3. Logical operator
4. Assignment operator
5. Short hand assignment operator
6. Increment or decrement operator(unary)
7. Comma operator
8. Conditional operator
9. Bitwise operator
Noornilo Nafees 49
Arithmetic operator
• It is used to carry out arithmetic
operations
NAME OPERATOR
ADDITION +
SUBTRACTION -
MULTIPLICATION *
DIVISION /
MODULUS %
(REMAINDER)

Noornilo Nafees 50
SAMPLE PROGRAM
#include<stdio.h> // Header File
#include <conio.h>
void main ( ) /* main is the starting of every c program */
{
int a=5,b=2; //Local Declaration
clrscr( ); OUTPUT
printf(“Addition : %d\n”,(a+b)); Addition :7
printf(“Subtraction : %d\n”,(a-b)); Subtraction :3
printf(“Multiplication : %d\n”,(a*b)); Multiplication : 10
Division :2
printf(“Division : %d\n”,(a/b)); Modulus(remainder):1
printf(“Modulus(remainder): %d”,(a%b));
getch( );
}

Noornilo Nafees 51
Division operator on Different
Data Type

Operation Result Example


int/int int 5/2 = 2
int/real real 5/2.0 = 2.5
real/int real 5.0/2 = 2.5
real/real real 5.0/2.0 = 2.5

Noornilo Nafees 52
Relational operator
• It is used to compare two or more
operands and returns 1 if true else return 0
NAME OPERATOR
Less than <
Less than or equal to <=
Greater than >
Greater than or equal to >=
Equal to ==
Not equal to !=

Noornilo Nafees 53
Relational Operator…
#include<stdio.h>
#include <conio.h>
void main()
{
clrscr();
printf(“\n5!=3:%d”,(5!=3)); OUTPUT
printf(“\n5<=3:%d”,(5<=3)); 5!=3 :1
printf(“\n5>=3:%d”,(5>=3)); 5<=3 :0
printf(“\n5<7 :%d”,(5<7)); 5>=3 :1
printf(“\n5>4 :%d”,(5>4)); 5<7 :1
5>4 :1
getch();
}

Noornilo Nafees 54
Logical operator
• It is used to perform logical operations

NAME OPERATOR
AND &&
OR ||
NOT !

Noornilo Nafees 55
Sample program
#include<stdio.h>
#include <conio.h>
void main ( )
{
clrscr( );
printf(“\n(5<=8)&&(4>=2):%d”,((5<=8)&&(4>=2)));
printf(“\n(5>=3)||(6<4):%d”,((5>=3)||(6<4)));
printf(“\n!(7==7):%d”,!(7==7));
getch( );
} OUTPUT
(5<=8)&&(4>=2) : 1
(5>=3)||(6<4) :1
!(7==7) :0

Noornilo Nafees 56
Assignment operator
• It is used to assign a value or
expression etc to a variable.

• Eg: a =10.(assignment operator ‘=‘


assigns value 10 to variable a.
a=b
a = b + c etc,.

Noornilo Nafees 57
Shorthand Assignment Operator

Noornilo Nafees 58
Increment & Decrement Operator
NAME OPERATOR
Increment operator ++
Decrement operator --

Pre Increment Post Increment


int a=10; int a=10;
++a a++
Now value of a is 11 Now value of a is 11

Pre decrement Post decrement


int a=10; int a=10;
--a a--
Now value of a is 9 Now value of a is 9

Noornilo Nafees 59
Increment & Decrement Operator
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“Enter a & b value : \n”);
scanf(“%d%d”,&a,&b);
printf(“Value of a & b before increment : %d %d\n”,a,b);
printf(“Value of a & b after increment : %d
%d\n”,a++,b++);
printf(“Value of a & b after decrement : %d %d\n”,a--,b—);
getch();
} Noornilo Nafees 60
Increment & Decrement Operator

OUTPUT
Enter a & b value :
6
9
Value of a & b before increment : 6 9
Value of a & b after increment : 7 10
Value of a & b after decrement : 5 8

Noornilo Nafees 61
Conditional Operator (or)
Ternary Operator
• It is used to checks the condition and
execute the statement depending on the
condition.
• Eg: C = a > b ? a:b

Noornilo Nafees 62
Sample Program
#include<stdio.h>
#include <conio.h>
void main ( ) OUTPUT
The Larger Value is 8
{
int a=5,b=8,c;
clrscr( );
c = a>b?a:b; //Conditional operator
printf(" \n The Larger Value is %d",c);
getch( );
}

Noornilo Nafees 63
Output
The Larger Value is 8

OUTPUT
The Larger Value is 8

Noornilo Nafees 64
Special Operator
• comma operator ( , )

EX: int a,b;

Noornilo Nafees 65
Expression
• An expression represent data item such as
variable, constant are interconnected
using operators.
• Eg:

Expression C Expression
a+b+c a+b+c
a2+b2 a*a + b*b

Noornilo Nafees 66
Precedence Operator

High *,/,%

Low +,-

Noornilo Nafees 67
Type Conversion
• Converting the type of an expression from
one type to another type.
Eg: x = (int)10.45

Noornilo Nafees 68
Sample Program
#include<stdio.h>
#include <conio.h>
void main ( )
{
int c;
clrscr( );
c=(int)10.45;
printf("\nOutput is:%d",c);
getch( );
}
OUTPUT
Output is:10
Noornilo Nafees 69
Input/Output Function
Input/Output
Function

Formatted Unformatted

Input Output
Input Output getc()
gets() putc()
scanf() printf() getchar() puts()
Noornilo Nafeesgetch() putchar()
70
Formatted Input/Output
 C uses two functions for formatted
input and output.

 Formatted input : reads formatted


data from the keyboard.

 Formatted output : writes formatted


data to the monitor.

Noornilo Nafees 71
Formatted Input and Output

Noornilo Nafees 72
Standard Output
 The standard output file is the monitor.

 Like the keyboard, it is a text file.

 When you need to display data that is


not text, it must be converted into to the
text before it is written to the screen.
Noornilo Nafees 73
Format of printf Statement

Noornilo Nafees 74
Formatted Input (scanf)

• The standard formatted input function in C is


scanf (scan formatted).
• scanf consists of :
 a format string .

 an address list that identifies where data

are to be placed in memory.


scanf ( format string, address list );

(“%c….%d…..%f…..”, &a,….&i,…..,&x…..)
Noornilo Nafees 75
Format of scanf Statement

Noornilo Nafees 76
Character Test Function
• It is used to test the character taken from
the input.
• isalpha(ch)
• isdigit(ch)
• islower(ch)
• isupper(ch)
• tolower(ch)
• toupper(ch) etc,.

Noornilo Nafees 77
getchar() Example
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char x;
printf("enter the character:");
x=getchar();
Noornilo Nafees 78
if(islower(x))
putchar(toupper(x));
else
putchar(tolower(x));
getch();
}

Output:
enter the character : A
a Noornilo Nafees 79
getc Example
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char x;
printf("enter the character:");
x=getc(stdin);
Noornilo Nafees 80
if(islower(x))
putc(toupper(x),stdout);
else
putc(tolower(x),stdout);
getch();
}

Output:
enter the character:a
A
Noornilo Nafees 81
gets() Example
#include <stdio.h>
#include<conio.h>
void main()
{
char c[80];
clrscr();
printf("Input a string:");
gets(c);
Noornilo Nafees 82
printf("The string is:");
puts(c);
getch();
}

Output:
Input a string:qwerty
The string is:qwerty
Noornilo Nafees 83
getch() Example
#include <stdio.h>
#include <conio.h>
void main()
{
char c;
clrscr();
printf("\nInput a character:");
c = getch();
Noornilo Nafees 84
printf("\nCharacter is:");
putch(c);
getch();
}
Output:
Input a character : N
Character : N

Noornilo Nafees 85
PROGRAM CONTROL STRUCTURES
• Depending upon the sequence of the execution of
statements, the control structures are categorized as
follows:
• Categories:
• Sequential structure
– In which instructions are executed in sequence.
• Selection structure
– In which instruction are executed based on the result
of some condition.
• Iteration structure
– In which instruction are executed repeatedly.

86
Sequential STRUCTURE
• It allows the program to flow in
sequence
START

Statement 1

Statement 2

Statement N

STOP
87
SELECTION STRUCTURE
• It allows the program to make a choice
from alternative paths.
• C provide the following selection
structures
– if statement
– if … else statement
– Nested if … else statement

88
if Statement
Syntax
if (condition is true)
{ True If
condition
Statements;
Statements False

89
if…else Statement
Syntax
if (condition)
{ If
True False
True statements; Condition
}
else True False
{ statements statements
False statements;
}

90
Nested if…else
TRUE Condition FALSE
1

TRUE Condition FALSE


Statements 2

TRUE Condition FALSE


Statements 3

Statements Statements

91
Syntax Nested if…else
IF (condition1)
{
statements;
}
else if (condition2)
{
statements;
}
else if (condition3)
{
statements;
}
else
{
statements; 92
}
Iteration structure
• It is used to execute some instructions
several time based on some condition.
– while
– do…while
– for

93
while Loop
Syntax
.

while (condition)
{ False
condition
.
Body of the loop;
True
.
} Body of The loop

94
do…while Loop
Syntax
do
{
Body of The loop

Body of the loop


True
condition
}while (condition);
False

95
for loop
Syntax
for (initialization; test condition; Increment/Decrement)
{

Body of the loop

96
for loop

Initialization

Inc / Decrement

Body of the loop

condition False

97
Nested for loop
Syntax
for (initi; cond; Inc/Dec)
{

for (initi; cond; Inc/Dec)


{

Body of the loop

}
98
DECISION MAKING & BRANCHING
• if statement
• if else statement
• Nested if else statement Selection statements

• switch statement
• Conditional statement

• goto statement
Unconditional
• break statement statements
• continue statement

99
if statement (Simple if)
Syntax
if (condition is true)
{

Statements;

100
if statement (Simple if)
#include<stdio.h>
#include <conio.h>
void main ( )
{ OUTPUT
int a;
clrscr( ); Enter the number: 12
printf("\nEnter a number:"); a is greater than 10
scanf("%d",&a);
if(a>10)
{
printf(" \n a is greater than 10");
}
getch( );
}
101
if else statement
Syntax
if (condition is true)
{

Statements;

}
else
{

Statements;

} 102
if else statement
#include<stdio.h>
#include <conio.h>
void main ( ) OUTPUT
{
int a; Enter the number: 12
clrscr( ); a is greater than 10
printf("\nEnter a number:");
scanf("%d",&a); Enter the number: 1
if(a>10) a is not greater than10
{
printf(" \n a is greater than 10");
}
else
{
printf(" \n a is not greater than 10");
}
getch( );
} 103
Nested if else statement
Syntax
if (condition is true) else
{ {
Statements; Statements;
} }
else if (condition is true)
{
Statements;
}
else if (condition is true)
{
Statements;
} 104
Nested if else statement
#include<stdio.h>
#include<conio.h>
void main()
{
int m1,m2,m3;
float avg;
printf("\nEnter the marks:");
scanf("%d%d%d",&m1,&m2,&m3);
avg=(m1+m2+m3)/3;
printf("\n The average is:%f",avg);
printf("\n The Grade is:");
if(avg>=60)
{
printf("First class");
} 105
else if(avg>=50)
{ OUTPUT
printf("Second class");
} Enter the marks:65
else if(avg>=35) 75
{ 70
printf("Third class"); The average is:70.00
} The Grade is: First
else class
{
printf("Fail");
}
getch();
}

106
switch statement
Syntax
switch (expression)
{ Switch
case constant 1:
block1; Case 1
break;
case constant 2:
block2;
Case 2
break;
.
. Default
default : case
default block;
break;
}
107
switch statement
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,n;
clrscr();
printf("\nEnter the value of a,b:\n");
scanf("%d%d",&a,&b);
printf("\nMENU");
printf("\n1.ADD\n2.SUB\n3.MULTIPLY\n4.EXIT");
printf("\nEnter the choice:");
scanf("%d",&n);

108
switch(n)
{
case 1:
c=a+b;
printf("\nThe result of Addition is:%d",c);
break;

case 2:
c=a-b;
printf("\nThe result of Subtraction is:%d",c);
break;

109
case 3:
c=a*b;
printf("\nThe result of Multiplication is:%d",c);
break;
case 4: OUTPUT
exit(0);
break; Enter the value of a,b:
5
default:
6
printf(“Wrong Choice”); MENU
} 1.ADD
getch(); 2.SUB
} 3.MULTIPLY
4.EXIT
Enter the choice:1
The result of Addition is:11

110
goto statement
• When a goto statement is encountered, the control
is transferred to the label.

goto label;
…………
…………
…………
label:
…………

111
goto statement
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
clrscr();
printf(“Enter a number to find odd or even no : “);
scanf(“%d”,&x);
if(x%2==0)
goto even;
else
goto odd;

112
goto statement
even:
printf(“%d is an even no”,x);
odd:
printf(“%d is an odd no”,x);
getch( );
}
OUTPUT

Enter a number to find odd or even no :5


5 is an odd no

113
continue statement
#include<stdio.h>
#include<conio.h> Continue statement terminates the
void main() current loop iteration & persist the loop with
{ next iteration
int a;
clrscr(); OUTPUT
for(a=1;a<=10;a++)
{ 1
if((a==5)||(a==7)) 2
continue; 3
else 4
6
printf(“%d\n”,a);
8
}
9
getch( ); 10
}

114
break statement

When break statement is encountered inside any


block or loop, control automatically passes to the first
statement after the block or loop

115
Branching and Looping
• Loop:
– A loop is defined as a block of statements
which are repeatedly executed for certain
no of times.

• Types of Loops in C
– while loop
– do while loop
– for loop(simple & nested)

116
while loop
• It is an entry controlled loop works only when the condition is
true

• Syntax:

while (condition)
{
.
Body of the loop;
.
}

117
while loop
#include<stdio.h> //program to print even no
#include<conio.h>
void main()
{
int n,i;
printf(“Enter the limit : “);
scanf(“%d”,&n);
i=1; OUTPUT
while (i<=n)
{ Enter the limit : 10
if(i%2==0) 2 4 6 8 10
{
printf(“%d\t”,i);
}
i++;
}
}
Noornilo Nafees 118
while loop
#include<stdio.h> //program to calculate factorial of given no
#include<conio.h>
void main()
{
int i=1,fact=1,n;
printf("\nEnter the Number:"); OUTPUT
scanf("%d",&n);
while(i<=n) Enter the Number:3
{ The value of 3! is: 6
fact =fact *i;
i++;
}
printf("\n The value of %d! is:%d",n,fact);
getch();
}

119
while loop
#include<stdio.h> //program to reverse a number and to check
#include<conio.h>// whether it is palindrome or not
void main() if(n==rev)
{ {
int n,rev=0; printf(“Palindrome”);
clrscr(); }
printf(“Enter a number to reverse : “); else
scanf(“%d”,&n); {
while(n!=0) printf(“Not Palindrome”);
{ }
rev=rev*10; getch():
rev=rev+(n%10); }
n=n/10; OUTPUT
} Enter a number to
printf(“Reverse of given no is : %d\n”,rev); reverse : 452
Reverse of given
number is : 254
Not Palindrome 120
while loop
#include<stdio.h> //program to find sum of digits
#include<conio.h>
void main() OUTPUT
{
int r=0,sum=0,n; Enter the no:156
printf("\nEnter the no:"); sum of the digits is:12
scanf("%d",&n);
while(n>0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
printf("sum of the digits is:%d",sum);
getch():
} 121
#include<stdio.h> //program to find armstrong number
#include<conio.h>
void main()
{
int r=0,sum=0,n,a; OUTPUT
printf("\nEnter the number:");
scanf("%d",&n); Enter the number:153
a=n; It is an armstrong number
while(n>0)
{
r=n%10;
sum=sum+r*r*r;
n=n/10;
}
if(a==sum)
printf("\nIt is an armstrong number");
else
printf("\nIt is not an armstrong number");
getch();
} 122
do while loop
• It is an exit controlled loop. It proceeds its first iteration without
checking the loop condition and proceeds next iteration by
checking the condition.

• Syntax:
do
{
.
Body of the loop;
.
}while (condition);

123
do while loop
#include<stdio.h> //program to calculate factorial of given no
#include<conio.h>
void main()
{
int i=1,fact=1,n;
printf("\nEnter the Number:"); OUTPUT
scanf("%d",&n);
do Enter the Number:3
{ The value of 3! is: 6
fact =fact *i;
i++;
}while (i<=n);
printf("\n The value of %d! is:%d",n,fact);
getch();
}

124
for loop

Syntax:

for (initialization; test condition; Increment/Decrement)


{

Body of the loop

125
for loop
#include<stdio.h> //program to generate number from 1 to n
#include<conio.h>
void main()
{
int i,n;
printf("\nEnter the limit : "); OUTPUT
scanf("%d",&n);
for(i=1;i<=n;i++) Enter the limit : 5
{
printf(“%d\n”,i); 1
} 2
getch(); 3
} 4
5

126
for loop
#include<stdio.h> //program to calculate factorial of given no
#include<conio.h>
void main()
{
int i,fact=1,n;
printf("\nEnter the Number:"); OUTPUT
scanf("%d",&n);
for(i=1;i<=n;i++) Enter the Number:3
{
fact =fact *i; The value of 3! is: 6
}
printf("\n The value of %d! is:%d",n,fact);
getch();
}

127
Fibonacci Series

#include <stdio.h>
#include <conio.h>
void main()
{
int i, n, t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
OUTPUT
for (i = 1; i <= n; i++)
{
Enter the number of terms:5
printf("%d ", t1);
Fibonacci series:0 1 1 2 3
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
getch();
} 128
for loop
#include<stdio.h> //program to generate given multiplication table
#include<conio.h>
void main()
{
int i,tab,n,res;
printf("\nEnter the multiplication table:");
scanf("%d",&tab);
printf("\nEnter the limit of multiplication table:");
scanf("%d",&n); OUTPUT
for(i=1;i<=n;i++)
{
res=i*tab; Enter the multiplication table : 2
printf("%d * %d : %d\n”,i,tab,res); Enter the limit of multiplication
} table :4
getch(); 1*2:2
} 2*2:4
3*2:6
4*2:8
129
for loop
#include<stdio.h>//program to calculate student marks & average using for loop
#include<conio.h>
void main()
{
int i,n,s1,s2,s3,s4,s5,tot;
float avg;
clrscr();
printf(“Enter no of students : ”);
scanf(“%d”,&n);
printf(“Enter marks of five subjects : \n”)
for(i=1;i<=n;i++)
{
printf(“Enter student %d marks\n”,i);
scanf(“%d%d%d%d%d”,&s1,&s2,&s3,&s4,&s5);
tot=s1+s2+s3+s4+s5;
avg=tot/5;
printf(“Total : %d\nAverage : %f”,tot,avg);
}
getch();
130
}
for loop
• Definition of prime number:
– A natural number greater than one has not any other divisors except
1 and itself. In other word we can say which has only two divisors 1
and number itself.
– For example: 5. Their divisors are 1 and 5.

131
for loop
#include<stdio.h>//program to check whether the given no is prime or not
#include<conio.h>
void main()
{
int n, i, c = 0;
printf("Enter a number :");
OUTPUT
scanf("%d", &n);
for (i = 1; i <= n; i++) Enter a number : 7
{ Given no is a Prime number
if (n % i == 0)
{
c++;
}
}
if (c == 2)
printf(“Given no is a Prime number");
else
printf(“Given no is not a Prime number");
getch(); 132
}
Nested for loop

Syntax
for (initi; cond; Inc/Dec)
{
for (initi; cond; Inc/Dec)
{
Body of the loop
}
}

133
Nested for loop
#include<stdio.h> //program to generate numbers in triangle
#include<conio.h>
void main()
{
OUTPUT
int i,j,n;
printf("\nEnter the limit : "); Enter the limit : 5
scanf("%d",&n); 1
for(i=1;i<=n;i++) 22
{ 333
for(j=1;j<=i;j++) 4444
{
55555
printf(“%d”,i);
}
printf(“\n”);
}
getch();
}

134
Nested for loop
#include<stdio.h> //program to generate stars(*) in triangle
#include<conio.h>
void main()
{
OUTPUT
int i,j,n;
printf("\nEnter the limit : "); Enter the limit : 5
scanf("%d",&n); *
for(i=1;i<=n;i++) **
{ ***
for(j=1;j<=i;j++) ****
{
*****
printf(“*”);
}
printf(“\n”);
}
getch();
}

135
Swapping without using third
variable
#include<stdio.h>
#include <conio.h>
void main ( )
{
int a,b;
clrscr( );
printf(" \nEnter the value of a:");
scanf("%d",&a);
printf(" \nEnter the value of b:");
scanf("%d",&b);

136
a=a+b;
b=a-b;
a=a-b;
printf(" \nThe value of a is:%d",a);
printf(" \nThe value of b is:%d",b);
getch( );
}

Output:
Enter the value of a:5
Enter the value of b:6

The value of a is:6


The value of b is:5
137
Quadratic Equation
#include<stdio.h>
#include <conio.h>
#include<math.h>
void main ( )
{
int a,b,c,d,r1,r2;
clrscr( );
printf(" \nEnter the value of a:");
scanf("%d",&a);
printf(" \nEnter the value of b:");
scanf("%d",&b);
printf(" \nEnter the value of c:");
scanf("%d",&c);
d=b*b-4*a*c;
138
if(d>=0)
{
r1=(-b+sqrt(d))/(2*a);
r2=(-b-sqrt(d))/(2*a);

printf(" \nThe roots are %d,%d",r1,r2);


}
else
{
printf(" \nThe roots are imaginary");
}
getch( );
}

139
Output
Enter the value of a:4

Enter the value of b:5

Enter the value of c:6

The roots are imaginary

140