0% found this document useful (0 votes)
33 views110 pages

Unit2 PDF

The document provides an overview of the C programming language. It discusses key aspects of C including: - C was developed in 1972 and designed for structured programming with functions to break code into modules. - The main function is the entry point for all C programs and other functions can be defined and called. - Preprocessor statements like #include are used to include header files with standard functions. - Variables, constants, and keywords are the basic elements used to write C programs along with operators, expressions, and basic data types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views110 pages

Unit2 PDF

The document provides an overview of the C programming language. It discusses key aspects of C including: - C was developed in 1972 and designed for structured programming with functions to break code into modules. - The main function is the entry point for all C programs and other functions can be defined and called. - Preprocessor statements like #include are used to include header files with standard functions. - Variables, constants, and keywords are the basic elements used to write C programs along with operators, expressions, and basic data types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 110

Unit 2

Overview of C

• C is a programming language developed at AT & T’s Bell Laboratories


of USA in 1972.
• It was designed and written by Dennis Ritchie.
• C is a structured programming language
• C supports functions that enables easy maintainability of code, by
breaking large file into smaller modules
• Comments in C provides easy readability
• C is a powerful language
Program structure
A sample C Program

#include<stdio.h>
int main( )
{

}
Preprocessor Statements:

• These statements begin with # symbol. They are


called preprocessor directives. These statements
direct the C preprocessor to include header files
and also symbolic constants in to C program.
• Some of the preprocessor statements are :
#include: for the standard input/output functions
• #define PI 3.141592 symbolic constant
Header files
• The files that are specified in the include section is
called as header file.
• These are precompiled files that has some functions
defined in them.
• We can call those functions in our program by
supplying parameters.
• Header file is given an extension .h
• C Source file is given an extension .c
Main function
• This is the entry point of a program
• When a file is executed, the start point is the main
function
• From main function the flow goes as per the
programmers choice.
• There may or may not be other functions written by
user in a program
• Main function is compulsory for any c program
Writing the first program
#include<stdio.h>
int main()
{
printf(“Hello world”);
return 0;
}

• This program prints Hello on the screen when we


execute it
The C Character Set

A character denotes any alphabet, digit or special symbol used to


represent information.
Constants, Variables and Keywords
The alphabets, numbers and special symbols when properly
combined form constants, variables and keywords. A constant is an
entity that doesn’t change whereas a variable is an entity that may
change.

There are two ways to define constant in C programming.


•const keyword
•#define preprocessor #include<stdio.h>
int main(){
const float PI=3.14;
#include<stdio.h> PI=4.5;
int main(){ printf("The value of PI is: %f",PI);
return 0;
const float PI=3.14; }
printf("The value of PI is: %f", PI);
return 0; } If you try to change the value of PI, it
will render compile time error.
The #define preprocessor is also used to define
constant.

The #define preprocessor directive is used to define constant


or micro substitution. It can use any basic data type.
Syntax: #define token value

#include <stdio.h>
#define PI 3.14
void main()
{
printf("%f",PI);
}
Rules for Constructing Integer Constants

•An integer constant must have at least one digit.


•It must not have a decimal point.
•It can be either positive or negative.
•If no sign precedes an integer constant it is assumed to be
positive.
•No commas or blanks are allowed within an integer constant.
Ex.: 426
+782
-8000
-7605
Rules for Constructing Real Constants

Real constants are often called Floating Point constants. The real
constants could be written in two forms—Fractional form and
Exponential form.
•A real constant must have at least one digit.
•It must have a decimal point.
•It could be either positive or negative.
•Default sign is positive.
•No commas or blanks are allowed within a real constant.
Ex.: +325.34
426.0
-32.76
-48.5792
Rules for Constructing Character Constants

• A character constant is a single alphabet, a single digit or a single


special symbol enclosed within single inverted commas.

• The maximum length of a character constant can be 1 character.

Ex.: 'A'
'I'
'5'
'='
C Variables
An entity that may vary during program execution is called a variable.
Variable names are names given to locations in memory.

Rules for Constructing Variable Names


