Programming in c unit 2 by K K Bohra Lachoo College

31
Programming in C [BCA I Sem] Unit II(1) K K Bohra (LMSCT, 2014) BCA I Year Semester I PROGRAMMING IN C [BCA111] Unit II Operators - relational, logical, bit wise, unary, hierarchy of operators. Control statements - if-else, nested if, switch case, goto and labels, looping statements - while, do-while and for, nested loops, break and continue. ===================================================================== »» Operators C support a rich set of operators. We have already used several of them, such as =, +,-, *, & and <. An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. . Operators are used in programs to manipulate data and variables. C operators can be classified into a number of categories, they include 1. Arithmetic Operator 2. Relational Operator 3. Logical Operator 4. Assignment Operators 5. Increment and Decrement Operators 6. Conditional Operators 7. Bitwise Operators 8. Special Operator. 1. Arithmetic Operators Already Discussed in Unit I 2. Relational Operators A Relational Operator is used to make comparisons between two expressions. These comparisons can be done with the help of relational operators. Each one of these operators compares its left hand side operand with its right hand side operand. ‘C’ supports six relational operators in all. These operators and their meaning are show in Table. Operator Meaning < is less than <= is less than or equal to > is greater than >= is greater than or equal to = = is equal to != is not equal to

description

 

Transcript of Programming in c unit 2 by K K Bohra Lachoo College

Page 1: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(1)

K K Bohra (LMSCT, 2014)

BCA I Year Semester I PROGRAMMING IN C

[BCA111]

Unit II Operators - relational, logical, bit wise, unary, hierarchy of operators. Control statements - if-else, nested if, switch case, goto and labels, looping statements - while, do-while and for, nested loops, break and continue. =====================================================================

»» Operators C support a rich set of operators. We have already used several of them, such as =, +,-, *, & and <. An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. . Operators are used in programs to manipulate data and variables. C operators can be classified into a number of categories, they include

1. Arithmetic Operator 2. Relational Operator 3. Logical Operator 4. Assignment Operators 5. Increment and Decrement Operators 6. Conditional Operators 7. Bitwise Operators 8. Special Operator.

1. Arithmetic Operators Already Discussed in Unit I 2. Relational Operators

A Relational Operator is used to make comparisons between two expressions. These comparisons can be done with the help of relational operators. Each one of these operators compares its left hand side operand with its right hand side operand. ‘C’ supports six relational operators in all. These operators and their meaning are show in Table.

Operator Meaning < is less than <= is less than or equal to > is greater than >= is greater than or equal to = = is equal to != is not equal to

Page 2: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(2)

K K Bohra (LMSCT, 2014)

• A simple relational expression contains only one relational operator and takes the following form.

• Expressions may be constant, variable or combinations of them. • Evaluated as Non-Zero and Zero

4.5<=10 True 4.5<-10 False -35 >= 0 False 10 <7+5 True ‘A’<64 False ‘B’>’A’ True Example: printf(“%d”,6>3); // True

printf(“%d”,2>31); // False

3. Logical Operators Any expression that evaluates to zero denotes a false logical condition, and that evaluating to non zero value denotes a True logical condition. C has three logical operators show in Table

Operator Meaning && Logical AND | | Logical OR ! Logical NOT

The first two operators && and | | are binary, whereas the exclamation (!) is a unary operator and is used to negate a condition. The result of logical operations when applied to operands with all possible values.

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

Example: printf(“%d”,6>3 && 5>2); // True

printf(“%d”,2>31 || 2>4); // False

Page 3: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(3)

K K Bohra (LMSCT, 2014)

4. Assignment Operators Assignment operators are used to assign the result of an expression to a variable. We have seen the usual assignment operator “=”. C has a set of ‘Shorthand’ assignment operators of the form Syntax: Variable operator = expression / constant / function Example: cnt = cnt + 10; total = 11; num = tot; in which the variable cnt on the left hand side is repeated immediately after = sign The operator += is compound assignment operator

