C-Lang (control statements)
C-Lang (control statements)
C-Lang (control statements)
SUPPORTING LEARNING
MATERIAL
MODULE-II
TOKENS AND CONTROL STATEMENTS
Module II
Syllabus
Tokens: All tokens, operators and expressions, type conversions in C. Input and Output:
Introduction, non-formatted input and output, formatted input and output. Control
Statements: Introduction, conditional execution (if, if-else, nested if), and selection (switch),
Tokens are the basic building blocks in programming, which are constructed together
Control statements used to specify the flow of program control; ie, the order in
1. What is an operator? Explain the arithmetic, relational, logical, and assignment operators
in C language.
2. Explain the importance of a switch case statement. In which situations is a switch case
desirable? Also give its limitations.
5. Explain the two way selection (if, if-else, nested if-else, else-if ladder) in C language with
syntax
6. Explain the differences between break and continue statement with example.
8. Write a C program to read a floating point number. Display the rightmost digit of the
integral part of the number.
10. Write a C program to swap the values of two variables, say x and y, using temporary
variable and without using temporary variable.
C - TOKENS
Tokens: Tokens are the basic buildings blocks in C language which are constructed together
to write a C program. Each and every smallest individual units in a C program are known as C
tokens.
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special symbols
6. Operators
Example:
main()
{
int x, y, total;
x = 10, y = 20;
Total = x + y;
Printf (“Total = %d \n”, total);
}
Where, main – identifier, {,}, (,) – delimiter int – keyword
X, y, total – identifier
Main, {, }, (, ), int, x, y, total – tokens
Identifiers in c language:
Each program elements in a C program are given a name called identifiers. Names
given to identify Variables, functions and arrays are examples for identifiers.
Eg. Int X;
Float f;
Char c;
double d;
here X, f, c, d are the names given to integer, float, char and double variables.
Keywords in c language:
Keywords are pre-defined words in a C compiler. Each keyword is meant to perform a
specific function in a C program. Since keywords are referred names for compiler, they can’t
be used as variable name.
Ex:
DO IF STATIC WHILE
Constant:
C Constants are also like normal variables. But, only difference is, their values can not
be modified by the program once they are defined. Constants refer to fixed values. They are
also called as literals. Constants may be belonging to any of the data type.
Syntax:
Const data_type variable_name; (or) const data_type *variable_name;
Types of c constant:
1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants
1. Integer constants in c:
Department Of CSE and IT, GITAM Institute Of Technology, GU
6
2. Real constants in c:
A real constant must have at least one digit
It must have a decimal point
It could be either positive or negative
If no sign precedes an integer constant, it is assumed to be positive.
No commas or blanks are allowed within a real constant.
Example:
float (0.456789)
double (123.123456789)
Backslash_character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
Example:
#include <stdio.h>
void main()
Department Of CSE and IT, GITAM Institute Of Technology, GU
8
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real constant*/
const char letter = 'A'; /*char constant*/
const char letter_sequence[10] = "ABC"; /*string constant*/
const char backslash_char = '\?'; /*special char cnst*/
printf("value of height :%d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);
}
Variable:
C variable is a named location in a memory where a program can manipulate the data.
This location is used to hold the value of the variable.
The value of the C variable may get change in the program.
C variable might be belonging to any of the data type like int, float, char etc.
Example:
#include <stdio.h>
int add_numbers( void );
int value1, value2, value3; /* global variables*/
OPERATORS
2) Relational
3) Logical
4) Assignment
5) Bitwise
6) Conditional
7) Increment and decrement.
Operator Description
/ division
* multiplication
Program: (a+b)
#include<stdio.h>
main()
{
int a,b,c;
printf(“enter a&b values:”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“the sum of a&b is %d”,c);
c=a-b;
c=a*b
printf(“a*b=%d”,c);
c=a/b
printf(“a/b=%d”,c);
}
2. Relational operators: These operators checks relation b/w 2 operants .if the relation
is true it returns value 1 otherwise it returns o.
Ex:-a>b
== Equal to 5==3(returns 0)
Returns false.
Returns true.
Returns false.
4. Assignment operator:
Most common assignment operator is ‘equal to’(=).this operator assigns the value in right side
to left side.
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
5. Bitwise operators: These are used to perform bit level operations on each bit of data.
Operator meaning
| Bitwise OR
^ Exclusive OR
~ Bitwise complement
Example:
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Program:
#include<stdio.h>
main()
{
int a,b,c;
printf(“enter a and b values:”);
scanf(“%d%d”,&a,&b);
c=a&b;
printf(“bitwise AND of a&b is %d”,c);
c=a|b;
printf(“bitwise OR of a&b is %d”,c);
c=a^b;
printf(“bitwise exclusive OR of a&b is %d”,c);
}
6. Conditional operators:
These are used for decision making in c programming .it takes 3 operands and consists
of 2 symbols (? And : ).
C=(a>b)?a:b;
C=(c>0)?10:10;
Comma operator:
A set of expression separated by comma is a valid constant in the C language. For example i
and j are declared by the statements
int i , j;
i=(j=10, j+20);
In the above declaration, right hand side consists of two expressions separated by comma. The
first expression is j=10 and second is j+20. These expressions are evaluated from left to right.
ie first the value 10 is assigned to j and then expression j+20 is evaluated so the final value of
i will be 30.
Size of operator:
It is a unary operator which is used in finding the size of data types, constants, arrays,
structures, etc
Program:
#include<stdio.h>
main()
{
int a;
float b;
double c;
char ch;
Department Of CSE and IT, GITAM Institute Of Technology, GU
15
Pre-increment:
In this first, the variable is incremented by 1 and only after that, any operation is performed on
variable.
Syntax: ++variable;
int a,i=2;
a=++i;
In the above example, first ‘i’ is incremented to 1, i.e, ‘i’ becomes 3 and after that ‘i’ will be
assigned to a.
Post-increment:
In this first, the operator is performed on variable and only after that, variable is incremented
by 1.
Syntax: variable++;
int a,i=2;
a=i++;
in the above example ,first ‘i’ is assigned to a and after that ‘i’ will be incremented by 1.
Pre-decrement:
In this first, the variable is decremented by 1 and only after that, any operation is performed
on variable.
Syntax: - -variable;
Example:
- -i or - -a;
int a,i=2;
a=- -i;
In the above example, first ‘i’ is decremented to 1 and only after that ‘i’ will be assigned to a.
Post-decrement:
In this first, the operator is performed on variable and only after that, variable is decremented
by 1.
Syntax: variable- -;
Example: i - -or a- -;
int a,i=2;
a=i- -;
In the above example, first ‘i’ is assigned to a and only after that ‘i’ will be decremented by 1.
EXPRESSIONS
Ex: SI=P*T*R/100
(a+b) c/d;
a*b+c (d+x);
5*a+b+b*c;
(a+b)*(x+y);
Evaluation of expressions:
Ex: SI=P*T*R/100
Precedence of operators:
Operator precedence determines which operator will be performed first in a group of operators
with different precedence. For instance 5 + 3 * 2 is calculated as 5 + (3 * 2), giving 11, and
not as (5 + 3) * 2, giving 16.
The order of priority in which the operations can perform in an expression is called
presidency.
An arithmetic expression without parenthesis will be executed from left to right
using the rules of presidency of operators.
The basic evaluation procedure includes two passes from left to right through the
expression.
During the first pass the highest priority operator (if any) are applied as they are
encountered.
Whenever parenthesis are used in the expressions, within parenthesis assumes
highest priority.
If two or more sets of parenthesis appear one after the another as 9-12/(3+3)*(2-1).
The expression contained in the left most set is evaluated first and the right most set
in the last.
Ex: 9-12/ (3+3)*(2-1)
9-12/6*1
9-2*1
9-2
Department Of CSE and IT, GITAM Institute Of Technology, GU
19
7
If the parenthesis is nested and in such cases evaluation of the expression will
process outwards from the inner most set of the parenthesis.
B) 9-((12/3) +3*2)-1
9-(4+3*2)-1
9-(4+6)-1
9-10-1
-1-1
-2
Program 1:-
#include<stdio.h>
#include<conio.h>
main()
{
int a=20;
int b=10;
int c=15;
int d=5;
int e;
e=(a+b)*c/d;
printf("\n Value of (a+b)*c/d is : %d\n",e);
e=((a+b)*c)/d;
printf("\n Value of ((a+b)*c/d) is : %d\n",e);
e=(a+b)*(c/d);
printf("\n Value of (a+b)*(c/d) is : %d\n",e);
e=a+(b*c)/d;
printf("\n Value of a+(b*c)/d is : %d\n",e);
getch();
}
TYPE CONVERSIONS:
Generally the data type conversions or the type casting can be possible in the following
three ways.
If we are using the assignment operator the right side value can be automatically
converted into left side.
Ex -1: int x=5; Ex-2: int x;
float y; float y=3.5;
y=x; x=y;
x=a*b+c;
3. USING CAST OPERATOR (EXPLICIT):
We can also perform type conversion explicitly by using a cast operator in the following
way.
Syntax: (Type name) expression;
OR
(Type name) variable;
Where, type name is any of c data types and expression may be a constant, variables or any
arithmetic expressions.
Ex-1: a= (int) 8.65; Ex-2: x= (float) 7;
It returns a=8 It returns x=7.000000
#include<stdio.h>
main()
{
int cum=17,count=5;
double mean;
mean=(double)sum/count;
printf(“\n Value of mean is : %f\n”,mean);
}
Program 2:-
#include<stdio.h>
main()
{
int i=17;
char c=’c’;
int sum;
sum=i+c;
printf(“\n The value of sum is : %d\n”,sum);
}
INPUT AND OUTPUT
Non formatted Input Output function :
These are console Input Output Library function which deal with one character at a
time and string function for Array of characters ( String ).Unformatted I/O functions works
only with character datatype (char). The unformatted Input functions used in C are getch(),
getche(), getchar(), gets().
putch displays any alphanumeric characters to the standard output device. It displays only one
character at a time.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char a[20];
gets(a);
puts(a);
getch();
}
%[-][+][0][x[.y]]conv
Here the terms put in brackets are optional. The meaning of these terms is as follows:
term meaning
- left justify the argument
+ print a number with its sign, + or -
0 pads a number with leading zeros
x minimum field width
.y number of decimal places
The conv is a character from the following list:
conv meaning
b boolean (true/false)
d integer
e exponential notation
f floating point number
lf double precision f.p. number
o unsigned octal
s string of characters
x unsigned lower-case hexadecimal
X unsigned upper-case hexadecimal
The format string, or strings to be output, can contain special control sequences (escape
sequences):
\r carriage return
\t horizontal tab
CONTROL STATEMENTS
Branching is deciding what actions to take and looping is deciding how many times to
take a certain action.
if statement:
This is the simplest form of the branching statements. It takes an expression in
parenthesis and a statement or block of statements. if the expression is true then the statement
or block of statements gets executed otherwise these statements are skipped.
Flowchart:
Syntax:
if (expression)
statement;
or
if (expression)
{
Block of statements;
}
or
if (expression)
{
Block of statements;
}
else
{
Block of statements;
}
or
if (expression)
{
Block of statements;
}
else if(expression)
{
Block of statements;
}
else
{
Block of statements;
}
Example 1:
#include <stdio.h>
main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// Test expression is true if number is less than 0
if (number < 0)
{
printf("You entered %d.\n", number);
}
Example 2:
#include <stdio.h>
main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
}
Nested if….else statement:
The if...else statement executes two different codes depending upon whether the test
expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities.
The nested if...else statement allows you to check for multiple test expressions and execute
different codes for more than two conditions.
Flowchart:
if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and
testExpression3 is true
}
.
.
else
{
// statements to be executed if all test expressions are false
}
Example:
#include <stdio.h>
main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
Switch statement
The switch statement is much like a nested if .. else statement. Its mostly a matter of
preference which you use, switch statement can be slightly more efficient and easier to read.
Syntax:
switch( expression )
{
case constant-expression1: statements1;
[case constant-expression2: statements2;]
[case constant-expression3: statements3;]
[default : statements4;]
}
Example:
#include <stdio.h>
main()
{
int Grade = 'A';
switch( Grade )
{
case 'A' : printf( "Excellent\n" );
case 'B' : printf( "Good\n" );
case 'C' : printf( "OK\n" );
case 'D' : printf( "Mmmmm....\n" );
case 'F' : printf( "You must do better than this\n" );
default : printf( "What is your grade anyway?\n" );
}
}
Using break keyword
If a condition is met in switch case then execution continues on into the next case
clause also if it is not explicitly specified that the execution should exit the switch statement.
This is achieved by using break keyword.
break Statement
The break statement terminates the loop immediately when it is encountered. The
break statement is used with decision making statement such as if...else.
Syntax: break;
Example:
# include <stdio.h>
main()
{
int i;
double number, sum = 0.0;
Continue Statement
The continue statement skips some statements inside the loop. The continue statement
is used with decision making statement such as if...else.
continue;
Example:
# include <stdio.h>
main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
if(number < 0.0)
{
continue;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
}
Goto Statement
The goto statement branches unconditionally from one point to another in the block. In
other words the goto statement transfers execution to another label within the statement block.
The goto requires a label to identify the place where the branch is to be made to. A label is
any valid identifier and must be followed by a colon. The label is placed immediately before
the statement where the control is to be transferred. The goto statement can transfer the
control to any place in a program.
Syntax :
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
The label is an identifier. When goto statement is encountered, control of the program jumps
to label: and starts executing the code.
As shown in the above syntax, if the label is after the goto statement, then it is known as
forward jump and if the label is before the goto statement, it is known as backward jump.
Example:
void fun(int x)
{
back:
if( condition1)
{
x++;
goto next;
}
else if( condition 2)
{x=x+2;
goto back;
}
x=x+3;
next:
printf(“%d”,x);
if (!done)
goto back;
}
Conclusion of Module II
input and output, formatted input and output. In Module II another key role topic in C
unconditional execution like if, if-else, nested if, and selection (switch), break, continue, goto.