•A variable name is any combination of alphabets, digits or
underscores. Some compilers allow variable names whose length
could be up to 247 characters.
•The first character in the variable name must be an alphabet or
underscore.
•No commas or blanks are allowed within a variable name.
•No special symbol other than an underscore (as in gross_sal) can be
used in a variable name.
Ex.: si_int
m_hra
pop_e_89
C Keywords

Keywords are the words whose meaning has already been


explained to the C compiler (or in a broad sense to the
computer). The keywords cannot be used as variable names
because if we do so we are trying to assign a new meaning to
the keyword, which is not allowed by the computer.
The general form of printf( ) function is,

printf ( "<format string>", <list of variables> ) ;

<format string> can contain,


%f for printing real values
%d for printing integer values
%c for printing character values
Return type and value of printf function

printf is a library function of stdio.h, it is used to display


messages as well as values on the standard output device
(monitor). printf returns an integer value, which is the total
number of printed characters.
new line character ( "\n")

#include <stdio.h>
void main()
{ int res;
res = printf("Hello\n");
printf("Total printed characters are: %d\n",res);
}
Return type and value of scanf function

scanf is a library function of stdio.h, it is used to take input


from the standard input device (keyboard). scanf returns an
integer value, which is the total number of inputs.

#include <stdio.h>
int main()
{ int x,y;
int res;
printf("Enter two number: ");
res=scanf("%d%d", &x,&y);
printf("Total inputs are: %d\n",res);
return 0;
}
Data Type Range Bytes Format
signed char -128 to + 127 1 %c
unsigned char 0 to 255 1 %c
short signed int -32768 to +32767 2 %d
short unsigned int 0 to 65535 2 %u
signed int -32768 to +32767 2 %d
unsigned int 0 to 65535 2 %u
long signed int -2147483648 to 4 %ld
+2147483647
long unsigned int 0 to 4294967295 4 %lu
float -3.4e38 to 4 %f
+3.4e38
double -1.7e308 to 8 %lf
+1.7e308
long double -1.7e4932 to 10 %Lf
+1.7e4932
Note: The sizes and ranges of int, short and long are compiler dependent. Sizes in this figure are
for 16-bit compiler.
I byte = 8 bits either 0 or 1

In case of signed one unsinged 2n-1


bit is reserved for sign
+/- 28-1 = 256-1=255
-2n-1 to 2n-1 -1 So range is 0 to 255 for
-27 to 27-1
= -128 to 127
unsinged char
Unsinged integer
If int takes 2 bytes then 2 bytes = 16 bits

Formula is 2n-1
216-1 = 65536-1=65535
Range is 0 to 65535

singed
0 to 65535 integer
-2n-1 to 2n-1 -1
-215 to 215 -1
-32768 to +32767
Identifiers : Identifiers are the name of functions, variables and
arrays. The identifiers are user-defined words in the C language.
These can consist of lowercase letters, uppercase letters, digits, or
underscores, but the starting letter should always be either an
alphabet or an underscore.

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


meaningful to the compiler.
Token is divided into six different types : Keywords, Operators,
Strings, Constants, Special Characters, and Identifiers.
Operators and Expressions

An operator specifies an operation to be performed


that yields a value. The variables, constants can be
joined by various operators to form an expression.

An operand is a data item on which an operator


acts. Some operators require two operands, while
others act upon only one operand. C includes a
large number of operators that fall under several
different categories, which are as follows
Expression

Expression is a combination of operators, constants,


variables and function calls. The expression can be
arithmetic, logical or relational

x+y //arithmetic operation


a = b+c //uses two operators ( =') and ( + )
a>b //relational expression
a== b //logical expression
func(a, b) //function call
•Arithmetic operators
•Assignment operators .
•Increment and Decrement operators
•Relational operators.
•Logical operators
•Conditional operator
• Comma operator
• sizeof operator
• Bitwise operators
•Other operators
Binary Arithmetic Operators
a= 17, b=4
Increment And Decrement Operators

C has two useful operators increment ( ++ ) and decrement ( - - ).


These are unary operators because they operate on a single
operand.