Operator Usage Effect + = a + = exp; a = a + exp; - = a - = exp; a = a - exp; * = a * = exp; a = a * exp; / = a / = exp; a = a / exp; % = a % = exp; a = a % exp;

The statement Syntax: Variable = Variable operator (Expression) Example: x+=3; x=x+3 tab *=2; tab = tab+2;

Operator Example Explanation

Simple operator

= sum = 10 Value 10 is assigned to variable sum

Compound assignment

operator

+= sum+=10 This is same as sum = sum+10

-= sum – = 10 This is same as sum = sum – 10

*= sum*=10 This is same as sum = sum*10

/+ sum/=10 This is same as sum = sum/10

%= sum%=10 This is same as sum = sum%10

&= sum&=10 This is same as sum = sum&10

^= sum^=10 This is same as sum = sum^10

Page 4: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(4)

K K Bohra (LMSCT, 2014)

# include <stdio.h> int main() { int Total=0,i; for(i=0;i<10;i++) { Total+=i; // This is same as Total = Total+i } printf("Total = %d", Total); }

The use of shorthand assignment operators has three advantages 1. The statement is more concise and easier to read 2. The statement is more efficient 3. Appear on the left hand side need not be repeated and therefore it becomes easier to write. 5. Increment / Decrement Operators [++ / --] C offers two unusual and unique operators ++ and -- called increment and decrement operator respectively. The use of these two operators will results in the value of the variable being incremented or decremented by unity. i=i+1 can be written as i++ and j=j-1 can be written as j --. The operators can be place either before(Pre) or after(Post) the operand. Pre incrementing or pre decrementing or post incrementing or post decrementing have different effect when used in expression. pre incrementing or pre decrementing: If the operator is placed before the variable (++I or --I) it is known as pre incrementing or pre decrementing. post incrementing or post decrementing: If the operator is placed after the variable (I++ or I--) it is known as post incrementing or post decrementing. In the pre increment or pre decrement first the value of operand is incremented or decremented then it is assigned.

Example: x=100; y=++x;

After the execution the value of y will be 101 and the value of x will be 100.

Page 5: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(5)

K K Bohra (LMSCT, 2014)

In the post increment or post decrement first the value of operand is assigned to the concern variable and then the increment or decrements perform.

Example: x=100; Y=x++;

After the execution the value of y will be 100 and the value of x will be 101. Example #include<stdio.h> void main() {

int a,b,x=10,y=10; a = x++; b = ++y; printf("Value of a : %d",a); //10 printf("Value of b : %d",b); //11

} 6. Conditional Operators/ Ternary Operator [ ? : ] The conditional expression can be used as shorthand for some if-else statements. It is a ternary operator. This operator consist of two symbols: the question mark (?) and the colon (:). The general syntax of the conditional operator is:

Identifier = (test expression)? Expression1: Expression2;

This is an expression, not a statement, so it represents a value. The operator works by evaluating test expression. If it is true (non-zero), it evaluates and returns expression1. Otherwise, it evaluates and returns expression2. The classic example of the ternary operator is to return the smaller of two variables. Every once in a while, the following form is just what you needed. Instead of... if (x < y)

min = x; else

min = y; You just say... min = (x < y) ? x : y;

Page 6: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(6)

K K Bohra (LMSCT, 2014)

This is the only operator in C that makes use of three operands. It test condition corresponding to test expression, if it is true the value corresponding to Expression1 and it is false it corresponds to the value of Expression2. Example #include<stdio.h> int main() {

int num; printf("Enter the Number : "); scanf("%d",&num); flag = ((num%2==0)?1:0); if(flag==0) printf("\nEven"); else

printf("\nOdd"); } OR #include<stdio.h> int main() {

int num; printf("Enter the Number : "); scanf("%d",&num); (num%2==0)?printf("Even"):printf("Odd");

} 7. Bitwise Operators Bitwise operators operate on individual bits of integer (int and long) values. This is useful for writing low-level hardware or OS code where the ordinary abstractions of numbers, characters, pointers, and so on, are insufficient. Bit manipulation code tends to be less "portable". Code is "portable" if without any programmer intervention it compiles and runs correctly on different types of computers. The bit wise operations are commonly used with unsigned types. These operators perform bit wise logical operations on values. Both operands must be of the same type and width: the resultant value will also be this type and width.

