C Note Upto Loop
C Note Upto Loop
Page 2
Programming with C
Flowcharts
INTRODUCTION
The flowchart is a mean of visually presenting the flow of data through an information
processing systems, the operations performed within system and the sequence in which
they are performed.
A flowchart is a pictorial representation of an algorithm in which the steps are drawn, in
the form of different shapes of boxes and the logical flow indicated by inter connecting
arrows.
Meaning of a Flowchart
A flowchart is a diagrammatic representation that illustrates the sequence of operations
to be performed to get the solution of a problem. Once the flowchart is drawn, it
becomes easy to write the program in any high level language. Hence, it is correct to say
that a flowchart is a must for the better documentation of a complex program.
ADVANTAGES:
Reasons for using flowcharts as a problem-solving tool are:
Makes logic clear
Communication: flowcharts are a good way of communicating the logic of a
system to all concerned.
Using in coding, flowcharts act as a guide during the system’s analysis and
program development phase.
S.E.REDDY Page 3
Programming with C
S.E.REDDY Page 4
Programming with C
c) Only one flow line should come out or from a process symbol.
d) Only one flow line should enter a decision symbol, but two or three flow lines, one
for each possible answer, should leave the decision symbol.
S.E.REDDY Page 5
Programming with C
f) Write within standard symbols briefly. As necessary, you can use the annotation
symbol to describe data or computational steps more clearly.
Connector
S.E.REDDY Page 6
Programming with C
Example 3: Draw a flowchart to compute the final price of an item after figuring in sales
tax.
S.E.REDDY Page 7
Programming with C
INTRODUCTION
C is a general-purpose programming language initially developed by Dennis Ritchie
between 1969 and 1973 at Bell Labs. C is a robust language whose rich set of built-in
functions and operators can be used to write any complex program. C is one of the most
widely used programming languages of all time.
Origin of C
Year Language Developed By Remarks
1960 ALGOL60 International too general, too abstract, not
Committee a specific language
1963 CPL(Combined Cambridge University too difficult to learn and
Programming Language) hard to implement
1967 BCPL(Basic Combined Martin Richard, could deal only special
Programming Language) Cambridge University problem
1970 B Ken Thompson, AT & could deal only special
T Bell Laboratories problem, did not support
various data types
1972 C Dennis Ritchie, AT & T programming efficiency &
Bell Laboratories relatively good machine
efficiency & support various
data types.
C was the offshoot of the earlier languages ‘BCPL’ and ‘B’. It supports high level features
with commands like if, else, goto etc making it convenient to use. It also supports low-
level features like manipulation of bits and addressing memory location directly by using
pointers. C may be called as middle level programming language.
S.E.REDDY Page 8
Programming with C
Application Areas of C
Initially C was used to design the system software like 90% of UNIX operating
system is written in C language.
for designing application software
In writing Device Drivers.
In INTERNET protocols.
In developing translators.
In print spoolers and other utilities.
S.E.REDDY Page 9
Programming with C
Character Set
Any symbol is referred as character in C language. A character denotes any alphabets
(A,B, … Z or a,b, … z), digits (0,1,2,3,4,5,6,7,8,9) or special symbols (!@#~`% ^ &*(){} -
=+_{}[]| \”/’<>:;) used to represent information. This character set is used to form
vocabulary of C (constants, variables and keywords).
ASCII Table
33 ! exclamation 65 A 97 a
35 # number sign 67 C 99 c
42 * asterisk 74 J 106 j
44 , comma 76 L 108 l
47 / slash 79 O 111 o
48 0 zero 80 P 112 p
49 1 one 81 Q 113 q
50 2 two 82 R 114 r
51 3 three 83 S 115 s
52 4 four 84 T 116 t
53 5 five 85 U 117 u
54 6 six 86 V 118 v
55 7 seven 87 W 119 w
56 8 eight 88 X 120 x
57 9 nine 89 Y 121 y
58 : colon 90 Z 122 z
S.E.REDDY Page 10
Programming with C
C TOKENS
In a C Program, the smallest individual units are known as C -Tokens. Programs are
written using these tokens and syntax of language. There are totally six tokens. They are:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
C-Tokens
Special
Keywords Identifiers Constants Strings Operators
Symbols
Keywords:
Keywords are those words, whose meaning is already known to the C compiler i.e. they
are predefined words. The keywords cannot be used as variable names. There are only
32 keywords available in C. A keyword can’t be used as a variable name because if we
do so, we are trying to assign a new meaning to the keyword.
int struct for static
float union switch register
char typedef case extern
double enum default void
signed if break volatile
unsigned else continue sizeof
long while goto const
short do auto return
Identifiers:
Identifiers refer to the names of variable, functions and arrays. These are user-defined
names and consist of a sequence of letters and digits, with a letter as a first character.
Both uppercase and lowercase letters are permitted, although lowercase letters are
commonly used. The underscore character is also permitted in identifiers.
S.E.REDDY Page 11
Programming with C
Constants:
Constants in ‘C’ refer to fixed values that do no change during the execution of a
program. Constant is a memory location in which a value can be stored and this cannot
be altered during the execution of program. ‘C’ supports several types of constants. They
are illustrated below.
Constants
Single
Integer Real String
Character
Integer Constants:
An integer constant refers to a sequence of digits. There are three types of integers,
namely binary, decimal, octal and hexadecimal.
Binary Numbers: A Binary Number is made up of only 0s and 1s.
Example: 110100
Representation of a Binary Number
MSB Binary Digit LSB
28 27 26 25 24 23 22 21 20
256 128 64 32 16 8 4 2 1
S.E.REDDY Page 12
Programming with C
Octal Integers constant consists of any combination of digits from 0 through 7 with a 0
at the beginning. Octal is fancy for Base Eight meaning eight symbols are used to
represent all the quantities. They are 0, 1, 2, 3, 4, 5, 6, and 7. Some examples of octal
integers are 026, 0, 0347, and 0676
3 6 2 3
1536+384+16+3
1939
S.E.REDDY Page 13
Programming with C
Digits are explained as powers of 16. Consider the hexadecimal number 2DB7.
163 16 2 161 160
2 D B 7
8192+3328+176+7
11703
Real Constants :
Real Constants consists of a fractional part in their representation. Integer constants are
inadequate to represent quantities that vary continuously. These quantities are
represented by numbers containing fractional parts like 26.082.
Examples of real constants are 0.0026, -0.97, 435.29, +487.0
These numbers are shown in decimal notation, having a whole number followed by a
decimal point and the fractional part. It is possible to omit digits before the decimal point
or digits after the decimal point. That is, 215.; .95; -.71; +.5 are all valid real numbers.
A real number may also be expressed in exponential (or scientific) notation. For example,
215.65 may be written as 2.1565e2 in exponential notation, e2 means multiply by 10 2.
The general form is:
𝑚𝑎𝑛𝑡i𝑠𝑠𝑎 𝑒 𝑒𝑥𝑝𝑜𝑛𝑒𝑛𝑡
The 𝑚𝑎𝑛𝑡i𝑠𝑠𝑎 is either a real number expressed in decimal notation or an integer. The
𝑒𝑥𝑝𝑜𝑛𝑒𝑛𝑡 is an integer number with an optional plus and minus sign. The letter 𝑒
separating the mantissa and the exponent can be written in either lowercase or
uppercase. The exponent causes the decimal point to "float", this notation is said to
represent a real number in floating point form.
Examples of legal floating point constants are: 0.65e4, 12e-2, 1.5e+5, 3.18E3, -1.2E-1
White spaces are not allowed. Exponential notation is useful for representing numbers
that are either very large or very small is magnitude. E.g. 7500000000 --> 7.5e9 or
75e8.
S.E.REDDY Page 14
Programming with C
String Constants
A string constant is a sequence of character enclosed in double quotes. The characters
may be letters, numbers, special characters and blank space.
Examples are "Hello!", "1987", "WELL DONE", "5+3", "X"
Logical Constant : A logical constant can take either a true or a false as value.
In C,
Zero (0) represents false value.
Any non-zero value such as 1 represents true value.
Variables:
In C, a quantity, which may vary during the program execution, is called a variable.
Variable names are the names given to the memory locations of a computer where the
variable value is stored.
A variable is a name that is used to store data value and is allowed to vary the value
during the program execution. A variable is able to hold different values during
execution of a program, where as a constant is restricted to just one value. Variable name
S.E.REDDY Page 15
Programming with C
can be chosen by the programmer in a meaningful way so as to reflect its nature in the
program.
Length of C variable name can be upto 8 characters and some translators permit even a
higher length (32). It may take different values at different times during program
execution.
Variable names may consist of letters, digits, and underscore subjected to following
conditions:
They must begin with a letter or underscore (_), followed by any number of
letters, digits, or underscores.
Uppercase is different from lowercase, so the names total, Total, and TOTAL
specify three different variables.
The variable name shouldn’t be a keyword.
Blank spaces are not allowed.
The length should be normally 8 characters (since only the first 8 characters
treated as significant by many compilers).
The variable names are case sensitive.
The variables are defined at the beginning of the block.
For example, in the equation 2𝑥 + 3𝑦 = 10; since x and y can change, they are
𝑣𝑎𝑟i𝑎𝑏𝑙𝑒𝑠, whereas 2,3 and 10 cannot change, hence they are 𝑐𝑜𝑛𝑠𝑡𝑎𝑛𝑡𝑠. The total
equation is known as 𝑒𝑥𝑝𝑟𝑒𝑠𝑠i𝑜𝑛.
Valid variable names: Alpha, X, fyear_9899, matrix, income
DATATYPES
A C language programmer has to tell the system before-hand, the type of numbers or
characters he is using in his program. These are data types. There are many data types in
C language. A C programmer has to use appropriate data type as per his requirement.
Data type is the instruction to the compiler telling about what type of value will be
stored in a memory location and also to specify the amount of memory required for
location.
C language data types can be broadly classified as
Primary data types
Derived data types
User-defined data types
S.E.REDDY Page 16
Programming with C
A 𝑠ℎ𝑜𝑟𝑡 i𝑛𝑡 represents small integer values and requires half the space than normal
integer values. The 𝑙𝑜𝑛𝑔 𝑎𝑛𝑑 𝑢𝑛𝑠i𝑔𝑛𝑒𝑑 𝑙𝑜𝑛𝑔 i𝑛𝑡 are used to declare a longer range of
values.
Size Size
Type Range
(in Bytes) (in Bits)
i𝑛𝑡 𝑜𝑟 𝑠i𝑔𝑛𝑒𝑑 i𝑛𝑡 2 16 −32768 𝑡𝑜 32767
𝑢𝑛𝑠i𝑔𝑛𝑒𝑑 i𝑛𝑡 2 16 0 𝑡𝑜 65535
𝑠ℎ𝑜𝑟𝑡 i𝑛𝑡 𝑜𝑟
𝑠i𝑔𝑛𝑒𝑑 𝑠ℎ𝑜𝑟𝑡 i𝑛𝑡 1 8 −128 𝑡𝑜 127
To find the range of these signed data type we use the formula, −2𝑛−1 𝑡𝑜 + 2𝑛−1 − 1
To find the range of these unsigned data type we use the formula, 0 𝑡𝑜 2𝑛 − 1
S.E.REDDY Page 17
Programming with C
When the accuracy provided by a float number is not sufficient, the type 𝑑𝑜𝑢𝑏𝑙𝑒 can be
used to define the number. This is also called long float. A 𝑑𝑜𝑢𝑏𝑙𝑒 data type number uses
64 bits giving a precision of 14 digits. These are known as double precision numbers. The
double represents the same data type that float represents, but with greater precision. To
extend the precision further, we may use long double which uses 80 bits.
Size Size
Type Range
(in Bytes) (in Bits)
ƒ𝑙𝑜𝑎𝑡 4 32 3.4𝐸 − 38 𝑡𝑜 3.4𝐸 + 38
𝑑𝑜𝑢𝑏𝑙𝑒 8 64 1.7𝐸 − 308 𝑡𝑜 1.7𝐸 + 308
𝑙𝑜𝑛𝑔 𝑑𝑜𝑢𝑏𝑙𝑒 10 80 3.4𝐸 − 4932 𝑡𝑜 1.1𝐸 + 4932
Note: The size and range of Data Types vary from one machine to another. The above
specified size and range of Data Types are on a 16-bit Machine.
S.E.REDDY Page 18
Programming with C
ƒ𝑙𝑜𝑎𝑡 𝑎 = 1.5, 𝑏 = 1.99 + 2.4 ∗ 1.44;
2) The order in which we define the variables is sometimes important sometimes not.
i𝑛𝑡 i = 10, j = 35; is same as i𝑛𝑡 j = 35, i = 10;
However, ƒ𝑙𝑜𝑎𝑡 𝑎 = 1.5, 𝑏 = 𝑎 + 3.1; is not same as ƒ𝑙𝑜𝑎𝑡 𝑏 = 𝑎 + 3.1, 𝑎 = 1.5;
(as we are trying to use a before defining it).
3) The following statements would work
i𝑛𝑡 𝑎, 𝑏, 𝑐, 𝑑;
𝑎 = 𝑏 = 𝑐 = 10;
& the following statements would not work
i𝑛𝑡 𝑎 = 𝑏 = 𝑐 = 𝑑 = 10;
as we are trying to use b (to assign to a) before defining it.
Declaring variable as constant
The value of certain variables might remain constant during the execution of a program
which can be achieved with the qualifier const at the time of initialization.
E.g. 𝑐𝑜𝑛𝑠𝑡 i𝑛𝑡 𝑐𝑙𝑎𝑠𝑠_𝑠iz𝑒 = 60;
The keyword const tells the compiler that the value of the int variable class_size must not
be modified by the program.
Declaring variable as volatile
Another qualifier volatile can be used to tell explicitly the compiler that a variable's value
may be changed at any time by external sources (from outside the program).
E.g. 𝑣𝑜𝑙𝑎𝑡i𝑙𝑒 i𝑛𝑡 𝑑𝑎𝑡𝑒;
The value of date may be altered by some external factors. When we declare a variable
as volatile, the compiler will examine the value of the variable each time whether any
external alteration has changed the value and can be modified by its own program.
If the value must not be modified by the program while it may be altered by some other
process, then we may declare the value as both const and volatile as
𝑣𝑜𝑙𝑎𝑡i𝑙𝑒 𝑐𝑜𝑛𝑠𝑡 i𝑛𝑡 𝑙𝑜𝑐𝑎𝑡i𝑜𝑛 = 100;
Format Codes:
Format codes are coding characters used to represent the data types. They are needed
must to print the output in a formatted manner. It is also called control string, or format
specifiers or format strings.
Code Description
%c Single Character
%d Decimal Integer
%i Decimal, Hexadecimal or Octal Integer
%h Short Integer
S.E.REDDY Page 19
Programming with C
Documentation section
This section consists of a set of comment lines giving the name of the programmer,
name of the program and other details, which the programmer would like to use
later. It starts with ‘\*’ and ends with ‘*/’.
Link section
This section provides instructions to the compiler to link functions from system
library. It is as “#include<stdio.h>”.
Definition section
This section defines all the symbolic constants.
Global Declaration Section:
There are some variables that are used in more than one function, such variables
are called global variables & are declared in the global declaration section.
main() function Section:
Every C program must have one ‘main’ function section. This section contains two
parts i.e. declaration part and executable part. The declaration part declares all the
S.E.REDDY Page 20
Programming with C
variables used in the executable part. These two parts must appear between
opening and closing braces {}.
Declaration & Execution Parts:
The program execution begins at opening brace and ends at the closing brace. All
statements in the declaration and executable part ends with semicolon (;).
Sub Program functions:
The sub program functions contain all the user-defined functions that are called in
the main function.
User defined functions are generally placed immediately after the main function.
The following are the rules to write C Programs:
1. All C statements must end with semicolon(;).
2. C is case-sensitive, i.e., upper and lower case characters are different. Generally, the
statements are typed in lower case.
3. A C statement can be written in one line or it can split into multiple lines.
4. Every C program is a collection of one or more functions. There must be only
function with the name as main as program execution starts and ends with main()
function.
5. The function's body must be enclosed within braces. Braces must always match
upon pairs i.e., every opening brace { must have a matching closing brace } to avoid
confusions and eliminate errors.
6. To make programs easily understandable, comments can be added. Comments
cannot be nested. For Example, /*Welcome to ‘C’, /*Programming*/*/ (this cannot
be used). A comment can split into more than one line.
Execution of C Program in TurboC:
The following are the steps to be followed in writing and running a C program:
a) Creation of Source Program:
Create a C program file in various C compilers that are available under MS-DOS,
Turbo C Editor etc.
b) Compilation of the Program:
Turbo C compiler is user friendly and provides integrated program development
environment. Thus, selecting key combination can do compilation. That means
press Alt+F9 for compilation.
c) Program Execution:
In Turbo C environment, the RUN option will do the compilation and execution
of a program. Press Ctrl+F9 for execution.
d) Result Display:
In Turbo C environment, the output of the executed program can be viewed.
Press Alt+F5 to view the output.
S.E.REDDY Page 21
Programming with C
I/O Functions
All most all the programming languages are designed to provide I/O activity. Input refers
to the process through which data is supplied to the system. On the other hand, output
refers to the provision which is made available by the computer to the user.
In C the input/output functions takes two forms they are: (1) Formatted (2) Unformatted
Syntax:
printf("<message>");
printf("<control string>", argument list separated with commas);
S.E.REDDY Page 22
Programming with C
Example:
printf("This is C statement");
printf("The number is % d", a);
printf("The number % d is equal to % d", 10,10);
printf("The number % d is not equal to % d", x,y);
scanf()
This is an input statement. Data can be stored in the variables after accepting the values
from the user through the keyword, by using a standard library function for input
operation. This allows a program to get user input from the keyboard. This means that
the program gets input values for variables from users.
Syntax:
scanf("<format code>",list of address of variables separated by commas);
Example:
scanf("% d", &a);
scanf("% d % c % f", &a, &b, &c);
S.E.REDDY Page 23
Programming with C
Output:
Name: Sachin Tendulkar
Qualification: Degree
Address: Mumbai
Work: Cricket Player
4. To accept the values of int, float, char data types and display them.
/*Program to accept values of int, char, float data types
Display them in the order of reading*/
#include<stdio.h>
#include<conio.h>
main()
{
char x;
int num;
float j;
clrscr();
/*Accept the values for data types from user*/
printf("Enter Character: ");
scanf("%c",&x);
printf("Enter Integer Value: ");
scanf("%d",&num);
printf("Enter Float Value: ");
scanf("%f",&j);
/*Display the accepted values*/
printf("Integer=%d\tFloat Value=%f\tCharacter=%c",num,j,x);
}
Output:
Enter Character: a (Enter)
Enter Integer Value: 20 (Enter)
S.E.REDDY Page 24
Programming with C
Enter Float Value: 100 (Enter)
Integer=20 Float Value=100.0 Character=a
Example:
char c; c = getchar(); /*reads a single character*/
(2) getch() & getche()
These functions read any alphanumeric characters from the standard input device.
getch() is a standard library function used for single character input, but it does
not wait for enter key and neither does it display the character on the screen.
Syntax: character_variable = getch();
getche() is a standard library functions used for single character input same as
getch() function. It also does not wait for enter key but echoes on the screen. It
can be used for getting the result directly on the screen.
Syntax: character_variable = getche();
Example:
char c; c = getche(); /*Displays the character entered on screen*/
c = getch(); /*does not display the character*/
(3) putchar()
It transmits a single character to a standard output device. The character being
transmitted will normally be represented as a character type variable. It must be
expressed as a parameter to the function, enclosed in parentheses, followed by the
word putchar.
S.E.REDDY Page 25
Programming with C
Syntax: putchar(character_variable/expr);
Example:
char c; c = getchar(); putchar(c); /*prints the accepted character*/
(4) putch()
This function prints any alphanumeric character taken by the standard input device.
Syntax: putch(character_variable/expr);
String I/O
In order to read and write string of characters the functions gets() and puts() are used.
gets() function reads the string and puts() function takes the string as argument and writes
on the screen.
S.E.REDDY Page 26
Operators in C
An operator is a symbol that tells the computer to perform certain mathematical or
logical manipulations (calculations). C is extremely rich in built-in operators. Operators
are used in program to manipulate data and variables. Some operators require two
operands, while others act upon only one operand. C operators are classified as follows:
1) Arithmetic Operators
2) Relational Operators
3) Logical Operators
4) Assignment Operator
5) Increment & Decrement Operator
6) Conditional Operator
7) Bit wise Operators
8) Special Operators
Integer division truncates any fractional part. Modulo division produces the remainder of
integer division.
E.g. sum = a+b; product = a*b; difference = a-b; quotient = a/b; remainder = a% b;
In the example, a & b are variables ad are known as operands.
Note: The modulo division operator (% ) can't be used on float and double datatypes.
S.E.REDDY Page 27
Programming with C
Relational Operators: Relational Operators are symbols that are used to test the
relationship between 2 variables or between variable and a constant. We often compare
two quantities & depending upon this relation take certain decisions.
Operator Meaning
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
A simple relational expression contains only one relational operator and takes the
following form:
𝑎𝑒1 𝑟𝑒𝑙𝑎𝑡i𝑜𝑛𝑎𝑙 𝑜𝑝𝑒𝑟𝑎𝑡𝑜𝑟 𝑎𝑒2
Here ae1 and ae2 are arithmetic expressions, which may be simple constants, variables or
combination of them. The value of a relational expression is either one or zero. It is one
if the specified relation is true and zero if the relation is false.
E.g. 10 < 20 is true, 20 < 10 is false.
These expressions are used in decision statements such as if and while to decide the
course of action of a running program.
The logical operator && and || are used when we want to test more than one condition
& make decisions.
E.g. a>b && x == 10
An expression of this kind will combine two or more relational expressions is
termed as logical expression or compound relational expression. The logical expression
given below is true if a>b is true and x == 10 is true. If either or both of them are false ,
the expression is false.
TRUTH TABLE
op-1 op-2 op-1 && op-2 op-1 || op-2
1 1 1 1
1 0 0 1
0 1 0 1
0 0 0 0
S.E.REDDY Page 28
Programming with C
Logical NOT is used to reverse the truth value of its operand. (i.e. NOT F -> T)
An expression containing a logical operator is termed as a logical expression. A logical
expression also yields a value of one or zero.
Assignment Operator: (=)
These are used to assign the result of an expression to a variable. C has a set of shorthand
assignment operators of the form:
𝑣 𝑜𝑝 = 𝑒𝑥𝑝;
where v is a variable, exp is an expression and op is a C arithmetic operator. The
operator op= is known as shorthand assignment operator.
The above expression can be equivalent to 𝑣 = 𝑣 𝑜𝑝 (𝑒𝑥𝑝);
E.g. x += y+1; -> x = x + (y+1);
Statement with simple Statement with shorthand operator
assignment operator
a = a+1 a += 1
a = a-1 a -= 1
a = a*(n+1) a *= (n+1)
a = a/(n+1) a /= (n+1)
a = a%b a %= b
The use of shorthand assignment operators has 3 advantages:
1. What appears on the left-hand side need not be repeated and therefore it
becomes easier to write.
2. The statement is more concise and easier to read.
3. The statement is more efficient.
Increment & Decrement Operators:
C has two very useful operators not generally found in other languages. These are
increment and decrement operators: ++ and --.
The operator ++ adds 1 to the operand, while -- subtracts 1.
Pre/Post Increment/Decrement Operators
PRE means do the operation first followed by any assignment operation. POST means do
the operation after any assignment operation.
++m; or m++; | --m; or m--;
++m; is equivalent to m=m+1; (or m+=1;) / --m; is equivalent to m=m-1; (or m-=1;)
While m++ and ++m mean the same when they form statements inde pendently, they
behave differently when they are used in expressions on the right-hand side of an
assignment statement.
E.g. (i) m = 5;
y = ++m; This statement results y and m = 6
S.E.REDDY Page 29
Programming with C
Since the prefix operator first adds 1 to the operand and then the result is assigned
to the variable on left.
(ii) m = 5;
y = m++; This statement results y = 5 and m = 6
Since the postfix operator first assigns the value to the variable on left then
increments the operand.
We use increment and decrement statements in for and while loops extensively.
Conditional Operator:
A ternary operator pair "? :" is available in C to construct conditional expressions of the
form:
𝑒𝑥𝑝1 ? 𝑒𝑥𝑝2 ∶ 𝑒𝑥𝑝3;
where exp1, exp2 and exp3 are expressions.
There operator ?: works as follows: exp1 is evaluated first. If it is true, then exp2 is
evaluated and becomes the value of the expression. If exp1 is false, exp3 is evaluated and
its value becomes the value of the expression.
E.g. a=10;
b=15;
x=(a>b) ? a : b; In this, the x will be assigned with the value of b.
Bitwise Operators:
In C, operations on bits at individual levels can be carried out using Bitwise operators.
These are used for manipulation of data at bit level. These operators are used for testing
the bits, or shifting them right or left. These may not be applied to float or double.
Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
~ One's complement
The bitwise AND does the logical AND of the bits in each position of a number in its
binary form.
00111100&
00001101
0 0 0 0 1 1 0 0 : Result
S.E.REDDY Page 30
Programming with C
The bitwise OR does the logical OR of the bits in each position of a number in its binary
form.
001 11100|
00001101
0 0 1 1 1 1 0 1 : Result
The bitwise exclusive OR performs a logical EX-OR function or in simple term adds the
two bits discarding the carry. Thus result is zero only when we have 2 zeroes or 2 ones
to perform on.
00111100^
00001101
0 0 1 1 0 0 0 1 : Result
The one's complement (~) or the bitwise complement gets us the complement of a given
number. Thus we get the bits inverted, for every bit 1 the result is bit 0 and conversely
for every bit 0 we have a bit 1.
Bit One's Complement
0 1
1 0
~ 0 0 1 1 1 1 0 0 --> 1 1 0 0 0 0 1 1
Two shift operators shift the bits in an integer variable by a specified number of positions.
The << operator shifts bits to the left, and the >> operator shifts bits to the right.
The syntax for these binary operators is x << n and x >> n.
Each operator shifts the bits in x by n positions in the specified direction.
For a right shift, zeros are placed in the n high-order bits of the variable;
For a left shift, zeros are placed in the n low-order bits of the variable.
Special Operators:
C supports some operators of interest such as comma operator, sizeof operator, pointer
operators (& and *) and member selection operators (. and ->).
S.E.REDDY Page 31
Programming with C
The comma operator can be used to link the related expressions together. A comma-
linked: list of expressions are evaluated left to right and the value of right-most exp is the
value of combined expression.
E.g. value = (x=10,y=5,x+y);
First 10 is assigned to x then 5 is assigned to y & finally x + y i .e. which 15 is
assigned to value .
Since comma operator has lowest precedence of all operators, the parentheses are
necessary.
In for loops: for(n=1,m=10;n<=m;n++,m++)
In while loops: while(c=getchar(), c!='10')
Exchanging values: t=x, x=y, y=t;
The sizeof is a compile time operator and when used with an operand, it returns the
number of bytes the operand occupies. The operand may be a variable, a constant or a
data type qualifier.
E.g. m = sizeof(sum);
n = sizeof(long int);
k = sizeof(235L);
This operator is normally used to determine the lengths of arrays and structures when
their sizes are not known to the programmer. It is also used to allocate memory space
dynamically to variables during execution of a program.
Precedence of Arithmetic operators
An arithmetic expression without parentheses will be evaluated from left to right using
the rules of precedence of operators. There are two distinct priority levels of arithmetic
operators in C:
High Priority *, /, %
Low Priority +, -
The basic evaluation procedure includes two left-to-right passes through the expression.
During the first pass, the high priority operators (if any) are applied as they are
encountered. During the second pass, the low priority operators (if any) are applied as
they are encountered.
E.g. Consider a=9, b=12 and c=3
x = a - b/3+c*2-1;
1> x = 9 - 12/3 + 3*2-1
2> x = 9 - 4 + 3*2-1
3> x = 9 - 4 + 6-1
4> x = 5 + 6 - 1
5> x = 11 - 1 6> x = 10
S.E.REDDY Page 32
Programming with C
y = a - b/(3+c)*(2-1);
1> y = 9 - 12/6 * (2-1)
2> y = 9 - 12/6 * 1
3> y = 9 - 2 * 1
4> y = 9 - 2 5> y = 7
z = a - (b/(3+c)*2)-1;
1> z = 9 - (12/(3+3) * 2) - 1
2> z = 9 - (12/6 * 2) - 1
3> z = 9 - (2 * 2) - 1
4> z = 9 - 4 - 1
5> z = 5-1 6> z = 4
S.E.REDDY Page 33
Programming with C
ARITHMETIC EXPRESSIONS
An arithmetic expression is a combination of variables, constants and operators arranged
as per the syntax of the language. C can handle any complex mathematical expressions.
Arithmetic Instruction
A C arithmetic instruction consists of a variable name on the left hand side of = and
variable names and constants on the right hand side of =. The variables and constants
appearing on the right hand side of = are connected by arithmetic operators like +, -, *,
/, and % .
𝑣𝑎𝑟i𝑎𝑏𝑙𝑒 − 𝑛𝑎𝑚𝑒 = 𝑒𝗑𝑝𝑟𝑒𝑠𝑠i𝑜𝑛 [𝑜𝑟] 𝑣𝑎𝑙𝑢𝑒;
E.g. int a;
a=3200;
float kot, deta, alpha=9.2, beta=3.1256, gamma=100.0;
kot = 0.0056;
deta = alpha*beta/gamma + 3.2 * 2/5;
Here 2,5 and 3200 are integer constants and 3.2 and 0.0056 are real constants
kot, deta, alpha, beta and gamma are real variables.
The variables and constants together are called operands that are operated upon by the
arithmetic operators and the result is assigned using the assignment operator, to the
variable on the left-hand side.
C arithmetic instructions are of 3 types:
(1) Integer mode: This is an arithmetic instruction in which all operands are either
integer variables or integer constants.
E.g. int i, king, issac, noteit;
i = i+1;
king = issac*234 + noteit-7689;
(2) Real mode: This is an arithmetic instruction in which all operands are either real
constants or real variables.
E.g. float q, a, si, princ, anoy, roi;
q = a + 23.123/4.5*0.344;
si = princ*anoy*roi/100.0;
(3) Mixed mode: This is an arithmetic instruction in which some of the operands are
integers and some of the operands are real.
E.g. float si, princ, anoy, roi, avg;
int a, b, c, num;
q = a + 23.123/4.5*0.344;
si = princ*anoy*roi/100.0;
avg = (a+b+c+num)/4;
S.E.REDDY Page 34
Programming with C
The execution of an arithmetic instruction: Firstly, the right hand side is evaluated using
constants and the numerical values stored in the variable names. This value is then
assigned to the variable on the left-hand side.
Guidelines for Arithmetic Inst ructions
a) C allows only one variable on left hand side of =.
i.e., x = k + l; is legal whereas k + l = x; is illegal.
b) An arithmetic instruction is often used for storing character constants in character
variables.
E.g. char a,b,d;
a = 'F';
b = 'G';
d = '+';
When we do this the ASCII values of the characters are stored in the variables.
ASCII values are used to represent any character in memory.
c) Arithmetic operations can be performed on ints, floats and chars.
char x,y;
int z; x='a';
y='b';
z=x+y;
d) No operator is assumed to be present. It must be written explicitly.
E.g. a = c.d.b(xy) usual arithmetic statement
b = c*d*b*(x*y); c statement
e) Unlike other high level languages, there is no operator for performing
exponentiation operation.
E.g. a = 3**2;
b = 3^ 2; statements are valid.
Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
𝑣𝑎𝑟i𝑎𝑏𝑙𝑒 = 𝑒𝑥𝑝𝑟𝑒𝑠𝑠i𝑜𝑛;
Algebraic Expression C expression
axb-c a*b-c
(m+n)(x+y) (m+n)*(x+y)
𝑎𝑏
a*b/c
𝑐
3x2 + 2x + 1 3*x*x + 2*x + 1
𝑥
𝑦
+ 𝑐 x/y + c
S.E.REDDY Page 35
Programming with C - Lab
Variable is any valid C variable name. When the statement is encountered, the expression
is evaluated first and the result then replaces the previous value of the variable on the
left-hand side. All variables used in the expression must be assigned values before
evaluation is attempted.
E.g. x = a*b-c;
y = b/c*a;
z = a-b/c + d;
The blank space around an operator is optional and adds only to improve readability.
When these statements are used in a program, the variables a, b, c and d must be defined
before they are used in the expressions.
Rules for evaluation of expression
1. Parenthesized sub expression from left to right is evaluated.
2. If parentheses are nested, the evaluation begins with the innermost sub-expression.
3. The precedence rule is applied in determining the order of application of
operators in evaluating sub-expressions.
4. The associativity rule is applied when 2 or more operators of the same precedence
level appear in a sub-expression.
5. Arithmetic expressions are evaluated from left to right using the rules of
precedence.
6. When parentheses are used, the expressions within parentheses assume highest
priority.
Type Casting
Typecasting concept in C language is used to modify a variable from one date type to
another data type. New data type should be mentioned before the variable name or
value in brackets which to be typecast.
C type casting example program:
In the below C program, 7/5 alone will produce integer value as 1.
So, type cast is done before division to retain float value (1.4).
#include <stdio.h>
int main ()
{
float x;
x = (float) 7/5;
printf("%f",x);
}
Output: 1.400000
Note:
It is best practice to convert lower data type to higher data type to avoid data
loss.
S.E.REDDY Page 36
Programming with C - Lab
Data will be truncated when higher data type is converted to lower. For example,
if float is converted to int, data which is present after decimal point will be lost.
“math.h” functions
Mathematics is relatively straightforward library to use again. You must
#include<math.h> and must remember to link in the math library at compilation:
cc mathprog.c -o mathprog -lm
Math Functions
S.no Function Description Example
floor of 5.100000 is 5.000000
This function returns the nearest integer
floor of 5.900000 is 5.000000
1 floor() which is less than or equal to the
floor of -5.400000 is -6.000000
argument passed to this function.
floor of -6.900000 is -7.000000
This function returns the nearest integer
value of the float/double/long
double argument passed to this
function. If decimal value is from “.1 to round of 5.400000 is 5.000000
2 round()
.5″, it returns integer value less than the round of 5.600000 is 6.000000
argument. If decimal value is from “.6 to
.9″, it returns the integer value greater
than the argument.
This function returns nearest integer ceil of 5.400000 is 6.000000
3 ceil() value which is greater than or equal ceil of 5.600000 is 6.000000
to the argument passed to this function. Ceil of 8.33=9
S.E.REDDY Page 37
Programming with C - Lab
Math Constants
The math.h library defines many (often neglected) constants. It is always advisable to use
these definitions:
⚫ HUGE - The maximum value of a single -precision floating-point number.
⚫ M_E - The base of natural logarithms (e).
⚫ M_LOG2E - The base-2 logarithm of e.
⚫ M_LOG10E - The base-10 logarithm of e.
⚫ M_LN2 - The natural logarithm of 2.
⚫ M_LN10 - The natural logarithm of 10.
⚫ M_PI - π.
⚫ M_PI_2 - π/2.
⚫ M_PI_4 - π/4.
⚫ M_1_PI - 1/π.
⚫ M_2_PI - 2/π.
⚫ M_2_SQRTPI - 2/√𝜋.
⚫ M_SQRT2 - The positive square root of 2.
⚫ M_SQRT1_2 - The positive square root of 1/2.
⚫ MAXFLOAT - The maximum value of a non -infinite single- precision floating point
number.
⚫ HUGE_VAL - positive infinity.
S.E.REDDY Page 38
Programming with C
Sample C Programs
Input two numbers and compute all arithmetic operations
/*Program to accept 2 numbers and compute all arithmetic operations*/
#include<stdio.h>
#include<conio.h>
main()
{
int num1,num2;
clrscr();
/*Accept two numbers from user*/
printf("Enter first number: ");
scanf("%d",&num1);
printf("Enter second number: ");
scanf("%d",&num2);
/*Display values for arithmetic operators*/
printf("Sum of 2 numbers: %d",num1+num2);
printf("\nDifference of 2 numbers: %d", num1-num2);
printf("\nProduct of 2 numbers: %d", num1*num2);
printf("\nQuotient for %d/%d: %d", num1,num2,num1/num2);
printf("\nRemainder for %d/%d: %d", num1,num2,num1%num2);
}
Output:
Enter first number: 52 (Enter)
Enter second number: 12 (Enter)
Sum of 2 numbers: 64
Difference of 2 numbers: 40
Product of 2 numbers: 624
Quotient for 52/12: 4
Remainder for 52/12: 4
Input radius, compute area, diameter, & circumference of the circle and display them.
/*Program to accept radius & calculate area, diameter and
circumference of circle*/
#include<stdio.h>
#include<conio.h>
main()
{
/*Declare the variables*/
int radius,diameter;
float area,circumference;
const float PI = 3.14; /*set variable PI to constant*/
clrscr();
/*Accept the value of radius*/
printf("Enter circle radius: ");
S.E.REDDY Page 39
Programming with C
scanf("%d",&radius);
/*Compute the area, diameter and circumference*/
diameter = 2*radius;
area = PI*radius*radius;
circumference = 2*PI*radius;
/*Display the results*/
printf("Area of circle = %.2f",area);
printf("\nDiameter of circle = %d",diameter);
printf("\nCircumference of circle = %.2f",circumference);
getch();
}
Output:
Enter circle radius: 5 (Enter)
Area of circle = 78.50
Diameter of circle = 10
Circumference of circle = 31.40
S.E.REDDY Page 40
Programming with C
Program for swapping the values of two variables without using third variable
/*Program to accept two numbers & swap the values*/
#include<stdio.h>
#include<conio.h>
main()
{
/*Declare the variables*/
int num1,num2;
clrscr();
printf("Enter first number: ");
scanf("%d",&num1);
printf("Enter second number: ");
scanf("%d",&num2);
printf("Numbers before swapping: %d %d",num1,num2);
/*swapping the values of variables*/
num1 = num1 + num2;
num2 = num1 – num2;
num1 = num1 – num2;
printf("Numbers after swapping: %d %d",num1,num2);
getch();
}
Output:
Enter first number: 6
Enter second number: 5
Numbers before swapping: 6 5
Numbers after swapping: 5 6
Program to calculate total marks and percentage of a student for 5 subjects where marks
of each subject should be greater than minimum pass marks (Ex: 35).
/*Program to accept marks and obtain total and percentage of marks*/
#include<stdio.h>
#include<conio.h>
main()
{
int sub1,sub2,sub3,sub4,sub5,sum;
long int studno;
float total=500,percentage;
clrscr();
printf("Enter Student Number: ");
scanf("%ld",&studno);
printf("Enter SUBJECT1 marks: ");
scanf("%d",&sub1);
printf("Enter SUBJECT2 marks: ");
scanf("%d",&sub2);
S.E.REDDY Page 41
Programming with C
printf("Enter SUBJECT3 marks: ");
scanf("%d",&sub3);
printf("Enter SUBJECT4 marks: ");
scanf("%d",&sub4);
printf("Enter SUBJECT5 marks: ");
scanf("%d",&sub5);
sum=sub1+sub2+sub3+sub4+sub5;
percentage=(sum/total)*100;
printf("=============RESULT=============\n");
printf("STUDENT NUMBER: %ld",studno);
printf("\nTOTAL MARKS OBTAINED FOR 500: %d",sum);
printf("\nPERCENTAGE: %.2f",percentage);
getch();
}
Output:
Enter Student Number: 1220610113
Enter SUBJECT1 marks: 90
Enter SUBJECT2 marks: 91
Enter SUBJECT3 marks: 95
Enter SUBJECT4 marks: 93
Enter SUBJECT5 marks: 89
=============RESULT=============
STUDENT NUMBER: 1220610113
TOTAL MARKS OBTAINED FOR 500: 458
PERCENTAGE: 91.60
S.E.REDDY Page 42
Programming with C
test
expression? False
True
Two-way Branching
S.E.REDDY Page 43
Programming with C
S.E.REDDY Page 44
Programming with C
Output:
(1) Enter student marks: 55
Student Passed
If-Else Statement
The if-else statement is an extension of the ‘simple if’ statement. The general form is
Syntax:
if(test_expression)
{
true-block-statements;
}
else
{
false-block-statements;
}
statement_x;
S.E.REDDY Page 45
Programming with C
Output:
(1) Enter number: 53
53 is odd number
(2) Enter student marks: 42
42 is even number
S.E.REDDY Page 46
Programming with C - Lab
S.E.REDDY Page 47
Programming with C
getch();
}
Output:
Enter number: 5 6 7
7 is largest
Else If Ladder
There is another way of putting if’s together when multipath decisions are involved. A
multipath decision is a chain of if’s in which the statement associated with each else is an
if. It takes the following general form:
Syntax:
if(condition1)
statement-1;
else if(condition-2)
statement-2;
else if(condition-3)
statement-3;
...
...
...
else if(condition-n)
statement-n;
else
default-statement;
statement-x;
S.E.REDDY Page 48
Programming with C
The switch test or checks the values of given variable (or expression) against a list of case
values and when a match is found a block of statements associated with that case is
executed. The switch makes one selection when there are several choices to be made.
The expression is an integer expression or characters. Value-1, value-2, ... are constants or
constant expressions and are known as case labels. Each of these values should be unique
within a switch statement.
Block-1, block-2, ... are statements lists and may contain 0 or more statements. There is
no need to put braces ({ }) around these blocks. Case labels end with a colon(:).
When a switch is executed the value of the expression is compared against the value
(value-1, value-2, ...). If a case is found whose value of expression then block of
statements that follows the case are executed.
The break statement at the end of each block signals the end of a particular case and
causes an exit from the switch statement, transferring the control to the statement-x
following the switch statement.
The default is an optional case, when present, it will be executed if the value of the
expression does not match with any of the case values.
S.E.REDDY Page 50
Programming with C
If not present, no action takes place and if all matches fail; the control goes to the
statement-x.
S.E.REDDY Page 51
Programming with C
case 6: printf("Six");
break;
case 7: printf("Seven");
break;
case 8: printf("Eight");
break;
case 9: printf("Nine");
break;
default: printf("More than 9");
}
getch();
}
Output:
Enter a number (0-9): 3
Three
Enter a number (0-9): 10
More than 9
S.E.REDDY Page 52
Programming with C
Pseudo code is an artificial and informal language that helps programmers develop
algorithms. Pseudo code is a "text-based" detail (algorithmic) design tool. It is an
algorithm written in English like language.
Pseudo-code Language Constructions :
Computation/Assignment
set the value of "variable" to :"arithmetic expression" or
"variable" equals "expression"
Input/Output
get/read "variable", "variable", ...
display "variable", "variable", ...
Conditional (dot notation used for numbering subordinate statements)
6. if "condition"
6.1 (subordinate) statement 1
6.2 etc ...
7. else
7.1 (subordinate) statement 2
7.2 etc ...
Example : Write a pseudo-code to compute the final price of an item after figuring
in sales tax.
Step 1. Begin
Step 2. get price_of_item
Step 3. get sales_tax_rate
Step 4. Set sales_tax to price_of_item times sales_tax_rate
Step 5. Set final_price to price_of_item plus sales_tax
Step 6. display final_price
Step 7. End.
Sample C Programs
1. To check whether number is +ve, -ve or zero
/*Program to check number is positive, negative or zero*/
#include<stdio.h>
#include<conio.h>
main()
{
int n;
clrscr();
printf("Enter a number: ");
scanf("%d",&n);
if(n>0)
printf("Number is Positive");
if(n<0)
S.E.REDDY Page 54
Programming with C
printf("Number is Negative");
if(n==0)
printf("Number is Zero");
}
Output:
Enter a number: -2
Number is Negative
Enter a number: 0
Number is Zero
Enter a number: 6
Number is Positive
S.E.REDDY Page 55
Programming with C
else
printf("The character %c is a consonant",x);
getch();
}
Output:
Enter letter: p
The character p is a consonant
Enter letter: a
The character a is a vowel
Enter a Number: 32
Invalid Number
S.E.REDDY Page 56
Programming with C
#include<conio.h>
main()
{
int initial,final,consumed;
float total;
clrscr();
printf("Initial & Final Readings: ");
scanf("%d %d",&initial,&final);
consumed = final-initial;
if(consumed>500)
total=consumed*5.50;
else if(consumed>=200 && consumed<=500)
total=consumed*3.50;
else if(consumed>=100 && consumed<=199)
total=consumed*2.50;
else if(consumed<100)
total=consumed*1.50;
printf("Total bill for %d units is %f",consumed,total);
getch();
}
Output:
Initial & Final Readings: 1200 1500
Total bill for 300 units is 1050.000000
S.E.REDDY Page 57
Programming with C
getch();
}
Output:
Enter character: *
Special Symbol
Enter character: T
Capital letter
Enter character: a
Small letter
Enter character: 6
Digit
Output:
Enter Character: a
Character a is Vowel
S.E.REDDY Page 58
Programming with C
Enter Character: B
Character B is Consonant
S.E.REDDY Page 59
GOTO Statement
C supports the goto statement to branch unconditionally from one point to another in
the program. Although it may not be essential to use the goto statement in a highly
structured language like C, there may be occasions when the use of goto might be
desirable.
The goto requires a label in order to identify the place where the branch is to be made. A
label is any valid variable name, and must be followed by colon. The label is placed
immediately before the statement where the control is to be transferred.
The general forms of goto and label statements are shown below:
goto label; label;
…. statement;
…. ….
…. ….
label; ….
statement; goto label;
Forward Jump Backward Jump
The label can be anywhere in the program either before or after the goto label;
statement. During running of a program when a statement like goto begin; is met, the
flow of control will jump to the statement immediately following the label begin. This
happens unconditionally.
Example: To print Multiplication Table
/*Program to print Multiplication Table*/
#include<stdio.h>
#include<conio.h>
main()
{
int a,i=1;
clrscr();
printf("Enter the value of a: ");
S.E.REDDY Page 60
Programming with C - Lab
scanf("%d",&a);
printf("\nMultiplication Table for %d\n",a);
printf(" \n");
start:
printf("%d x %d = %d\n",a,i,a*i);
i=i+1;
if(i<=10)
goto start;
getch();
}
Output:
Enter the value of a: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Advantage:
Using goto statement you can alter the normal sequence of the program execution so it
gives the power to jump to any part of program.
Disadvantages:
It is always recommended not to use goto statement as this reduces the readability of the
program. It becomes difficult to trace the control flow of a program, making the
program logic complex to understand .Using goto statement is considered as poor
programming practice. Any program written in C language can be written without the
use of goto statement. So try to avoid goto statement as possible as you can.
Looping
Loop is a mechanism through which you repeatedly execute a set of statements. In
looping, a sequence of statements is executed until some condition for termination of the
loop is satisfied.
S.E.REDDY Page 61
Programming with C - Lab
A program loop therefore consists of two segments, one the body of the loop & other
the control statement. The control statement tests certain conditions and then directs the
repeated execution of statements contained in body of the loop.
Depending on the position of the control statement in the loop, a control structure may
be classified either as entry-controlled loop or exit-controlled loop.
□ In entry-controlled loop , the control conditions are tested before start of the execution. If
conditions are not satisfied, then body of the loop will not be executed.
□ In exit-controlled loop , the test is performed at the end of the body of the loop and
therefore the body is executed unconditionally for the first time.
The test conditions should be carefully stated in order to perform the desired number of
loop executions. It is assumed that the test condition will eventually transfer the control
out of the loop. In case, due to some reason it does not do so, the control sets up an
infinite loop and the body is executed over and over again.
A looping process, in general, would include the following four steps:
1. Setting & Initialization of a counter
2. Execution of the statements in the loop
3. Test for a specified condition for execution of the loop
4. Updating the counter
The test may be either to determine whether the loop has been repeated the specified
number of times or to determine whether a particular condition has been met.
The C language provides the following loop constructs:
(a) while statement
(b) do..while statement
(c) for statement
S.E.REDDY Page 62
Programming with C - Lab
S.E.REDDY Page 63
Programming with C - Lab
printf("\n%d",i); 9
i++; 10
}
getch();
}
S.E.REDDY Page 64
Programming with C - Lab
Enter a number (0 to stop): 98
Enter a number (0 to stop): 0
Largest number is 98
Braces { } are must for do…while. And we can have any number of statements between
braces (body of the loop).
□ Since the test_condition is evaluated at bottom of the loop, the do…while construct
provides an exit-controlled loop and therefore the body of loop is always executed
at least once.
Example 1: To calculate sum of 10 natural numbers.
/*Calculate sum of 10 natural numbers*/
#include<stdio.h>
#include<conio.h>
main()
{
int i=1,sum=0;
clrscr();
do
{
sum + = i;
i++;
}
while(i<=10);
printf("\nThe sum of 10 natural numbers is: %d",sum);
getch();
}
S.E.REDDY Page 65
Programming with C - Lab
Output:
The sum of 10 natural numbers is: 55
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
S.E.REDDY Page 66
Programming with C - Lab
Fibonacci Series:
0 1 1 2 3 5 8 13 21 34
FOR Loop:
□ This is another entry control loop.
□ This integrates 3 basic ingredients of a loop (initialization, condition and
incrementing).
□ For loop is typically used to repeat statements for a fixed number of times.
□ The basic form of for statement:
Syntax:
for(initialization;condition;updation)
{
statement;
}
initialization Executed only for once just before loop starts. Normally counter
(variable used in loop) is initialized here.
condition Is any valid C condition. As long as this is true statement is
repeatedly executed.
S.E.REDDY Page 67
Programming with C
This is in effect same as while loop used previously. But, as it combines initialization,
condition and updation, it is more easier compared with while loop.
The following is another example for for loop where initialization and updation parts are
omitted.
/*this is to be terminated when 0 or negative number is given*/
for(;n>0;)
scanf("%d",&n);
Note: In C language, for loop can be used in place of while loop and vice -versa. Both of them
execute statements as long as the condition is true and terminate the loop once condition is
false.
The for statement
for(; ;)
{
statement;
}
is an infinite loop. This can be terminated using a break statement or an exit() function.
Comma Operator
It is possible to have more than one expression in initialization and updation portions
using (comma) operator. Comma operator is used to separate expressions.
The following is an example of for loop using comma operator:
printf("\nn\tj");
for(n=0,j=10;n<j;n++,j--)
printf("\n%d\t%d",n,j);
The output of the above example is
n j
0 10
1 9
2 8
3 7
S.E.REDDY Page 68
Programming with C
4 6
Example 2: Program to find number of even and odd numbers in the list
/*Program to find number of even and odd numbers in the list*/
#include<stdio.h>
#include<conio.h>
main()
{
int i,n,num,ecount=0,ocount=0;
clrscr();
printf("Enter number of values: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter a value: ");
scanf("%d",&num);
if(num%2==0) ecount++;
else ocount++;
}
printf("Even count in the list of %d numbers is %d\n",n,ecount);
printf("Odd count in the list of %d numbers is %d\n",n,ocount);
getch();
}
Output:
Enter number of values: 10
S.E.REDDY Page 69
Programming with C
Enter a value: 8
Enter a value: 6
Enter a value: 4
Enter a value: 12
Enter a value: 9
Enter a value: 2
Enter a value: 3
Enter a value: 1
Enter a value: 15
Enter a value: 98
Even count in the list of 10 numbers is 6
Odd count in the list of 10 numbers is 4
S.E.REDDY Page 70
Programming with C
float sum=1;
clrscr();
printf("Enter number of terms: ");
scanf("%d",&n);
printf("Enter x value: ");
scanf("%d",&x);
k=1;
for(i=1;i<n;i++)
{
j=k;
f=1;
while(j>0) {
f = f*j;
j--;
}
sum=sum+sign*((float)(pow(x,i))/f);
k++;
sign=sign*(-1);
}
printf("\n1");
for(i=1;i<n;i++) {
if(i%2==0) ch='-';
else ch='+';
printf(" %c %d^%d/%d!",ch,x,i,i);
}
printf(" = %f",sum);
getch();
}
Output:
Enter number of terms: 5
Enter x value: 2
break statement
This is used to terminate a loop. A loop can be terminated either when condition is false
or when you execute break statement. When you have to terminate loop based on some
other condition other than condition of the loop then you can use break statement.
Example 1: Program to implement break statement
/*Program to Implement break Statement*/
#include<stdio.h>
main()
{
int i;
S.E.REDDY Page 71
Programming with C
clrscr();
for(i=1; i<=10; i++)
{
printf("\n%d", i);
if (i == 7)
break;
}
getch();
}
Output:
1
2
3
4
5
6
7
Example 2: Program to display sum of 10 numbers or till 0 is given which comes first.
/*Program to display sum of given numbers*/
#include<stdio.h>
main()
{
int sum=0,n,c;
clrscr();
for(c=1;c<=10;c++)
{
printf("Enter a number (0 to stop): ");
scanf("%d",&n);
if(n==0)
break;
sum += n;
}
printf("Sum = %d",sum);
getch();
}
Output:
Enter a number (0 to stop): 5
Enter a number (0 to stop): 6
Enter a number (0 to stop): 4
Enter a number (0 to stop): 2
Enter a number (0 to stop): 8
Enter a number (0 to stop): 0
Sum = 25
S.E.REDDY Page 72
Programming with C
continue statement
This is used to transfer control to the beginning of the loop from within the loop. It is
used to skip the statements after continue statement and enter into next iteration of the
loop.
Example: Program to Implement continue Statement
/*Program finds square of positive numbers only*/
#include <stdio.h>
main()
{
int i, n, a, sq;
clrscr();
printf("\nHow many numbers you want to enter: ");
scanf("%d", &n);
for (i=1;i<=n; i++)
{
printf("\nEnter number: ");
scanf("%d", &a);
if(a<0)
continue;
sq = a * a;
printf("\nSquare = %d\n", sq);
}
getch();
}
Output:
How many numbers you want to enter: 3
Enter number: 2
Square = 4
Enter number: -1
Enter number: 6
Square = 36
Nested Loops
When a loop is placed inside another loop, it is called as nested loop. C allows nested
loops. The inner loop or nested loop is executed for each repetition of the outer loop.
Example 1: Display numbers in the following format.
1 2 3 4 5
1 2 3 4 5
S.E.REDDY Page 73
Programming with C - Lab
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
#include<stdio.h>
main()
{
int i,j;
clrscr();
for ( i = 1; i <= 5 ; i++)
{
printf("\n");
for ( j = 1 ; j <= 5 ; j ++)
printf("%5d", j);
}
getch();
}
S.E.REDDY Page 74
Programming with C - Lab
{
int i,j;
clrscr();
for ( i = 1; i <= 5 ; i++)
{
for ( j = 1 ; j <= i ; j ++) {
printf("%5d", i);
}
printf("\n");
}
getch();
}
S.E.REDDY Page 75
Programming with C - Lab
for ( i = 1; i <= 5 ; i++)
{
for ( j = 5 ; j >= i ; j--) {
printf("%5d", j);
}
printf("\n");
}
getch();
}
S.E.REDDY Page 76
Programming with C - Lab
}
getch();
}
S.E.REDDY Page 77
Programming with C - Lab
Step 5.1: rem = n%10
Step 5.2: rev = (rev*10) + rem
Step 5.3: n = n/10
Step 6: EndWhile;
Step 7: Print "Reverse Number: ", rev
Step 8: End
S.E.REDDY Page 78