The increment operator ( ++ ) increments the value of the variable


by 1 and decrement operator ( - - ) decrements the value of the
variable by 1.

++x is equivalent to x = x + 1

--x is equivalent to x = x-I


These operators are of two types

Prefix increment / decrement - operator is written before the


operand (e.g. ++x or - -x )

Postfix increment / decrement - operator is written after the


operand (e.g. x++ or x - - )
Prefix Increment / Decrement
Here first the value of variable is incremented / decremented then the
new value is used in the operation .
X=3 (x whose value is 3.)
The statement y = ++x; means first increment the value of x by 1,
then assign the value of x to y .

equivalent to these two statements (x = x+1; y = x; )


Hence now value of x is 4 and value of y is 4.
The statement y = - -x ;
means first decrement the value of x by 1 then assign the value of x to
y
This statement is equivalent to these two's statements
x = x -1 ; y= x;
Hence now value of x is 3 and value of y is 3.
Postfix Increment / Decrement
Here first the value of variable is used in the operation and then
increment/decrement is perform.
Let us take a variable whose value is 3.
The statement y = x++; means first the value of x is assigned to y
and then x is incremented.

statement is equivalent to these two statements y = x; x = x+1;


Output :
x is 4 and value of y is 3.
y = x- -; means first the value of x is assigned to y and then x is
decremented.
This statement is equivalent to these two statements
y = x;
x = x-I;
Output is x is 3 and value of y is 4.
Relational Operators

Relational operators are used to compare values of two


expressions depending on their relations. An expression that
contains relational operators is called relational expression. If
the relation is true "then the value of relational expression is 1
and if the relation is false then the value of expression is 0
a=9, b=5
Logical Or Boolean Operators

The expression that combines two or more expressions is


termed as a logical expression. For combining these
expressions we use logical operators. These operators
return 0 for false and 1 for true. C has three logical
operators.
AND ( &&) Operation (This operator gives the net result true if
both the conditions are true, otherwise the result is false. )

a = 10, b = 5, c = 0
nonzero values
are regarded as
true and zero
value is
regarded as
false
OR ( II) Operator
This operator gives the net result false, if both the conditions
have the value false, otherwise the result is true.

a = 10, b = 5, c =0
Consider the logical expression(a >= b) I I (b > 15)
This gives result true because one condition is true
Not ( ! ) Operator

This is a unary operator and it negates the value of the condition. If


the value of the condition is false then it gives the result true. If the
value of the condition is true then it gives the result false.

a = 10, b = 5, c = 0

! ( a = = 10 )

The value of the condition (a= =10) is true.


NOT operator negates the value of the condition. Hence the result is
false.
Assignment Operator

x=8

y=5

s = x+y-2 /* Value of expression x+y-2 is assigned to s*/

y=x /* Value of x is assigned to y*/


Operator Example
= C = A + B will assign the value of A + B to
C
+= C += A is equivalent to C = C + A
-= C -= A is equivalent to C = C - A
*= C *= A is equivalent to C = C * A
/= C /= A is equivalent to C = C / A
%= C %= A is equivalent to C = C % A
Conditional Operator

Conditional operator is a ternary operator ( ? and : ) which


requires three expressions as operands. written as

TestExpression ? expression1 : expression2

TestExpression is evaluated first

•If TestExpression is true(nonzero), then expression1 is evaluated


and it becomes the value of the overall conditional expression.

•If TestExpression is false(zero), then expression2 is evaluated and


it becomes the value of overall conditional expression.
Conditional Operator

Conditional operator is a ternary operator ( ? and : ) which requires


three expressions as operands. This written as

Test Expression ? expression1 : expression2

a < b ? printf("a is smaller") : printf("b is smaller");

max = a > b ? a : b;
sizeof operator
sizeof is an unary operator. This operator gives the size of
its operand in terms of bytes. The operand can be a
variable, constant or any datatype ( int, float, char etc ).

How to get the sizes:


char c;
int i;
printf("%d,%d\n", sizeof(c), sizeof(i) );

Output: 1,4
Bitwise Operators