Note: Bitwise operators operate on Integer and Character but not on float and double

Page 7: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(7)

K K Bohra (LMSCT, 2014)

Biwise operators are: ~ Bitwise Negation one's complement (unary) & Bitwise And | Bitwise Or ^ Bitwise Exclusive Or >> Right Shift by right hand side (RHS) (divide by power of 2) << Left Shift by RHS (multiply by power of 2) Definition of bitwise logical operators: Bit a Bit b a & b a | b a ^ b 0

~a 0 0 0 0 1

0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 1 0 0 Example: Bitwise Negation a=00000011 ~a =11111100

Bitwise And a = 00000011 b = 00010110 a&b=00000010

Bitwise Or a = 00000011 b = 00010110 a|b=00010111

Bitwise Exclusive Or a = 00000011 b = 00010110 a^b=00010101

Right Shift a = 0000 0011 = 3 (a<<=1) = 00000110 = 6 (a<<=2) = 00011000 = 24 (a<<=3) = 11000000 = 192

Left Shift a=11000000 =192 (a>>=1) = 01100000 = 96 (a>>=2) = 00011000 = 24 (a>>=3) = 0000 0011 = 3

Page 8: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(8)

K K Bohra (LMSCT, 2014)

»» Hierarchy of operators Operator Description Associativity

( )

[ ]

Parentheses (function call) (see Note 1)

Brackets (array subscript)

left-to-right

+ -

!

Unary plus/minus

Logical negation

right-to-left

* / % Multiplication/division/modulus left-to-right

+ - Addition/subtraction left-to-right

< <=

> >=

Relational less than/less than or equal to

Relational greater than/greater than or equal to

left-to-right

== != Relational is equal to/is not equal to left-to-right

&& Logical AND left-to-right

| | Logical OR left-to-right

=

+= -=

*= /=

%= &=

Assignment

Addition/subtraction assignment

Multiplication/division assignment

Modulus/bitwise AND assignment

right-to-left

, Comma (separate expressions) left-to-right

Parentheses are also used to group sub-expressions to force a different precedence; such parenthetical expressions can be nested and are evaluated from inner to outer.

Page 9: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(9)

K K Bohra (LMSCT, 2014)

»» Control statements (or Decision Making or Branching statements) C language supports the following statements known as control or decision making statements. 1. if statement 2. switch statement 3. conditional operator statement 4. goto statement These statements ate known as decision-making statement and these statements ‘control’ the flow of execution. They are also known as control statements. 1. If Statement: If Statement is a powerful decision making statement and is used to control the flow of execution of statement. It is not terminated by semicolon. If Statement may be implemented in different forms depending on the complexity of condition. condition(s) part may be combination of relational or logical operators.

a. Simple if statement. b. if…else statement. c. Nested if…else statement. d. else if ladder.

a. Simple if statement. Syntax/Variant Example if(<condition(s)>) stmt1; or if(<condition(s)>) { stmt1; }

if(<condition(s)>) { stmt1; stmt2; ... }

if(<condition(s)>) {

Page 10: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(10)

K K Bohra (LMSCT, 2014)

stmt1; ... } stmt2; if(NonZero Term/Constant) { stmt1; ... }

if(23) printf(“Sahi !”); if(2.2) printf(“Sahi !”); if(‘A’) printf(“Sahi !”); if(0) printf(“Sahi !”);

if(Expression) { stmt1; ... }

if(x=23) printf(“Sahi !”); if(x=0) printf(“Ghalat !”); x=-1; if(x++) printf(“Sahi !”); x=-1; if(++x) printf(“Ghalat !”);

b. if…else statement.

Syntax: If(<condition>) statement 1; else statement 2; Example:

# include <stdio.h> int main() { int i=1; if(i>10) printf("Greater than 10”); else printf(“Less than 10”); }

Example:

#include<stdio.h> int main() {

