Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
UNIT-2
History of C language,
Characteristics of C language,
Structure of C Language,
C Tokens
Arithmetic expressions,
Operator Precedence & Associativity
Conditional Branching and
Loops
Writing and evaluation of conditionals, consequent
branching, Jumping Constructs, Pretest and Post test,
Iteration and loops
Dennis Ritchie
History of C language
‘B’ was used to create early versions of UNIX operating system at Bell
Laboratories.
a) Multi-line comment:
/* This is a multi-line comment */
b) Single-line comment
// This is a single-line comment
Link Section
The link section provides instructions to the compiler to link
functions from the system library.
If we want to access the functions stored in the library, it is
necessary to tell the compiler about the files to be accessed. This is
achieved by using the preprocessor directive #include as follows:
#include<filename>
where filename is the name of the library file that contains the
required function definition. Preprocessor directives are placed at
the beginning of the program. Some of the examples are:
#include<stdio.h>
#include<conio.h>
#include<math.h>
Definition Section
The definition section defines all symbolic constants.
A #define is a preprocessor compiler directive and not a
statement. Therefore #define lines should not end with a
semicolon.
Symbolic constants are usually written in uppercase so that
they are easily distinguished from lowercase variable names.
#define instructions are usually placed before the main( )
function.
e.g. #define YEAR 2014
#define PI 3.14
Global Declaration Section
There are some variables that are used in more than one
function. Such variables are called global variables and are
declared in the global declaration section that is outside of all
the functions.
Main calls
library function
printf to print
this message.
Let us look various parts of the above program:
Preprocessor Directives
Example: #include<stdio.h>
Header file contains a collection of library files.
#include<stdio.h> includes the information about the standard
input/output library.
All sections except the main () function may be absent when they are
not required.
Digits: 0123456789
Special Characters:
’"()*+-/:= !&$;<>%?,. ˆ#@˜‘{}[]\|
Percent Legal
y2x5__fg7h Legal
expression
X=Y+Z
Operators: =, + Operands: x, y, z
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operator
5. Increment and Decrement Operators
6. Conditional / Ternary Operators
7. Bitwise Operators
8. Special Operators
Arithmetic Operators
An arithmetic operator performs mathematical operations such as
addition, subtraction and multiplication on numerical values
(constants and variables).
C Operation Binary C
Operator Expression
Addition + a+b
Subtraction - a-b
Multiplication * a*b
Division(second operand must be nonzero) / a/b
Modulus (Remainder both operands must % a%b
be integer and second operand must be non
zero)
#include <stdio.h>
void main()
{
int a=9,b=4;
printf("Addition of a, b is : %d\n", a+b); //13
printf("Subtraction of a, b is : %d\n", a-b); //5
printf("Multiplication of a, b is : %d\n", a*b); //36
printf("Division of a, b is : %d\n", a/b); //2
printf("Modulus of a, b is : %d\n", a%b); //1
}
Relational Operators
Relational operators are used to compare the relationship between
two operands.
Syntax: exp1 relational_operator exp2
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.
Relational operators are used by if , while and for statements.
C operation Relational C expression
Operator
greater than > x >y
less than < x<y
greater than or equal to >= x >= y
less than or equal to <= x <= y
Equality == x == y
not equal != x != y
// C Program to demonstrate the working of relational operators
#include <stdio.h>
void main()
{
int a = 5, b = 5, c = 10;
printf("%d == %d = %d \n", a, b, a == b); // 1
printf("%d == %d = %d \n", a, c, a == c); // 0
printf("%d > %d = %d \n", a, b, a > b); // 0
printf("%d > %d = %d \n", a, c, a > c); // 0
printf("%d < %d = %d \n", a, b, a < b); // 0
printf("%d < %d = %d \n", a, c, a < c); // 1
printf("%d != %d = %d \n", a, b, a != b); // 0
printf("%d != %d = %d \n", a, c, a != c); // 1
printf("%d >= %d = %d \n", a, b, a >= b); // 1
printf("%d >= %d = %d \n", a, c, a >= c); // 0
printf("%d <= %d = %d \n", a, b, a <= b); // 1
printf("%d <= %d = %d \n", a, c, a <= c); // 1
}
Logical Operators
Logical operators used to test more than one condition and make
decision. Yields a value either one or zero.
Syntax: operand1 logical_operator operand2 (or)
logical_operator operand
Example: (x<y) && (x= = 8)
Operator Meaning
&& Logical AND (true only if both the operands are true)
|| Logical OR (true if either one operand is true)
! Logical NOT (negate the operand)
A B A && B A || B
A !A
0 0 0 0
0 1
0 1 0 1
1 0 0 1 1 0
1 1 1 1
// C Program to demonstrate the working of logical operators
#include <stdio.h>
void main()
{
int a = 5, b = 5, c = 10, result;
result = (a == b) && (c > b);
printf("(a == b) && (c > b) equals to %d \n", result); // 1
result = (a == b) && (c < b);
printf("(a == b) && (c < b) equals to %d \n", result); // 0
result = (a == b) || (c < b);
printf("(a == b) || (c < b) equals to %d \n", result); // 1
result = (a != b) || (c < b);
printf("(a != b) || (c < b) equals to %d \n", result); // 0
result = !(a != b);
printf("!(a == b) equals to %d \n", result); // 1
result = !(a == b);
printf("!(a == b) equals to %d \n", result); // 0
}
Assignment Operators
Assignment operators are used to assign the result of an expression
to a variable.
Assignment Operator is =
Syntax: variable = expression;
Types of assignment:
– Single Assignment Ex: a = 10;
– Multiple Assignment Ex: a=b=c=0;
– Compound Assignment Ex: c = a + b;
Operator Example Equivalent
Statement
+= c += 7 c=c+7
-= c -= 8 c=c–8
*= c *= 10 c = c * 10
/= c /= 5 c=c/5
%= c %= 5 c=c%5
// C Program to demonstrate the working of assignment
operators
#include <stdio.h>
void main()
{
int a = 5, c;
c = a;
printf("c = %d \n", c); // 5
c += a; // c = c+a
printf("c = %d \n", c); // 10
c -= a; // c = c-a
printf("c = %d \n", c); // 5
c *= a; // c = c*a
printf("c = %d \n", c); // 25
c /= a; // c = c/a
printf("c = %d \n", c); // 5
c %= a; // c = c%a
printf("c = %d \n", c); // 0
}
Increment and Decrement Operators
We can add or subtract 1 to or from variables by using
increment (++) and decrement (--) operators.
The operator ++ adds 1 to the operand and the operator – –
subtracts 1.
They can apply in two ways: postfix and prefix.
Syntax: increment or decrement_operator operand
operand increment or decrement_operator
Prefix form: Variable is changed before expression is evaluated
Postfix form: Variable is changed after expression is evaluated.
#include <stdio.h>
void main()
{
int a = 10, b = 100;
}
Conditional (ternary)Operators ( ?: )
C’s only conditional (or ternary) operator requires three operands.
Syntax: conditional_expression? expression1: expression2;
The conditional_expression is any expression that results in a true
(nonzero) or false (zero).
If the result is true then expression1 executes, otherwise
expression2 executes.
Example: a=1;
b=2;
x = (a<b)?a:b;
This is like
if(a<b)
x=a;
else
x=b;
// C Program to demonstrate the working of Conditional
operators
#include <stdio.h>
void main()
{
int a = 10, b = 100;
(a>b)?printf("a=%d",a):printf("b=%d",b);
}
// Finding the Biggest Of Three Numbers Using Conditional operator
Conditional operator
#include <stdio.h>
void main()
{
int a=10,b=50,c=100;
(a>b)?(a>c?printf("a=%d",a):printf("c=%d",c)):(b>c?printf("b=%d",b):printf("c=%d",c));
}
Bitwise Operators
C has a special operator known as Bitwise operator for manipulation
of data at bit level.
Bitwise operator may not be applied for float and double.
Manipulates the data which is in binary form.
Syntax: operand1 bitwise_operator operand2
Bitwise Meaning
Operators
& Bitwise AND
| Bitwise OR
^ Exclusive OR
<< Shift left
>> Shift right
~ One’s compliment
A B A&B A|B A^B
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Examples:
& Bitwise AND 0110 & 0011 0010
| Bitwise OR 0110 | 0011 0111
^ Bitwise XOR 0110 ^ 0011 0101
<< Left shift 01101110 << 2 10111000
>> Right shift 01101110 >> 3 00001101
~ One's complement ~0011 1100
void main()
{
int m = 10,n = 20 ;
printf("AND_opr value = %d\n",m&n ); //0
printf("OR_opr value = %d\n",m|n ); //30
printf("NOT_opr value = %d\n",~m); //-11
printf("XOR_opr value = %d\n",m^n ); //30
printf("left_shift value = %d\n", m << 1); //20
printf("right_shift value = %d\n", m >> 1); //5
}
Note:Twist in bitwise complement operator in C
Programming
• The bitwise complement of 11 (~11) is -11 instead of
220, but why?
• For any integer n, bitwise complement of n will be -
(n+1). To understand this, you should have the
knowledge of 2's complement.
comma operator :
It doesn’t operate on data but allows more than one expression to
appear on the same line.
sizeof Operator :
It is a unary operator (operates on a single value).
Produces a result that represent the size in bytes.
Syntax: sizeof(datatype);
Example: int a = 5;
sizeof (a); //produces 2
sizeof(char); // produces 1
sizeof(int); // produces 2
Constants
Constants are data values that cannot be changed during the program
execution.
Like variables, constants have a type.
Types of constants:
Boolean constants: A Boolean data type can take only two
values true and false.
Character constants
Single character constants
string constants.
Numeric constants.
integer constant
real constants.
Type qualifier const
One way to use the constant is with memory constants. Memory
constants use a C type qualifier; const.
This indicates that the data cannot be changed.
const type identifier= value;
const float pi=3.14;
#include<stdio.h>
void main()
{
float area,radius=3.0;
const float pi=3.14;
area=pi*radius*radius;
printf(“area of a circle= %f”,area);
}
What is the output of the following code
main()
{
const int i=1,j;
j=i+1;
printf(“%d”,j)
}
#include<stdio.h>
void main()
{
const int a=10;
int b=20;
a=a+1;
b=b+1;
printf(“a=%d b=%d”,a,b);
}
Single character constants
A single character constants are enclosed in single quotes.
Example: ‘1’ ‘X’ ‘%’ ‘ ‘
Character constants have integer values called ASCII values.
char ch=‘A’;
printf(“%d”,ch); Output: 65
similarly printf(“%c”,65) Output: A
string Constants
String is a collection of characters or sequence of characters
enclosed in double quotes.
The characters may be letters, numbers, special characters and
blank space.
Example: “snist” “2011” “A”.
Backslash \escape characters
constant meaning
‘\a’ Alert(bell)
‘\b’ Back space
‘\f’ Form feed
Backslash characters are used ‘\n’ New line
in output functions.
‘\r’ Carriage return
These backslash characters are
preceded with the \ symbol. ‘\v’ Vertical tab
‘\t’ Horizontal tab
‘\’’ Single quote
‘\”’ Double quotes
‘\?’ Question mark
‘\\’ Backslash
‘\0’ null
Numeric Constants
integer constant: It is a sequence of digits that consists numbers from
0to 9.
Example: 23 -678 0 +78
Rules:
1. integer constant have at least one digit.
2. No decimal points.
3. No commas or blanks are allowed.
4. The allowable range for integer constant is -32768 to 32767.
To store the larger integer constants on 16 bit machine use the
qualifiers such as U,L,UL.
Mantissa e exponent
double 0. 0.0
double 0.0 .0
Defined constants:
By using the preprocessor command you can create a constant.
Example: #define pi 3.14
Memory constants:
Memory constants use a C type qualifier, const, to indicate that the
data can not be changed.
Its format is: const type identifier = value;
Example: const float PI = 3.14159;
Precedence and Association rules among operators
Precedence is used to determine the order in which different
operators in a complex expression are evaluated.
Example: a++; a- -;
expression
#include<stdio.h>
void main()
{
a=10;
x=a++;
printf(“x=%d, a=%d”,x,a);
}
Output:
x=10, a=11
Pre fix expression:
It is an expression which contains operator followed by an operand.
Prefix Expression
Result of prefix ++a
Example on pre fix expression
#include<stdio.h>
void main()
{
a=10;
x=++a;
printf(“x=%d, a=%d”,x,a);
}
Output:
x=11, a=11
Unary expression: It is an expression which consists of unary operator
followed by the operand
Binary Expressions
Example for Binary Expressions
Example for Binary Expressions
(continued)
Example for Binary Expressions
(continued)
The left operand in an assignment expression must be a single variable.
Where (data type) can be any valid C data type and expression is any
variable, constant or a combination of both.
Example: int x;
x=(int)7.5;
Conversion Rank (C Promotion Rules)
Example program for Implicit Type Conversion
Example program for Implicit Type Conversion (contd…)
Example program for Implicit Type Conversion (contd…)
Example program for Explicit Casts
Example program for Explicit Casts (contd…)
Example program for Explicit Casts (contd…)
Decision Control
Structures/Selection/branching statements
The decision is described to the computer as a conditional
statement that can be answered either true or false.
if (condition)
{
statement-block;
}
Both the true and false statements can be any statement (even
another if…else).
Nested if…else means within the if…else you can include another if…else either in
if block or else block.
Dangling else
Dangling else (contd…)
To avoid dangling else problem place the inner if statement with in
the curly braces.
Conditional Expression
Decision Control Statement: switch
A case label cannot appear more than once and there can only be one
default expression.
Decision Control Statement: switch
If printFlag is 2, then the first print statement is skipped and the last two
are executed.
If we add break to the last statement of the case, the general form of
switch case is as follows:
Decision Control Statement: switch
Example2 for switch statement:
Concept of a loop
Post-test Loop
In each iteration, the loop action(s) are executed. Then the
control expression is tested. If it is true, a new iteration is
started; otherwise, the loop terminates.
C Loop Constructs
Pretest and Post-test Loops
Minimum Number of Iterations in Two Loops
Initialization and Updating
Loop Initialization
Loop Update
Algorithm:
Step 1: start
Step 2: Initialize & Declare the variable i.
Step 3: Check the condition with i<=10;
if true go to step 4 else go to step 5
Step 4: print i
step 5: End.
Example 1: To print 1 to 10 natural numbers
#include<stdio.h>
main()
{
int i=1;
while (i<=10)
{
printf(“%d\n”,i);
i++;
}
}
1. Write a c program to print 1 to 10 natural numbers
2. Write a c program calculate the average of n numbers
3. Write a c program to print a multiplication table using while
4. Write a c program to print 1.. 10 multiplication tables using
while
5. Write a c program o print the reverse of the given number
(or) sum of individual digit.
6. Write a c program to check ASCII values using while loop
7. Write a c program to print reverse of 1..10 numbers
8. Write a C program to count total number of digits of an
Integer number (N).
9. Write a C program to check whether the given number(N)
can be expressed as Power of Two (2) or not. For example
8 can be expressed as 2^3.
10. Write a C program to check whether a given number (N) is
a perfect number or not?
do while
The “do while" loop is a repetition statement that allows an action
to be done at least once and then condition is tested.
If the condition is true, it evaluates the body of the loop once again.
Algorithm:
Step 1: start
Step 2: Initialize & Declare the variable i.
Step 3: print i
Step 4: i++
Step 5: Check the condition with i<=10;
if true go to step 3&4 else go to step 5
step 6: End.
Example 1: To print 1 to 10 natural numbers
#include<stdio.h>
main()
{
int i=1;
do
{
printf(“%d\n”,i);
i++;
} while (i<=10);
}
1. Write a calculator program using while and switch
2. Write a c program to check given value is palindrome or
not
3. Write a c program to check given value is prime or not
4. Write a c program to find given number factorial
5. Write a c program to print Fibonacci series
6. Write a c program to display 1 to n numbers using do while
7. Write a c program to display n to 1 numbers using do while
8. Write a multiplication table using do-while
9. Write a c program to check given value is Armstrong
number or not(Armstrong number of 3 digits, the sum of cubes of each digits is equal to
the number itself)
10. Write a c program to print 1 to n prime values using do
while
for
A for loop is used when a loop is to be executed a known number
of times.
We can do the same thing with a while loop, but the for loop is
easier to read and more natural for counting loops.
Option 1:
for (k= 1; k< = 10 ;)
{
printf(“%d”, k);
k = k + 1;
}
Here the increment is done within the body of the for loop and not in
the for statement. Note that the semicolon after the condition is
necessary.
Option 2:
int k = 1;
for (; k< = 10; k++);
{
printf(“, k);
}
Here the initialization is done in the declaration statement itself, but
still the semicolon before the condition is necessary.
Option 3: The infinite loop
One of the most interesting uses of the for loop is the creation of the infinite loop.
Since none of the three expressions that form the for loop are required, it is
possible to make an endless loop by leaving the conditional expression empty.
For example: for (; ;)
printf(“The loop will run forever\n”);
Actually the for (; ;) construct does not necessarily create an infinite loop because
C’s break statement, when encountered anywhere inside the body of a loop,
causes immediate termination of the loop.
Program control then picks up the code following the loop, as shown here:
for (; ;)
{
ch = getchar( ); /* get a character */
if (ch = = ‘A’)
break ;
}
printf (“you typed an A”);
This loop will run until A is typed at the keyboard.
Option 4: For loop with no body
The following statement shows how to create a time delay loop using a for
loop:
Example:
for(i=0;i<5;i++);
printf(“%d”,i);
The operator comma , is used to separate the more than one
expressions.
When loop are nested break only exit from the inner loop
containing it.
#include<stdio.h>
main()
{
int i;
i=1;
while(i<=10)
{
if(i==8)
break;
printf(“%d\t”,i);
i=i+1;
}
printf(“\n Thanking You”);
}
continue
When a continue statement is enclosed inside a block or loop, the
loop is to be continued with the next iteration.
#include<stdio.h>
main()
{
int i;
for(i=1;i<=5;i++)
{
if(i = = 3)
continue;
printf(" %d",i);
}
}
GOTO
A goto statement in C programming language provides an unconditional
jump from the goto to a labeled statement in the same function..
Syntax:
goto label;
.. .
label: statement;
Example 6: Program to demonstrate goto statement.
main()
{
int age;
Vote:
printf("you are eligible for voting");
NoVote:
printf("you are not eligible to vote");