C has the ability to support the manipulation of data at the


bit level. Bitwise operators are used for operations on
individual bits. Bitwise operators operate on integers only.
The bitwise operators are as
Bitwise AND Operator ( & )

The output of bitwise AND is 1 if the corresponding bits of two


operands is 1. If either bit of an operand is 0, the result of
corresponding bit is evaluated to 0.

bitwise AND operation of two integers 12 and 25.

12 = (In Binary)
0 0 0 0 1 1 0 0
25 = (In Binary)
________ & 0 0 0 1 1 0 0 1
8 (In decimal) 0 0 0 0 1 0 0 0
Bitwise OR Operator ( | )

The output of bitwise OR is 1 if at least one corresponding bit of


two operands is 1. In C Programming, bitwise OR operator is
denoted by |.

12 0 0 0 0 1 1 0 0

25 0 0 0 1 1 0 0 1
0 0 0 1 1 1 0 1 29
Bitwise XOR (exclusive OR) Operator ^

The result of bitwise XOR operator is 1 if the corresponding bits of


two operands are opposite.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25


000011 0 0
^ 000110 0 1
___________
00010101 = 21 (In decimal)
Bitwise Complement Operator

Bitwise complement operator is a unary operator (works on only one


operand). It changes 1 to 0 and 0 to 1. It is denoted by . Bitwise
complement of any number N is -(N+1).

0 0 1 0 0 0 1 1 35

1 1 0 1 1 1 0 0

#include <stdio.h>
int main() {
printf("Output = %d\n",~35);
printf("Output = %d\n",~-12);
return 0;
}
Output = -36
Output = 11
The bitwise complement of 35 (~35) is -36 instead of 220, but
why?

For any integer n, bitwise complement of n will be -(n + 1).


Precedence And Associatively of operators

Consider the following expression

2+3*5

If addition is performed before multiplication then result will be 25

and if multiplication is performed before addition then the result


will be 17.
Associativity of Operators

When an expression contains two operators of equal priority the


tie between them is settled using the associativity of the
operators. Associativity can be of two types—Left to Right or
Right to Left.
x = a+b < c

+ operator has higher precedence than < and =, and < has
more precedence than =, so first a+b will be evaluated,
then < operator will be evaluated, and at last the whole
value will be assigned to x.

If a = 2,b = 6, c = 9 then final value of x will be ??


x = a<=b II b==c

Here order of evaluation of operators will be

<=, = =, II,=. If initial values are

a = 2, b = 3, c = 4,

then final value of x will 'be 1.


To solve these types of problems, an associativity
property is assigned to each operator. Associativity of
the operators within same group is same. All the
operators either associate from left to right or from
right to left

5 + 16 / 2 *4 since / and * operators associate from


left to right so / will be evaluated before * and the
correct result 37.
An escape sequence is a sequence of characters which are used in
formatting the output. They are not displayed on the screen while
printing.

An escape sequence contains a backslash (\) symbol followed by one


of the escape sequence characters
Conditional Statements
Control Statements
In C programs, statements are executed sequentially in the order in
which they appear in the program. But sometimes we may want to
use a condition for executing only a part of program. Also many
situations arise where we may want to execute some statements
several times. Control statements enable us to specify the order in
which the various instructions in the program are to be executed.
This determines the flow of control. Control statements define how
the control is transferred to other parts of the program. C language
supports four types of control-statements, which are as
1. if...else
2. goto
3. switch
4. loop (while, do...while , for)
5. Break
6. continue
Compound Statement or Block

A compound statement or a block is a group of statements enclosed


within a pair of curly braces { } The statements inside the block are
executed sequentially. The general form is
{
statementl;
statement2;
…………. }
For example

{ l=4;
b=2;
area=l*b;
printf("%d",area) ;
}
if...else
•This is a bi-directional conditional control statement.

•This statement is used to test a condition and take one of the two
possible actions.

•If the condition is true then a single statement or a block of


statements is executed (one part of the program), otherwise
another single statement or a block of statements is executed
(other part of the program).

•nonzero value is regarded as true while zero is regarded as false.