int mynumber; scanf("%d",&mynumber); if ( mynumber == 10 )

printf("Is equal\n"); return 0;

}

Page 11: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(11)

K K Bohra (LMSCT, 2014)

In the example above the user can input a number. The number is stored in the variable mynumber. Now take a look at the “if statement”: if the number stored in the variable mynumber is equal to ten, then print “is equal” on the screen. Simple, isn’t it. If the number is not equal to ten, then nothing gets printed. Now take another look at the “if statement”: look at the placement of the semi-colon. As you can see there is no semi-colon behind the “if statement”. If there is just one instruction (if the statement is true), you can place it after the“if statement” (with an indentation). Are multiple instructions necessary then you will have to use curly brackets, like so: if ( mynumber == 10) { printf("is equal\n"); printf("closing program\n"); } Now we like to also print something if the “if statement” is not equal. We could do this by adding another “if statement” but there is an easier / better way. Which is using the so called “else statement” with the “if statement”. #include<stdio.h> int main() { int mynumber; scanf("%d",&mynumber); if ( mynumber == 10 ) { printf("Is equal\n"); printf("Closing program\n"); } else { printf("Not equal\n"); printf("Closing program\n"); } return 0; } This is all done to make reading easier and to make less mistakes in large programs.

Take a look at the placement of the curly brackets and how the indentations are placed.

Page 12: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(12)

K K Bohra (LMSCT, 2014)

c. Nested if statements Syntax

if(<condidion(s)>) {

Stmt1; Stmt2; If(<condidion(s)>)

Stmt1; else

Stmt2; } else {

Stmt3; Stmt4; If(<condidion(s)>)

Stmt1; else {

Stmt2; Stmt3;

} }

If you use an “if statement” in an “if statement” it is called nesting. Nesting ”if statements” can make a program very complex, but sometimes there is no other way. So use it wisely. Take a look at a nested “if statement” example below: Example #include<stdio.h> int main() { int grade; scanf("%d",&grade); if ( grade <= 10 ) { printf("YOU DID NOT STUDY.\n"); printf("YOU FAILED ! \n"); } else { if ( grade < 60 ) { printf("You failed \n"); printf("Study harder\n"); } else

Page 13: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(13)

K K Bohra (LMSCT, 2014)

{ if ( grade >= 60 ) printf("YOU PASSED ! \n"); } } return 0; } So let’s walk through the example above: If the grade is equal or below ten, you did not study. If the grade is above ten, the program will go into the “else statement”. In the “else statement” there is another “if statement” (this is nesting). This “if statement” checks the grade again. If the grade is below sixty, you must study harder. In the “else statement” from this “if statement” there is another “if statement”. It checks whether the grade is above or equal to sixty. If it is, you passed the test. Multiple condition testing It is possible to test two or more conditions at once in an “if statement” with the use of the AND (&&) operator. Example: if ( a > 10 && b > 20 && c < 10 ) If a is greater then ten and b is greater then twenty and c is smaller then ten, do something. So all three conditions must be true, before something happens. With the OR ( || ) operator you can test if one of two conditions are true. Example: if ( a = 10 || b < 20 ) If a equals ten or b is smaller than twenty then do something. So if a or b is true, something happens.

Page 14: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(14)

K K Bohra (LMSCT, 2014)

d. Ladder if The else if ladder is a way of putting multiple ifs together when multipath decisions are involved. It is a one of the types of decision making and branching statements. A multipath decision is a chain of if’s in which the statement associated with each else is an if. The general form of else if ladder is as follows – Syntax if(<condidion(s)>) Stmt1; else if(<condidion(s)>) Stmt2; else if(<condidion(s)>) Stmt3; else if(<condidion(s)>) Stmt4; else

The switch statement is almost the same as an “if statement”. The switch statement can have many conditions. You start the switch statement with a condition. If one of the variable equals the condition, the instructions are executed. It is also possible to

