Operators and Expressions, Control Structures in C
Operators and Expressions, Control Structures in C
relational operation to be performed. The data items that operators act upon are called operands. An expression is any computation involving variables and operators that yields a value.
operators
arithmetical unary
bitwise
ternary binary
ARITHMETIC OPERATORS
There are five arithmetic operators in C. They are
The% operator is also called as modulus operator Arithmetic operators are binary operators because they are operators act upon 2 operands
operand be nonzero.
UNARY OPERATORS
operators that act upon a single operand to produce a new value are
resides in memory
++var first add 1 to the variable var . then the result is assigned to the variable on the left. --var first subtract 1 from the variable var . then the result is assigned to the variable on the left.
Postfix-first assigns the value to the variable on left and then
Example
Let int i=1 printf("i = %d\n", i); printf (i= %d\n", ++i); printf("i = %d\n", i); output will be i=1 i=2 i=2 printf ("i = %d\n" i); printf("i = %d\n", i++); printf("i = %d\n", i); output will be i=1 i=1 i=2
Sizeof operator
sizeof is a unary compile time operator that returns the number of
Sizeof var (where var is a declared variable) Or Sizeof(type) (where type is a c data type)
Example
RELATIONAL OPERATORS
Relational operators are used for comparing numerical quantities. Relational operators evaluate to 1,representing true outcome or 0
The operands of a relational operator must evaluate to a number. Characters are valid operands since they are represented by numeric
values. For ex A < F /*will give the output 1 because comparing ascii values of A and F
Relational operators should not be used for comparing strings this
Logical operators
Logical operators&& and || are used to combine two or more relational expressions. An expression which combines 2 or more relational expression is termed as logical expression Logical And produces 0 if one or both operands evaluate to 0.otherwise produces 1 Logical OR produce 0 if both operands evaluate to 0 otherwise it produce 1
Logical not( ! ) is a unary operator negates the logical value of its single operand .it causes an expression that is originally true to become false, and vice versa.
Assignment operators
assign the value of an expression to an identifier assignment operators are used to form assignment expressions Assignment expressions are written in the form
identifier = expression identifier generally represents a variable. Expression represents a constant, a variable or a more complex expression.
assignment operator is used to assign a value to an identifier, whereas the equality operator is used to determine if two expressions have the same value
identifier 1 = identifier 2 = .... = expression is permissible in C In such situations, the assignments are carried out from right to left identifier 1 = identifier 2 = expression is equivalent to identifier 1 = (identifier 2 = expression)
Beside = operator, C programming language supports other short hand format which acts the same assignment operator with arithmetic operators a+=b means a=a+b
Conditional(ternary) operator
C offers a conditional operator(?: that store a value depending on a
condition.
A conditional expression is written in the form
first. If expression 1 is true then expression 2 is evaluated and this becomes the value of the conditional expression.
if expression 1 is false , then expression 3 is evaluated and this
Comma operator
The comma operator can be used to link related expressions together. A comma-linked list of expressions are evaluated left to right and value of right most expression is accepted as final result The general form of an expression using comma operator is Expression M=(expression1,expression2,..............expressionN); Since comma has the lowest precedence in operators the parenthesis is necessary.
Highest priority is for () and lowest for comma. Postfix ++ and - -has higher priority than prefix ++ and - Unary operators has higher priority than binary operators Relational operators having precedence less than arithmetic and unary operators Logical AND has higher precedence than logical OR
Associativity left-to-right
right-to-left
* / %
+ -
left-to-right
left-to-right
Type conversion
Type conversion occurs when the expression has data of mixed data types. example of such expression include converting an integer value in to a float value,
or assigning the value of the expression to a variable with different data type.
In type conversion, the data type is promoted from lower to higher because
Implicit conversion
It is the automatic conversion done by compiler without
programmers intervention
Rules for implicit conversion 1. If either operand is long double, convert the other to long double. 2. Otherwise, if either operand is double, convert the other to double. 3. Otherwise, if either operand is float, convert the other to float. 4. Otherwise, convert char and short to int. 5. Then, if either operand is long, convert the other to long.
I integer variable with value 7 F float variable with 5.5 C char variable with value w I+F will have value 12.5 I+C will have value 126
Explicit conversion
Explicit conversion is user defined that forces an expression to be of
specific type Explicit conversion of an operand to a specific type is called type casting General form of casting is (data type) expression The expression is converted to the data type specified in parenthesis The data type associated with the expression itself is not changed by a cast. Rather, it is the value of the expression that undergoes type conversion
For ex int a=100,b=40 float c; c=a/b will result 2.000000 but actual value required is 2.5 for that we have to use c=(float)a/b
Library functions
The C language is accompanied by a number of library functions
together as (compiled) object programs in separate library files. These library files are supplied as a part of each C compiler.
A library function is accessed simply by writing the function name,
followed by a list of arguments that represent information being passed to the function. The arguments must be enclosed in
with the compiler. Thus, the required information can be obtained simply by accessing these special files. This is accomplished with the preprocessor statement #include; i.e., #include <filename> where filename represents the name of a special file. For example #include<math.h> contains library functions for mathematical operations
putchar() Printf
Scanf
strcpy(s,t)
strlen(s)
Copy t to s
return length of s
Mathematical Functions
These functions defined in math.h
sin(x) cos(x) exp(x) log(x) sqrt(x) abs(i) pow(x,y) sine of x, x in radians cosine ofx, x in radians exponential function ex natural logarithm of x square root ofx (x>0) absolute value of integer variable xy
Unformatted
Formatted functions Type char int float string Input Scanf() Scanf() Scanf() Scanf() Output Printf() Printf() Printf() Printf() Type char
int
float string Gets() Puts()
programmer without waiting for the Enter Key to be hit. The typed character is not echoed on screen.
Getche() function will also read a single character the instant it is
typed by programmer without waiting for the Enter key to be hit, just like getch() function. Getche() echoes the character on screen that you
typed.
#include<stdio.h> #include<conio.h> Void Main() { char ch; printf(Press any key to continue"); getch(); //will not echo the character printf(Type any character:"); ch=getche();
putch()
putch() writes a character to the screen.
empty parenthesis.
The getchar has the following form.
Char_variable = getchar();
Char_variable must be previously declared character variable.
On end of file the value of EOF is returned. Usually EOF will be assigned the value -1, though this may vary from
#include<stdio.h> main() { char in; printf(" enter one character "); in=getchar(); Printf(entered character is ); putchar(in); }
scanf ()
Scanf() allows to enter data from the keyboard that will be formatted
in a certain way.
The function returns the number of data items that have been entered
successfully.
General form of scanf
scanf(control string,arg1,arg2.......argn);
Control string is a string that can consist of format specifiers.it
indicates the format and type of data to be read from standard input device.
Argl,arg2, . . . argn are arguments that represent the individual input
data items.
These arguments are preceded with the address-of operator to
There is no need to use & for strings stored in arrays because array name is already a pointer
x c
s e f g %lf
the size qualifier conversion characters may be preceded with certain conversion characters
main( )
{
char item[20]; i n t partno; f l o a t cost; ..... scanf("%s %d %f",item, &partno, &cost); ..... }
%s, indicates that the first argument (item) represents a string. %d, indicates that the second argument (&partno) represents a decimal
integer value
%f,indicates that the third argument (&cost) represents a floating-point
value
More on scanf
The format specifier %% is used for single % character in the input stream.
%[characters] %[^characters]
The specification %[characters] means that only the character
specified with in the brackets are permissible in the input string.if input string contains any other character string will be terminated at the first
spaces.
The specification %[^characters] means the characters specified
after the circumflex(^) are not permitted in the input string. The reading of string will be terminated at the encounter of one of these character
Example of %[]
main() { char address[80]; printf("Enter address\n"); scanf("%[a-z]", address); printf(%-80s,address); } Output Enter address new york 122345 new york
Example of %[^]
main() { char address[80]; printf("Enter address\n"); scanf("%[^\n]", address); printf("%-80s", address); } Output Enter address New Delhi 110 002 New Delhi 110 002
following cases A white space character found in numeric specification Maximum number of characters have been read An error detected The end of file is reached
Printf()
O/P data can be written from the computer onto a standard O/P
device using the library function printf General form is printf(control string,arg1,arg2.....argn); where control string refers to a string that contains formatting information, and arg1, arg2, . . . , argn are arguments that represent the individual output data items. Control string contain 3 types of items characters that are simply printed as they are conversion specification that begin with a % sign escape sequence that begin with a \sign
Signed decimal integer decimal, hexadecimal or octal integer octal integer unsigned decimal integer
the size qualifier conversion characters may be preceded with certain conversion characters .size qualifier characters are h for short,l for long and L for long double
x c
s e f g %lf
More on printf()
Outputting integer numbers
While outputting a integer number we can also specify minimum field
width for the output. General format is %wd w-minimum field width for output. if number grater than specified field width it will be printed in full overriding minimum specification d-value to be printed is a integer The number is written right justified in the given field width
Examples
Format
Printf(%d,1234); Printf(%6d,1234);
output
1 2 1 3 2 3 4 4
Printf(%-6d,1234) 1
2 2
3 3
4 4
Printf(%2d,1234);
decimal point and minimum number of positions that are to be used for display
General format is
%w.pf w-minimum field width specification p- specifies no.of digits to be displayed after decimal
We can also use
point(precision)
examples
To print Float y=98.7654 Format Printf(%7.4f,y) Printf(%7.2f,y)
Printf(%-7.2f,y)
9 8
output
9 .
8 7
. 7
8
9 .
8 8 e + 0 1
Outputting strings
A single character can be displayed in desired position
using %wc The character will be displayed right justified in field of w columns Format specification for outputting string is %w.ps where w specifies the field width for display and p specifies only first p characters of the string are to be displayed
examples
For outputting strings NEW DELHI 110001 specification output %s N E W D E L H I 1 1 0 0 %20s N E W D E L H I
%20.10s %5s %.5s
%-20.10s N E W N E W N E W N E W D E L H I D D E L H I 0 1 1 1 0 0 0 1 D E L H I
1 1 0 0 0 1
We can also include flags , which affects the appearance of the output in printf Flags are used immediately after % sign Commonly used flags and their meaning given below
flag + 0 #
Printf(%07.2f,y) Printf(%-+6.1f,5.5)
0 +
0 5 .
9 5
gets (str)
Here str is a string variable It will reads characters into str from keyboard until newline character is encountered and will append a null character to the string
puts outputs the string to the standard output device. The standard form for the puts function is puts (str) where str is a string variable.
The puts function displays the contents stored in its parameter on the screen. In puts() function,we cannot pass more than one argument.So it can display one string at a time.
#include<stdio.h> Void main() { char s[80]; printf("Type a string less than 80 characters:"); gets(s); Puts( The string types is: ); puts(s); }
Control statements
C language provides statements that can alter the flow of a sequence of instructions. These statements are called control statements. These statements help to jump from one part of the program to another.
The statements which specify the order of execution
Selection/branching
Conditional type
Unconditional type
Iteration/looping
for while Do-while
if Ifelse
If-elseif
If statement
The simplest form of the control statement is the If statement. It is very frequently used in decision making and allowing the flow
of program execution.
Syntax if (Test expression) statement; The test expression inside if should not end with a semicolon
If-else
If...else is an extension of simple if statement. General form is
if(test expression)
Statement1 Else Statement 2
if the test expression evaluates to true, then program statement 1 is
#include<stdio.h> void main() { int a,b; printf("Enter 2 number"); scanf("%d%d",&a,&b); if (a>b) printf("%d is greater",a); else printf("%d is greater",b); }
II
III
if(test expression 1 ) {
/*sample code using nested if-else */ if(a>b) { if(a>c) printf("%d is larger",a); } else if(b>c) printf("%d is larger",b); else printf("%d is larger",c); }
If-else-if ladder
When a series of many conditions have to be checked
if (test Expression 1) statement 1; else if (test Expression 2) statement2; else if (test Expression 3) statement3; . . else if (Test Expression n) statement n; else statement-F;
if expression2 is true then statement 2 is executed and so on. If none of the test expression are true then statement F will be executed
Sample code for if else- if ladder { ---------If(score>=80) Grade=A; Else if(score>=70 && score<80) Grade=B; Else if(score>=60 && score<70) Grade=C; Else if(score>=50 && score<60) Grade=D Else Grade=F; }
Looping/iteration
Looping allows set of instructions to be performed repeatedly until a
the loop.
In a exit controlled loop test expression is evaluated before exiting
Test expression
false
Body of loop
True
Body of loop True Test expression false Pre-test loop Post-test loop
In pretest loop ,loop body may not be executed where as in post-test loop loop body will be executed at least once
Do while
for and while are pretest/entry controlled loops and do while is exit controlled/post test loops
Parts of loop
Initialization expression(s)
before entering the loop, loop control variables must be initialized. this initialization of control variable take place under initialization
expression .
This part of loop is the first to be executed. Initialization expression(s) are executed only once in the beginning of the
loop
Test expression
Test expression is an expression whose truth value decides whether the
is terminated
Update expression(s)
change value of loop control variable(s)
Update expression are executed every time through the loop before
test expression is tested Body- of- the loop The statements that are executed repeatedly form the body of the loop
While Loop
The while statement is used to carry out looping operations, in which a
group of statements is executed repeatedly, until some condition has been satisfied.
Is an entry controlled loop The general form of the while statement is
is true
Statements can be simple or compound,
start
Initialization
false
In while loop ,initialization of loop control variable done before the loop starts. Updating must included in the body of the loop
Statement(s)
Update expressions
Sample program
//to print numbers 1 to 10 using while loop void main() { int i=1; while(i<=10) { printf("%d\n",i); i++; } }
For loop
It is a commonly used loop
This loop is definite loop because programmer knows exactly how
Initialization
false
All the four parts of while loop is also present in for loop. but all are comprised in one line
for loop can written as equivalent to while loop and vice versa
{
statement ; Update expressions;
Do while loop
It is a post-test loop
Test expression is evaluated after executed loop body at least once General syntax is
do { statement } while (expression); Statements will be executed until expression become false.
Initialization
statements
Update expressions
True
//to print numbers 1 to 10 using do-while loop void main() { int i=1; do { printf("%d\n",i); i++; }while(i<=10);
}
for(i=1;i<5;i++) { for(j=1;j<=i;j++) { printf(%d\t",j); } printf("\n"); } Here inner for loop is executed for each value of i.i takes values 1,2,3,4 Inner loop is executed once for i=1 according to condition j=i;,twice for i=2,thrice for i=3 and four times when i=4
Nesting of while int n,i=1,j=1; while(i<=n) { j=1; while(j<=i) { printf(%d\t,j); j++; } printf("\n"); i++; }
Nesting of do while Int i=1,j=1; do { j=1; do { printf("%d",j); j++; }while(j<=i); printf("\n"); i++; }while(i<=n);
Switch statement
The usage of multiple If else statement increases the complexity of the program since when the number of If else statements increase it
affects the readability of the program and makes it difficult to follow the
program. The switch statement removes these disadvantages by using a
Switch(expression) { Case constant 1:statementlist1; break; Case constant 2:statementlist2; break; .. Default :statementlist n }
is executed the expression is evaluated first and the value is compared with the
case label values in the given order. If the case label matches with the value of the expression then the control is
Sample code
switch(choice) { case 1: printf(you entered menu choice #1); break; case 2:printf(you entered menu choice #2); break; default:printf("Invalid Choice"); break; }
Once the statement list under a case is executed ,the flow of control
continues down executing all the following cases until the break is reached
Switch(number) { Case 1: Case 3: Case 5: Case 7: case 9 : printf(%d is an odd number,number); break; Case 2: Case 4: Case 6: Case 8:printf(%d is an even number,number); break; Default:printf(%d is not between or including 1 and 9,number); break; }
belong to the same statements The default label is optional. If present, it will be executed when the expression does not find a matching case label There can be at most one default label Default may be placed anywhere but usually placed at the end
logical expression
2.switch cannot handle floating point test. Where if can handle floating
variable against set of constants whereas if else use series of expression that involve unrelated variables and complex expression
4.Switch case label value must be a constant
break
The break statement is used to terminate loops or to exit from a switch. It
break;
After a break is executed with in a loop or a case in switch execution
getch();
} Here output will be 1 2 break statement skips the rest of the loop and jumps over to the statement following loop
continue
Continue statement does not terminate the loop .it forces the next
do
{ . continue; }while(testexpr); For(initialization;testexpr;updation) { Continue; . . }
continue
It helps in avoiding the remaining statements in current iteration of the loop and continuing with the next iteration It can be used only in loop constructs
GOTO statement:
The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program. In its general form, the goto statement is written as goto label; where label is an identifier that is used to label the target statement
Sample code
void main() { float x,y; read: scanf(%f,&x); if(x<0) goto read; y=sqrt(x); printf(%f%f\n,x,y); }
void main() { int n,i; long int fact=1; scanf(%d,&n); if(n<0) goto end; for(i=1;i<=n;i++) fact*=i; printf(factorial is %ld,fact); end: getch(); }