C Lang Material
C Lang Material
Documentation section
Link section or pre processor commands
Definition section
Global declarations
main()
{
local declarations
Executable statements
}
User defined functions(argument list)
{
local declarations
executable statements
}
Documentation section:- This is the comment area where we give the description of the program.
The comments are given between the symbols /* and */.
Link section:- In a C program we use different C statements whose programs are written in
separate files. These files are known as header files which have an extension of .h. Some of the
header files are stdio.h, conio.h, string.h, math.h, alloc.h, graphics.h etc. When we are using any
of these statements then we have to link the respective header files in our program. We can
include as many header files as we want in our program. This is done by using the preprocessor
directive #include. The following statement shows the linking of a header file stdio.h
#include <stdio.h>
Definition section:- In this section, we define names to the constants. These values cannot be
changed in our program. While giving names to the constant we have to give them in UPPER
case, so that we can distinguish which is a variable and which is a constant. It is defined by using
the #define which is another preprocessor directive. This preprocessor directive is also used to
create macros in C.
Eg: #define A 45
Global declarations:- The variable declarations that are made outside the main are known as
global declarations. These variable values can be accesses outside the main () also.
main():- This is a special function name and should be included in the program. This is the first
function that will be executed when you run a program. Every C program should start with a
main().
{ and }:- All the C statements that form our program should be enclosed in { and } only.
Local declarations:-All the variables that are declared inside the main() are known as local
declarations. These can be accessed only in the main() and not outside the main().
Executable statements:- All the input and output statements, expressions that form our actual part
of the program are known as executable statements.
Rules For Writing A ‘C’ Program
1. All the C statements should be written in lowercase only.
2. C program should contain at least one main ( ).
3. The executable statements are enclosed in open brace ({ )and close brace( }).
4. Every statement should end with a semi colon (;)
5. We can write any number of statements in a single line separating them with a semi colon.
6. We can also write a single statement in multiple lines ending each line with a ‘\’.
7. The comments are written in between /* and */. We can write comments anywhere in the
program. These statements are ignored by the system. Comments are used to describe the
program, to describe a statement or to ignore some statements in the program.
C Tokens
In C program, the smallest individual units are known as C tokens. C has following tokens.
1) Character set
2) Identifiers
3) Keywords
4) Datatypes
5) Variables
6) Constants
7) Format Specifiers
8) Escape sequences
9) Operators
1) Character set:- The characters that can be used to form words, numbers and expressions
depend upon the computer on which the program is run. C uses the upper case letters from A to
Z, lower case letters from a to z, 0 – 9 digits and certain special characters as building blocks to
form basic program elements. Eg: constants, variables, expressions etc. The special characters
are +, -, *, / , =, %, &, #, !, ?, ^, “, ‘ | <, >, etc.
2) Identifiers:- Identifiers are the names that are given to various program elements such as
variables, functions and array. These are user defined names and consist of a sequence of letters
and digits. Both upper case and lower case letters are permitted. The following are the rules for
identifiers.
i) An identifier should not contain a blank space.
ii) We can use underscore( _ ) in an identifier.
iii) The first character should be an alphabet or an underscore( _ ). It should not be a number.
iv) They cannot use a keyword.
v) They can be of any length but first 31 characters are significant.
3) Keywords:- C has certain reserved words which are known as keywords that have some
special meaning in C. These are used only for their intended purpose and not for naming a
variable, functions or constants. There are 32 keywords in ANSI (American National Standard
Institute) C which are as follows.
auto double int struct
break else long switch
case enum register typedef
char extern return union
constant for short unsigned
continue float signed void
default goto size of volatile
do if static while
4)Datatypes:- Computer programs usually work with different types of data and need way to
store the values being used. These values can be numbers or characters. C language is rich in its
datatypes. The variety of datatypes available allows the programmer to select the type
appropriate to the needs of the application as well as the machine. The datatypes in C are
categorized as follows.
i) Primary data type Eg: int, float, char, long, double
ii) User defined data type Eg: typedef, enum
iii) Derived data type Eg: Structure and union
iv) Empty data set Eg: void
The primary datatypes are the basic datatypes and they are classified as int, long int, float, double
and char. Their types, size and range are listed in the table below.
int:- It is used to store numbers without decimals. It occupies a memory of 2 bytes (16 bits) in the
RAM. This can be used in the signed or unsigned form. Its range is from -32768 to 32767. Eg:
25, -45, 356, etc. Signed int has the same size and range as int datatype. Out of 16bits, the first
15 bits are used to represent the data and the 16th bit to the left side is used to represent the sign
of the value. If the bit position has a ‘0’, then it indicates a positive number and if it has a ‘1’, it
represents a negative number. The unsigned int has no sign and all the 16bits are used to
represent the data value. Its range is from 0 to 65535.
long int :- It is also used to store numbers without decimals. It is used to store values greater than
the ‘int’ datatype range. Its size is 4 bytes and its range is -2,147,483,648 to 2,147,483,647, etc.
Eg: 76, 12500, 45367, 65600 etc. It can also be used in the signed form or in the unsigned form.
float:- This datatype is used to store numbers with decimal values i.e, floating point values. It
occupies a memory of 4 bytes and its range is 3.4E-38 to 3.4E+38. Eg: 3.56, 1.28, 66.78 etc.
double:- This datatype is used to store numbers with decimal points more than the float range. It
occupies a memory of 8 bytes and its range is 1.7E-308 to 1.7E+308.
char:- It is used to store characters. It occupies a memory of 1 byte and its range is -128 to 127.
Eg: ‘r’,’U’, ‘P’, ‘a’ ‘&’,’%’, etc. Here the character range is specified as a number. These
numbers are the ASCII code of the characters. This can be in the signed form or in the unsigned
form.
5) Variables:- A variable is an identifier that is used to represent a specified type of data. A
variable is used to store a single data item, wither numeric data or character data. Each variable
in a program must be declared before they are used in a C program. The following is the syntax
to declare a variable.
Syntax for declaring a variable:-
datatype <var_name>;
Eg: int num;
float price;
char ch;
char city[15];
The datatype is the type of value we want to store in the variable. Var_name is the name of the
variable. Whenever, we declare a variable, memory will be allocated in the RAM which is equal
to the size of its datatype. To assign a value to a variable, we use ‘=’ symbol as shown below.
Eg: num=10;
price=28.50;
ch=’y’;
Rules to be followed while naming a variable
1. Variable name should consist of alphabets and numbers.
2. We should not use spaces in a variable name.
3. No special characters are allowed in a variable name except underscore( _ ).
4. The first character should be an alphabet or an underscore( _ ).
5. Variable name should be unique.
6. It should be short and meaningful.
7. Variable names should be in lowercase only.
8. We should not use C keywords to name a variable like if, else, auto etc.
6) Constants:- Constants refer to values that do not change during the execution of a program.
We use the keyword ‘const’ to declare a constant. There are 4 basic types of constants in C. They
are:
i) Integer constants
ii) Floating point (real) constants
iii) Character constants
iv) String constants
Integer and floating point constants represent numbers and they are often called numeric
constants. The following rules apply to all numeric type constants.
a) Commas and blank spaces are not permitted within the constant.
b) The constant can be preceded by a minus (-) sign if required.
c) The value of a constant must be within its minimum and maximum bounds of its
specified datatype.
i) Integer constant:- an integer constant is an integer valued number. It consists of a sequence of
digits. Integer constants can be written in 3 different number system as decimal (base 10), octal
(base 8) and hexadecimal (base 16).
Decimal integer constants consist of a set of digits form 0 through 9. Eg: 0 1 -56
32767 1234789L 65121U (unsigned integer constant)
Octal integer constant consists of any combination of digits between 0 through 7 with a
leading 0. Eg: 0 01 03456 07777
Hexadecimal integer constant must begin with ox or OX. It can then be followed by any
combination of digits 0 through 9 and a through f (or A to F). The letter A to F represents
decimal values 10 through 15 respectively. Eg: ox0 0x1 oxAF
ii) Floating point integer constant:- It is a base 10 number that contains either a decimal point or
exponent (or both).
Decimal notation : 1234.56, exponent or scientific notation : 1.23456E+3 (1.23456 x 103)
Eg: 0. 1. 0.00001 345.67
iii) Character constants:- A character constant is a character enclosed within single quotes. Eg:
‘y’ The character constants have integer values that are determined by the computer’s particular
character set. These may vary from one computer to another. All personal computers make use
of the ASCII character set. Eg: ‘A’ ‘a’ ‘+’ ‘?’ ‘ ’ , ‘5’
iv) String constants:- A string constant or string literal is a sequence of zero or more characters
surrounded by double quotes. Eg: “kakatiya” “yes” “ ” (empty string) “05P11A256”
7) Format specifiers:- These are used in the input and output statements when working with
variables. The following are the format specifiers used in C to accept or retrieve the values from
the variables.
%d int used for integer datatype
%ld long int used for long int
%f float used for float values
%lf double used for double
%c char used for a single character
%s string used for group of characters of char datatype
%u unsigned used for unsigned values like, to display memory addresses.
%o octal used to display octal equivalent of a decimal number
%x hexadecimal used to display hexadecimal equivalent of a decimal number
%i used to display decimal or hexadecimal or octal
%e used to display floating point number in exponential form
%g used to display floating point number with trailing zeroes truncated
8) Escape sequences:- C Supports some special backslash characters that are used in output
functions. An escape sequence always begins with a backslash and is followed by one or more
special characters. The following are some of the escape sequences.
\n new line character
\t Horizontal tab character
\v Vertical tab character
\a alert (bell sound)
\b backspace character (the cursor will be placed one character back)
\f form feed, (moves the cursor to the next line)
\r carriage return (moves the cursor to the starting of the line)
\’ single quote (prints a single quote)
\” double quote (prints double quotes removing the specialty of ‘\’)
OPERATORS IN ‘C’
Expression:- An expression consists of a single entity such as a constant, a variable, an array
element or a reference to a function or can be a combination of such entities joined together
using one or more operators. An expression can also represent logical condition, that is either
true or false, which can be represented using integer values like ‘1’ and ‘0’ respectively. Some of
the examples are as follows:
1) c= a+b*d;
2) x=y;
3) a = = b;
4) a+=b;
C supports a rich set of built-in operators. An operator is a symbol that tells the computer to
perform certain mathematical or logical manipulations. Operators are used in programs to
manipulate data and variables. They form a part of mathematical or logical expressions. The data
items that operators act upon are called operands (variables & constants). C operators can be
classified into the following categories:
1) Arithmetic Operators
2) Relational Operators
3) Logical Operators
4) Unary Operators
5) Assignment Operators
6) Conditional Operator or Ternary Operator
7) Bitwise Operators
8) Special operators
1) Arithmetic Operators:- C provides all the basic arithmetic operators. The different arithmetic
operators are those which we generally use in mathematics like + (addition), - (subtraction), *
(multiplication), and / (division). Apart from these, there is another operator % which is
known as modulus operator. This modulus operator gives you the remainder after division.
2) Relational Operators:- We often compare two quantities and depending on their relation,
take certain decisions. These comparisons can be done with the help of relational operators.
The relational operators that we use in C are to relate two operands are <(less than), >
(greater than), <= (less than or equal to), >= (greater than or equal to), = = (equal to) and !=
(not equal to). The double equal to (= =) is used to compare the equality of the operands and
is known as the equality operator.
3) Logical Operators:- The logical operators are used to check for more than one condition at a
time. The different logical operators available in C are logical AND (&&), logical OR(||) and
logical NOT(!). The && operator returns true when all the conditions are satisfied only. The
|| operator returns true when any of the condition is true and returns false only when all the
conditions are false. The following table shows the operations of these operators.
condition 1 condition condition1 condition 1 !condition1
2 && ||
condition2 condition 2
F F F F T
F T F T T
T F F T F
T T T T F
4) Unary Operators:- The unary operators available in C are – (unary minus i.e., negative sign),
++ (increment operator) and -- (decrement operator). These operators work on a single
operand. The unary minus (-) is used to assign a negative value to a variable.
Eg: a=5; b = -a; It stores –5 in ‘b’.
Increment Operator(++):- This operator increments the operand value (variable value) by 1.
There are 2 types of increment operators. (a) Pre increment operator and (b) Post increment
operator.
The Pre increment operator first increments the operand value by 1 and then
assigns the operand value to the Left Hand Side (LHS) variable. The operator is placed
before the variable. The following example illustrates this.
main()
{
int a=5,b;
b=++a;
printf(“\na=%d”,a);
printf(“\nb=%d”,b);
}
In the above program the values are 6 and 6 in ‘a’ and ‘b’ respectively.
The Post decrement operator first assigns the value to the variable on the LHS and
then the increments the operand value by 1. The operator is placed after the operand.
main()
{
int a=5,b;
b=a++;
printf(“\na=%d”,a);
printf(“\nb=%d”,b);
}
In the above program the values in ‘a’ and ‘b’ are 6 and 5 respectively.
Decrement Operator:- This is similar to increment operator but here the operand value is
decremented by 1. Here also we have 2 types of decrement operators and they are pre
decrement and post decrement operators.
The Pre decrement operator function is similar to pre increment operator but here
the value is decremented. In this, first value in the operand (variable) is decremented and
then assigned to the LHS variable. The following example illustrates this.
main()
{
int a=5,b;
b=--a;
printf(“\na=%d”,a);
printf(“\nb=%d”,b);
}
In the above program the values are 4 and 4 in ‘a’ and ‘b’ respectively.
The Post decrement operator first assigns the value to the LHS variable and then
the value of the operand is decremented.
main()
{
int a=5,b;
b=a--;
printf(“\na=%d”,a);
printf(“\nb=%d”,b);
}
In the above program the values in ‘a’ and ‘b’ are 5 and 4 respectively.
5) Assignment Operators:- These operators are used to assign a value or the result of an
expression to another variable. The basic assignment operator is =. Apart from this operator,
there are otther assignment operators such as +=, -=, *=, /= and %=. These operators
perform the respective operations on the variables and again store the result in the same
variable. Here, we require only one variable.
Eg: a+=5 indicates that a value of 5 is added to the variable ‘a’ and again the result is
stored in the same variable. i.e. a+=5; a=a+5;
Similarly,
a-=5; a=a-5;
a*=4; a=a*4;
a/=10; a=a/10;
a%=6; a=a%6;
The | operator gives 1 when two variables contain a 1 or 0 in their respective positions. We
get 0 when those are 0 only.
Eg:
A B A|B
0 0 0
0 1 1
1 0 1
1 1 1
The ~ operator gives 1 when it is 0 and 0 when it is 1.
Eg:
A ~A
0 1
1 0
The ‘^’ operator returns 1 only when either of the bits has 1 or 0 only, but not both, i.e., it
returns 0 when all are 0s or all are 1s in the respective positions of the variables.
Eg:
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
Example:
main(){int a,b,c;clrscr();
printf("\nEnter 2 values :");
scanf("%d%d",&a,&b);
c=a&b;
printf("\nAfter bitwise AND, c : %d",c);
c=a|b;
printf("\nAfter bitwise OR : %d",c);
c=a^b;
printf("\nAfter bitwise X-OR : %d",c);
c=~a;
printf("\nAfter negation of a : %d",c);
c=a<<1;
printf("\nLeft shift a, c : %d",c);
c=a>>1;
printf("\nRight shift a, c : %d",c);
getch();
}
8) Special operators:- C supports some special operators like Comma(,) , sizeof(), pointer
operators (& and *) and member selection operators (. and ->). Comma (,) is used to separate
the variable names in the declaration when they are of same datatype. Sizeof() is used to find
the memory occupied by a variable or a datatype.
Precedence of operators:- Each operator in C has a precedence associated with it. This
precedence is used to determine how an expression involving more than one operator is
evaluated. There are distinct levels of precedence and an operator may belong to one of these
levels. The operators at higher level of precedence are evaluated first. The operators of the same
precedence are evaluated either from ‘left to right’ or from ‘right to left’ depending on the level.
This is known as the associativity property of an operator. The following table shows the
different ranks (levels) and the associativity of the operators.
Operator Description Associativity Rank
() Function call Left to Right 1
[] Array elements reference Left to Right 1
+ Unary plus Right to Left 2
- Unary minus Right to Left 2
++ Increment operator Right to Left 2
-- Decrement operator Right to Left 2
! Logical negation Right to Left 2
~ Ones complement Right to Left 2
* Pointer reference Right to Left 2
& Address of operator Right to Left 2
Sizeof Size of an object Right to Left 2
(type) Type cast (conversion) Right to Left 2
* Multiplication Left to Right 3
/ Division Left to Right 3
% Modulus operator Left to Right 3
+ Addition Left to Right 4
- Subtraction Left to Right 4
<< Left shift Left to Right 5
>> Right shift Left to Right 5
< Less than Left to Right 6
<= Less than or equal to Left to Right 6
> Greater than Left to Right 6
>= Greater than or equal to Left to Right 6
== Equality Left to Right 7
!= Inequality Left to Right 7
& Bitwise AND Left to Right 8
^ Bitwise XOR Left to Right 9
| Bitwise OR Left to Right 10
&& Logical AND Left to Right 11
|| Logical OR Left to Right 12
?: Conditional expression Right to Left 13
=, *=, /=, %=, Assignment operators Right to Left 14
+=, -=. &=,
^=, |=
, Comma operator Left to Right 15
Type conversion:- Type conversion means converting one form of datatype to another form. In
C we have two types of type conversions. They are implicit and explicit conversion.
Implicit conversion:- C automatically converts any intermediate value to the proper type so that
the expression can be evaluated without losing any significance. This automatic conversion is
known as implicit type conversion. During evaluation it adheres to very strict rules of type
conversions. If the operands are of different types, the ‘lower’ type is automatically converted to
the ‘higher’ type before the operation proceeds. The result is of higher type.
Explicit conversion:- Sometimes, we want to force a type conversion in a way that is different
from the automatic conversion. This conversion is known as explicit conversion or type casting.
Following is the syntax for explicit conversion.
(type_name) expression;
Here, ‘type_name’ is one of the standard C datatypes. The ‘expression’ may be a constant,
variable or an expression.
Types of errors:-There are different types of errors encountered in any programming language.
There are 3 types of errors which are described below.
1) Syntactic errors:- Syntactic errors are found quickly at the time of compiling the program.
These errors occur due to the usage of wrong syntaxes for the statements.
Eg: x= a * y +b
The syntax error here is, semi colon (;) is missing at the end.
2) Runtime errors:- These errors may occur during the execution of programs even though the
program is successfully compiled without syntax errors. The most common types of runtime
errors are eg: (1) Array range out of bound (2) Divided by zero
3) Logical Errors:- These occur due to incorrect usage of the instructions in the program. These
errors are neither detected during compilation or execution nor cause any stoppage to the
program execution. They only produce incorrect outputs. When the program ends up with
incorrect outputs, the logical errors are the most probable reason. Logical errors are to be
detected by analyzing the outputs for different possible inputs that can be applied to the program.
This is considerably a difficult task.
1) If statement:- There are 4 types of ‘if’ statements used in C language. They are (a) simple if
(b) if else (c) ladder if (if else if else) and (d) nested if.
a) Simple if:-In simple if , we check an expression and when it is true, the control enters into the
‘if’ block and executes the statements in the block and then comes out of ‘if’ and executes the
statements present after the ‘if’ block. When the condition is false nothing is done and the
statements after the ‘if’ block gets executed.
Syntax for simple if:
if(expression)
{
statement 1;
statement 2;
----------
----------
statement n;
}
Pointes to remember while using conditional statement:
1) Condition should be in ( ).
2) Condition should not end with semi colon (;)
3) When there are more than one statement to be executed when the condition is true then, we
have to enclose them in { and }. If we have only one statement then there is no need of { }.
b) if else:- In this type of statement, the control checks the condition. If it is true, it executes the
statements present in the ‘if’ block otherwise it executes the statements present in the ‘else’
block.
Syntax:
if(expression)
{
statement 1;
statement 2;
----------
statement n;
}
else
{
statement 1;
statement 2;
----------
statement n;
}
/*Program to display biggest of 2 numbers*/
#include <stdio.h>
#include <conio.h>
main()
{
int a,b;
printf(“\nEnter 2 values :”);
scanf(“%d%d”,&a,&b);
if(a>b)
printf(“\n%d is bigger”,a);
else
printf(“\n%d is bigger”,b);
printf(“\nEnd of program”);
}
c) Ladder if (if else if else):- This type of statement is used to check more than one condition
when a condition is not satisfied. First, the control checks the first expression. If it is true, it
executes the statements present in the block following it and when it is false, it will check the
next expression or condition which is given in ‘else if’. If it is also false, it checks the next
condition present in next ‘else if’ and so on. If a matching condition is found, it executes the
statements in the respective block. If it does not find a match, then it executes the statements
which are present in ‘else’ block. The else block is optional.
Syntax:
if(expression 1)
{
statement 1;
statement 2;
----------
statement n;
}
else if(expression 2)
{
statement 1;
statement 2;
----------
statement n;
}
else if(expression 3)
{
statement 1;
statement 2;
----------
statement n;
}
else
{
statement 1;
statement 2;
----------
statement n;
}
c) Nested if :- Using an ‘if’ statement inside another ‘if’ statement is known as ‘nested if’. The
‘if’ statement may be any type of ‘if’ statement. The following is one of the forms of nested if.
syntax:
if(expr 1)
{
if(expr 2)
{
statement 1;
statement 2;
----------
statement n;
}
else
{
statement 1;
statement 2;
---------
statement n;
}
}
else
{
if(expr 2)
{
statement 1;
statement 2;
----------
statement n;
}
else
{
statement 1;
statement 2;
---------
statement n;
}
}
/*program to find the biggest of 3 numbers*/
#include <stdio.h>
#include <conio.h>
main()
{
int a,b,c; clrscr();
printf(“\nEnter 3 values :”);
scanf(“%d%d%d”, &a,&b,&c);
if(a>b)
{
if(a>c)
printf(“\n%d is bigger”,a);
else
printf(“\n%d is bigger”,c);
}
else
{
if(b>c)
printf(“\n%d is bigger”,b);
else
printf(“\n%d is bigger”,c);
}
getch();
}
2) Switch case:- It is also similar to ladder if, but here we cannot check the logical and relational
expression. It is used to check whether the value in the variable is matching with the case value
or not. This statement directly goes to the matching case value, executes the statements in that
case and comes out of the switch. If no case value matches, it executes the statements present in
the ‘default’ block.
Syntax:
switch(variable)
{
case value1:
statements
break;
case value2:
statements
break;
case value3:
statements
break;
case value4:
statements
break;
default :
Statements
}
If we do not use a ‘break’ statement, all the statements in all the cases will be executed whether
the case value matches or not. That is why we have to terminate each case with a ‘break
statement except the default case which is present at the end of the case. In switch, default can be
given anywhere, in such a case, we have to give a break statement in the default block.
Eg: main()
{
int no; clrscr();
printf(“\nEnter a number :”);
scanf(“%d”,&no);
switch (no)
{
case 1:
printf(“\nIt is Sunday”);
break;
case 2:
printf(“\nIt is Monday”);
break;
case 3:
printf(“\nIt is Tuesday”);
break;
case 4:
printf(“\nIt is Wednesday”);
break;
case 5:
printf(“\n It is Thursday”);
break;
case 6:
printf(“\nIt is Friday”);
break;
case 7:
printf(“\nIt is Saturday”);
break;
default :
printf(“\n Invalid choice “);
}
getch();
}
If you want to check the case values of character data type, then you have to enclose the values
in ‘single quotes’ Eg: case ‘a’: .
Looping statements:- The loops are used when we require some group of statements to be
executed repeatedly for a particular number of times. While loop, do while loop and for loop are
known as iterative loops. In C, loops are categorized into 2 types as Entry control loop and Exit
control loop. In the entry control loop, when the condition is satisfied only the statements are
executed, otherwise it will come out of the loop. The ‘while’ loop comes under ‘entry control
loop’. In the exit control loop, when the condition is satisfied or not the statements are executed
at least once. The ‘do while’ loop comes under ‘exit control loop’.
1) While Loop:- In this loop, when the condition is satisfied, the controls enters into the loop
and executes the statements inside it. After executing the statements, again it goes for checking
the condition. If the condition is true again, it enters into the loop, executes the statements there
and again checks the condition. This process goes on until give condition or expression becomes
false. When using loops, care must be taken to use a statement in the loop that makes the
condition false at some point so that control comes out of the loop. Otherwise, it becomes an
infinite loop and we have to use ‘ctrl+break’ to come out of the loop.
Syntax:
while(expression)
{
statement 1;
statement 2;
----------
statement n;
}
Syntax:
do
{
statement 1;
statement 2;
----------
statement n;
} while(expression);
/*program to display the sum of squares of numbers till the given number*/
Eg: main()
{
int n, i=1,sum=0;
clrscr();
printf(“\nEnter the number :”);
scanf(“%d”,&n);
do{
sum=sum+( i*i);
i++;
}while(i<=n);
printf(“\nSum of squares is %d”,sum);
getch(); }
3) For loop:- It is the most flexible, simple and mostly used loop. All the three, i.e.,
initialisation, condition and iteration (incrementation / decrementation) are written in a single
statement. So there will be no problem of missing any statement as may be the case with other
loops.
Syntax:-
for(initialisation; condition; iteration)
{
statement 1;
statement 2;
----------
statement n;
}
In ‘for’ loop, first initialization is done and then the condition is evaluated. If it is true, the
control enters into the loop and executes the statements in the loop. After executing the
statements in the loop, the control goes to the iteration part and then checks the condition. If the
condition is true again, it enters into the loop and executes the statements there. This process
goes on until the given condition is satisfied.
We can initialize more than one variable in for loop by separating the variables with a
comma. Similarly, we can give more than one iteration statement, in such case separate them
with comma.
We can leave the initialization part blank for loop with a semi colon when the
initialization is done before only. Similarly, it is the case with iteration also.
Unconditional Statements:-
Break:- The break statement is used to come out of the loop. When it is encountered in a loop,
the control comes out of the loop, even though the condition is satisfied.
Syntax:
break;
Continue:- It is also used in the loops. When the control encounters a continue statement, the
statements following this statement in the loop are skipped and the control goes to check for next
iteration condition.
Syntax:
continue;
Exit():- This statement when encountered in the program terminates the program. Include the
header file stdlib.h .
Syntax:
exit(0);