Stmt5; This construct is known as the else if ladder. The conditions are evaluated from the top of the ladder to downwards. As soon as a true condition is found, the statement associated with it is executed and the control is transferred to the statement-x (skipping the rest of the ladder). When all the n conditions become false, then the final esle containing the default statement will be executed. Below is the sample C program of the if – else ladder statement in which the color is to be selected by using the if – else ladder – Note – C programming language is a structured language; so it will be better to form blocks in ‘if else ladder’ as this makes the programmer to understand the language better and reduces the confusion and chaos. Also it will make the others easy to understand your program. It is also necessary to align the opening and the closing braces of the block. 2. Switch statement A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

Page 15: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(15)

K K Bohra (LMSCT, 2014)

add a default. If none of the variable equals the condition the default will be executed. Syntax switch(expression) { case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements */ default : /* Optional */ statement(s

The following rules apply to a switch statement:

); }

• The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.

• You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

• The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.

• When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.

Page 16: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(16)

K K Bohra (LMSCT, 2014)

• When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.

• Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

• A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Example #include <stdio.h> int main () { /* local variable definition */ char grade = 'B'; switch(grade) { case 'A' : printf("Excellent!\n" ); break; case 'B' : case 'C' : printf("Well done\n" ); break; case 'D' : printf("You passed\n" ); break; case 'F' : printf("Better try again\n" ); break; default : printf("Invalid grade\n" ); } printf("Your grade is %c\n", grade ); return 0; } 4. goto label statement

A goto statement in C programming language provides an unconditional jump from the goto to a labeled statement in the same function. The goto requires a label in order to identify the place where the branch to be made. A label is any valid character constant, and must be followed by a colon. The label is placed immediately before the statement where the control is to be transferred.

Page 17: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(17)

K K Bohra (LMSCT, 2014)

The label: can be anywhere in the program either before or after the goto label; statement. goto breaks the normal sequential execution of the program. If the label: is before the statement goto label; a loop will be formed and some statement will be execution repeatedly. Such jump is known as a backward jump. On the other hand, if the label: is placed after the goto label; some statement will be skipped and the jump is known as a forward jump. NOTE: Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten so that it doesn't need the goto.

The syntax for a goto statement in C is as follows:

Syntax1: … goto label; s1; s2; … label: S3; S4;

… Example:

# include <stdio.h> void main() { int i=1; goto jump; printf("Great!”);

jump: printf(“Looser !”); }

Output : Looser !

Page 18: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(18)

K K Bohra (LMSCT, 2014)

Syntax2: … label: s1; s2; … goto label; S3; S4;

Example: # include <stdio.h> void main() { int i=1;

jump:

printf("Great!”); goto jump;

printf(“Looser !”); }

Output : Great ! Great ! Great ! Great !...

More Example: # include <stdio.h> void main() { int goals ; printf ( "Number of goals scored against India" ) ; scanf ( "%d", &goals ) ; if ( goals <= 5 )

goto sos; else {

printf ( "About time soccer players learnt C\n" ) ; printf ( "and said goodbye! adieu! to soccer" ) ; exit( ) ; /* terminates program execution */

} sos: printf ( "To err is human!" ) ; } Output: Number of goals scored against India 3 To err is human!

Page 19: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(19)

K K Bohra (LMSCT, 2014)

»» Looping statement There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages:

C programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail.

Loop Type Description while loop Repeats a statement or group of statements while a

given condition is true. It tests the condition before executing the loop body.

for loop Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

do...while loop Like a while statement, except that it tests the condition at the end of the loop body

Depending on the position of the control statement(condition) in the loop, a control structure may be classified two categories

1. entry-controlled loop 2. exit- controlled loop

In the entry-controlled loop, the loop conditions are tested before the start of the loop execution. If the conditions are not satisfied, then the body of the loop will not execute.

Page 20: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(20)

K K Bohra (LMSCT, 2014)

In the exit-controlled loop, the test is performed at the end of the body of the loop and therefore the body is execution unconditionally for the first time.

While Loop A while loop statement in C programming language repeatedly executes a target statement as long as a given condition is true. The While is an entry-controlled loop statement. The test condition is evaluated and if the condition is true, then the body of the loop is executed. After execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again. This process of repeated execution of the body continues unit the test condition finally becomes false and the control is transferred out of the body. Body of the loop has one or more statement. The braces are needed only if the body contains two or more statement.