if(condition)
if(condition) {

Statement l; Statements;
………

}
if(condition)
if(condition)
{
statement l;
statement;
else
………..
statement 2 ;
}

else
{
statement;
……….
}
Program to print a message if negative number is
entered

#include<stdio.h>
Void main ( )
{
int num;
printf("Enter a number”);
scanf("%d“, &num};

if (num<0)
printf ("Number entered is negative);

}
if ( a = 10 )
printf ( "Even this works" ) ;

if ( -5 )
printf ( "Surprisingly even this works" ) ;

In the first if, 10 gets assigned to a so the if is now reduced to if ( a )


or if ( 10 ). Since 10 is non-zero, it is true hence again printf( ) goes
to work.

In the second if, -5 is a non-zero number, hence true. So again


printf( ) goes to work. In place of -5 even if a float like 3.14 were
used it would be considered to be true.
The current year and the year in which the employee joined
the organization are entered through the keyboard. If the
number of years for which the employee has served the
organization is greater than 3 then a bonus of Rs. 2500/- is
given to the employee. If the years of service are not greater
than 3, then the program should do nothing.
int main( )

{ int bonus, cy, yoj, yr_of_ser ;

printf ( "Enter current year and year of joining " ) ;


scanf ( "%d %d", &cy, &yoj ) ;

yr_of_ser = cy - yoj ;

if ( yr_of_ser > 3 )
{ bonus = 2500 ;
printf ( "Bonus = Rs. %d", bonus ) ;
}
Return 0;
}
In a company an employee is paid as under:

If his basic salary is less than Rs. 1500, then


HRA = 10% of basic salary and DA = 90% of
basic salary. If his salary is either equal to or
above Rs. 1500, then HRA = Rs. 500 and DA
= 98% of basic salary. If the employee's salary
is input through the keyboard write a program
to find his gross salary.
/* Calculation of gross salary */
main( )
{
float bs, gs, da, hra ;

printf ( "Enter basic salary " ) ;


scanf ( "%f", &bs ) ;

if ( bs < 1500 )
{
hra = bs * 10 / 100 ;
da = bs * 90 / 100 ; }
else
{
hra = 500 ;
da = bs * 98 / 100 ;
}

gs = bs + hra + da ; printf ( "gross salary = Rs. %f", gs ) ;

}
Nesting of if...else
if (condition 1)
{
if (condition 2)
statement A1;
else
statement A2;
}
else
{
if(condition 3)
statement B1
else

statement B2;
}
Program to find largest number from three given numbers

#include<stdio.h>
main( )
{ int a,b,c,large;
printf ("Enter three· numbers ") ;
scanf("%d%d%d",&a,&b,&c) ;
if (a>b)
{ if(a>c)
large=a;
else
large=c;
}
else
{ if (b>c)
large=b;
else
large=c;
}
printf(largest number is %d\n", large) ; }
else if Ladder
This is a type of nesting in which there is an if. ..else statement in every else part
except the last else part. This type of nesting is frequently used in programs and is
also known as else if ladder.

Here each condition is checked, and when a condition is found to be true, the
statements corresponding to that are executed, and the condition comes out of
the nested structure without checking remaining conditions. If none of
theconditions is true then the last else part is executed.
if (per>=85)
grade= 'A' ;
else if(per>=70)
grade='B';
else if (per>=55)
grade= 'C' ;
else if (per>=40)
grade= 'D' ;
else
grade='E';
Switch Case
switch (expression) {
case constant1:
statements;
Switch case statement break;
evaluates a given
expression and based on case constant2:
the evaluated statements;
value(matching a certain break;
condition), it executes .
the statements associated .
with it. Basically, it is .
used to perform different default:
actions based on different // code to be executed if
conditions(cases). // expression doesn't match
any constant
}
*Program that demonstrate switch-case-default*/

void main()
{
int ch;
float n1,n2,res=0;
clrscr();
printf("\n\n **************** WELCOME TO THE WORLD OF
MATHEMATICS************");
printf("\n\n\t1.) Addition");
printf("\n\t2.) Subtraction");
printf("\n\t3.) Multiplication");
printf("\n\t4.) Division");
printf("\n\t5.) Exit");

printf("\n\n Enter your choice from the list: ");


scanf("%d",&ch);
printf("\n Enter the values for two numbers:");
scanf("%f%f",&n1,&n2);
switch(ch) {
case 1:
res=n1 + n2;
break;
case 2:
res=n1 - n2;
break;
case 3:
res=n1 * n2;
break;
case 4:
res=n1 / n2;
break;
case 5:
exit(0);
default:
printf("\n You Entered wrong choice. \n");
}
printf("\n The result of operation is=%f",res);
printf("\n\n\n Press any key to goto the source code! ");
getch();

}
1. C program to check whether a given character is ‘a’ or not.

2. C program to find largest from three numbers given by user to explain working of if-
else-if statement or ladder.

3. C program to print weekday based on given number (use if-else ladder).

4. C Program to Check Vowel or Consonant.

5. Write a C program to calculate the root of a quadratic equation.

6. Write a C program to determine eligibility for admission to a professional course


based on the following criteria:
Eligibility Criteria : Marks in Maths >=65 and Marks in Phy >=55 and Marks in
Chem>=50 and Total in all three subject >=190 or Total in Maths and Physics >=140.

Inputs are : Physics :65 Chemistry :51 Mathematics :72


Loops in C
Why Loops?
• The looping simplifies the complex problems into the easy ones.

• It enables to alter the flow of the program so that instead instead of writing writing
the same code again and again, we can execute the same code for a finite number
of times.

• It provides code reusability.


Essential components of a loop

• Counter

• Initialization of the counter with initial value.

• Condition to check with the optimum value of the counter

• Statement(s) to be executed by iteration

• Increment/decrement
For Loop
for( expressionl; expression2; expression3)
{ statement
statement
}

Expressionl is an initialization expression


expression2 is a test expression or condition
eexpression3 .is an update expression

expression1 is executed only once when the loop starts and is used to Initialize the loop
variables. This expression is generally an assignment expression. Expression2 is a condition
and is tested before each iteration of the loop. This condition generally uses relational and
logical operators. Expression3 is an update expression and is executed each time after the
body of the loop is executed.
Write a C program to print all alphabets from a to z.
Program to find Factorial of a number

#include<stdio.h>
int main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++){
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
return 0;
}
Fibonacci Series
#include <stdio.h>
int main()
{
int n1=0, n2=1, n3, i, number;
printf("Enter the number of elements: “);
scanf(“%d”, &number);
Printf(“%d %d”, n1,n2);

for(i=2;i<number; i++)
{
n3=n1+n2;
printf(“%d”, n3);
n1=n2;
n2=n3;
} return 0;
}
Write a C program to print multiplication table of any number.

#include <stdio.h>
int main() {
int n;
printf("Enter an integer: ");
scanf("%d", &n);

for (int i = 1; i <= 10; ++i) {


printf("%d * %d = %d \n", n, i, n * i);
}
return 0;
}
While loop

initialize loop counter ;


while ( test loop counter using a condition )
{ do this ;
and this ;
increment loop counter ;
}
Write a program to calculate the sum of first 10 numbers

void main()
{
int i=0,sum=0;
while (i<=10)
{
sum=sum+i;
i=i+1; //condition updated
}
Printf(“\n sum =%d”,sum)
}
Program to print numbers in reverse order with a difference
of 2
int k=10;
while(k>=2)
{

printf("%d \t, k);


k=k-2;
}

Output 10 8 6 4 2
Program to' print the sum of digits of any number

int main()
{
int n, sum=0, rem
printf ("Enter the number”)
scanf("%d, &n);
while(n>0)
{
rem=n%10 //taking the last digit of the number
sum=sum+rem;
n=n/10
}
printf ("Sum of digits = %d\n, sum) ;
return 0;
}
output: Enter the number: 1452 Sum of digits = 12
Program to find the product of digits of any number

int main() {
int n, prod=l, rem;
printf ("Enter the number :");
scanf("%d",&n) ;
while(n>0)
{ rem=n%10;
prod=prod *rem;
n=n/10;
}

printf("Product of digits = %d \n",prod);


return 0;
}
int main() To Check whether a given no. is palindrome or not
{
int n, r, sum=0, temp;
printf("Enter the Number“);
scanf(“%d”, &n);
temp=n;
while(n>0)
{
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
printf("Number is Palindrome.“);
else
printf("Number is not Palindrome.“);
return 0;
}
int main() To find whether a no is Armstrong or not
{
int n,r,sum=0,temp;
Printf("Enter the Number= “);
Scanf(“%d”, &n);
temp=n;
while(n>0)
{
r=n%10;
sum=sum+(r*r*r);
n=n/10;
}
if(temp==sum)
printf("Armstrong Number.“);
else
Printf("Not Armstrong Number.“);
return 0;
}
do...while loop
#include <stdio.h>
int main()
do {
{ int j=0;
do
//Statements {
Inc/dec; printf("Value of variable j is: %d\n", j);
} j++;
}
while (j<=3);
while(condition test); return 0;
}
do-while runs at least once even if the
condition is false because the condition is
evaluated, after the execution of the body
of loop.
Entry Control Loop the test condition is checked first
and if that condition is true then the block of the statement
will be executed,

While in Exit control loop first executes the body of the


loop and checks condition at last.
Add numbers until the user enters zero
#include <stdio.h>
int main()
{
int number, sum = 0;
do
{
printf("Enter a number: ");
scanf("%d", &number);
sum += number;
}
while(number != 0.0);
printf("Sum = %d ",sum);
return 0;
}
Nested For Loop
The syntax for a nested for loop statement in C is as follows:

for ( init; condition; increment )


{
for ( init; condition; increment )
{
inner loop statement(s);
}
outer loop statement(s);
}
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;
}
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;
}
#include<stdio.h>
int main()
{
int i,j,k;
for(i=3;i>0;i--)
{
for(j=3;j>=i;j--)
{
printf(" ");
}

for(k=1;k<=i;k++)
{
printf("*");
}
printf("\n");
}
}
#include<stdio.h>
int main()
{
int i,j,k;
for(i=3;i>0;i--)
{
for(j=1;j<=i;j++)
{
printf(" ");
}

for(k=3;k>=i;k--)
{
printf("*");
}
printf("\n");
}
}
To check whether a given no. is prime or not
#include <stdio.h>
using namespace std; if (flag==0)
int main() printf( "Number is Prime.“);
{ return 0;
int n, i, m=0, flag=0; }
printf("Enter the Number to check Prime: “);
scanf(“%d”, &n);
m=n/2;
for(i = 2; i <= m; i++)
{
if(n % i == 0)
{
printf("Number is not Prime.“);
flag=1;
break;
}
}
Program to find Prime Number between 1 to 100

#include <stdio.h>
int main ()
{
int i, j;
for(i=2; i<100; i++)
{
for(j=2; j <= (i/j); j++)
{
if(!(i%j))
break;
}
if(j > (i/j))
printf("%d is prime\n", i);
}
return 0;
Break and Continue Statement
C break statement
The break is a keyword in C which is used to bring the program control out of the loop.
The break statement is used inside loops or switch statement.

The break statement breaks the loop one by one, i.e., in the case of nested loops, it
breaks the inner loop first and then proceeds to outer loops.

Syntax:
1. //loop or switch case
2. break;
#include<stdio.h>
#include<stdlib.h>
void main ()
{
int i;
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);

}
continue statement :- The continue statement is used inside the body of the loop
statement. It is used when we want to go to the next iteration of the loop after skipping
some of the statements the loop.
It is generally used with a condition. When a continue statement is encountered all the
remaining statements (statements after continue) in the current iteration are not executed
and the loop continues with the next iteration.

The difference between break and continue is that when a break statement is encountered
the loop terminates and the control is transferred to the next statement following the
loop, but when a continue statement is encountered the loop is not terminated and the
control is transferred to the beginning of the loop

You might also like