Page 21: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(21)

K K Bohra (LMSCT, 2014)

Syntax1: while(<condition>)

statement1; Example:

i=1; while(i<=10)

printf(“%d”,i);

Syntax2: while(<condition>) {

statement1; statement2;

} Example:

i=1; while(i<=10) {

printf(“%d”,i); printf(“%d”,i++);

} More Example:

void main() {

int p, n, count ; float r, si ; count = 1 ; while ( count <= 3 ) {

printf ( "\nEnter values of p, n and r " ) ; scanf(“%d %d %f", &p, &n, &r ) ; si = p*n * r / 100 ; printf ( "Simple interest = Rs. %f", si ) ;

count = count +1;

} }

Output:

Page 22: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(22)

K K Bohra (LMSCT, 2014)

For Loop A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. The initial expression is initialized only once at the beginning of the for loop. Then, the test expression (condition) is checked by the program. If the test expression is false, for loop is terminated. But, if test expression is true then, the code block is executed and update expression (increment / decrement / …) is updated. Again, the test expression is checked. If it is false, loop is terminated and if it is true, the same process repeats until test expression is false

Here is the flow of control in for loop:

1. The init

2. Next, the

step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.

condition

3. After the body of the for loop executes, the flow of control jumps back up to the

is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.

increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.

Page 23: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(23)

K K Bohra (LMSCT, 2014)

4. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.

Note: A single instruction can be placed behind the “for loop” without the curly brackets.

Syntax1: for(<initialize>;<cond.>;<incr. or decr. or …>)

statement1;

Syntax2: for(<initialize>;<cond.>;<incr. or decr. or …>) {

statement1; statement2;

}

Syntax3: <initialize> for(;<cond.>;<incr. or decr. or …>) {

statement1; statement2;

} Syntax4:

<initialize> for(;<cond.>;) {

statement1; statement2; <incr. or decr. or …>

} Syntax5:

<initialize> for(;;) {

statement1; statement2; <incr. or decr. or …> <cond.> break;

}

Page 24: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(24)

K K Bohra (LMSCT, 2014)

Example1: for(i=1;i<=10;i=i+1)

printf(“%d”,i);

Example2: for(i=1;i<=10;i=i+1) {

printf(“%d”,i); printf(“%d”,i++);

}

Example3: i=1; for(;i<=10;i=i*2) {

printf(“%d”,i); }

Example4:

i=1; for(;i<=10;) {

printf(“%d”,i); i=i*2;

} Example5:

i=1; for(;;) {

printf(“%d”,i); if(i<=10) break; i=i*2;

} More Example

/* C program to display factorial of an integer*/ #include <stdio.h> int main() {

int n, count; unsigned int factorial=1; printf("Enter an integer: "); scanf("%d",&n); if ( n< 0)

Page 25: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(25)

K K Bohra (LMSCT, 2014)

printf("Error!!! Factorial of negative number doesn't exist."); else {

for(count=1;count<=n;++count) {

factorial*=count; } printf("Factorial = %lu",factorial);

} return 0;

} do while Loop Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming language checks its condition at the bottom of the loop. A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. At first codes inside body of do is executed. Then, the test expression(condition) is checked. If it is true, code inside body of do are executed again and the process continues until test expression becomes false (zero).

Note There is semicolon in the end of while (); in do...while loop.

Syntax1:

do {

statement1; statement2;

}while(<cond.>);

Page 26: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(26)

K K Bohra (LMSCT, 2014)

Example: /*Working of do...while statement*/ #include <stdio.h> int main() {

int sum=0,num; do {

printf("Enter a number\n"); scanf("%d",&num); sum+=num;

}while(num!=0);

printf("sum=%d",sum); return 0;

} Break and Continue There are two statements built in C, break; and continue; to interrupt the normal flow of control of a program. Loops perform a set of operation repeatedly until certain condition becomes false but, it is sometimes desirable to skip some statements inside loop and terminate the loop immediately without checking the test expression. In such cases, break and continue statements are used. break Statement In C programming, break is used in terminating the loop immediately after it is encountered. The break statement can also be used with conditional if statement.

Example

/*Working of break; break if user inputs -ve no.*/ # include <stdio.h> int main() {

float num,average,sum; int i,n; printf("Maximum no. of inputs\n"); scanf("%d",&n); for(i=1;i<=n;++i) {

printf("Enter n%d: ",i); scanf("%f",&num); if(num<0.0)

break; //for loop breaks if num<0.0

sum=sum+num;

Page 27: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(27)

K K Bohra (LMSCT, 2014)

} average=sum/(i-1); printf("Average=%.2f",average); return 0;

}

continue Statement It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements are used. For better understanding of how continue statements works in C programming. Analyze the figure below which bypasses some code/s inside loops using continue statement

Example

//Working of continue statement # include <stdio.h> int main() {

int i,num,product; for(i=1,product=1;i<=4;++i) {

printf("Enter num%d:",i); scanf("%d",&num); if(num==0)

continue; product*=num;

} printf("product=%d",product); return 0;

} Exit The function exit() will terminate the process that calls the exit. void exit ( int status ); On call the process will terminate normally. It will perform regular cleanup as normal for a normal ending process. Parameters: A status value returned to the parent process.

Page 28: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(28)

K K Bohra (LMSCT, 2014)

Return value: The argument status is returned to the host environment. Normally you say 1 or higher if something went wrong and 0 if everything went ok. For example exit(0) or exit (1). Example #include<stdio.h> void main() { int goals; printf("enter number of goals scored"); scanf("%d",&goals); if(goals<=5) goto sos; else { printf("hehe"); exit( ); } sos: printf("to err is human"); }

Page 29: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(29)

K K Bohra (LMSCT, 2014)

Programs for Loop

Fibonacci series in c

0, 1, 1, 2, 3, 5, 8 etc

/* Fibonacci Series c language */ #include<stdio.h> int main() { int n, first = 0, second = 1, next, c; printf("Enter the number of terms\n"); scanf("%d",&n); printf("First %d terms of Fibonacci series are :-\n",n); for ( c = 0 ; c < n ; c++ ) { if ( c <= 1 ) next = c; else { next = first + second; first = second; second = next; } printf("%d\n",next); } return 0; }

C program to print Floyd's triangle

1 2 3 4 5 6 7 8 9 10

#include <stdio.h> int main() { int n, i, c, a = 1; printf("Enter the number of rows of Floyd's triangle to print\n"); scanf("%d", &n); for (i = 1; i <= n; i++) { for (c = 1; c <= i; c++) { printf("%d ",a);

Page 30: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(30)

K K Bohra (LMSCT, 2014)

a++; } printf("\n"); } return 0; }

C program to reverse a number

#include <stdio.h> int main() { int n, reverse = 0; printf("Enter a number to reverse\n"); scanf("%d",&n); while (n != 0) { reverse = reverse * 10; reverse = reverse + n%10; n = n/10; } printf("Reverse of entered number is = %d\n", reverse); return 0; }

Palindrome Numbers

#include <stdio.h> int main() { int n, reverse = 0, temp; printf("Enter a number to check if it is a palindrome or not\n"); scanf("%d",&n); temp = n; while( temp != 0 ) { reverse = reverse * 10; reverse = reverse + temp%10; temp = temp/10; } if ( n == reverse ) printf("%d is a palindrome number.\n", n); else printf("%d is not a palindrome number.\n", n); return 0; }

Page 31: Programming in c unit 2 by K K Bohra Lachoo College

Programming in C [BCA I Sem] Unit II(31)

K K Bohra (LMSCT, 2014)

Factorial program in c

#include <stdio.h> int main() { int c, n, fact = 1; printf("Enter a number to calculate it's factorial\n"); scanf("%d", &n); for (c = 1; c <= n; c++) fact = fact * c; printf("Factorial of %d = %d\n", n, fact); return 0; }