‘C’ Programming Khalid Jamal
SCANF()
SCANF FOR FLOAT (REAL VALUES)
Example
Scanf – specification for strings %[characters] means that only the characters specified in the brackets are permissible in the input string %[^characters] does exactly the reverse, the characters specified after (^) are not permitted main() { int no; char address[80]; printf("Enter No. and Address: "); scanf("%d %[a-z]",&no, address); printf("%d %s", no, address); } Enter No. and Address: new delhi 110017 new delhi
Decision Making and Branching We know that C program is a set of statements which are normally executed in a sequential manner. Suppose, we need to change the order of execution of statements based on certain conditions or repeat a group of statements until certain condition is satisfied. This involves a kind of decision making to see whether a particular condition has occurred or not.
Decision Making Statements C language possesses decision making capabilities by supporting if statement switch statement Conditional operator statement goto statement These statements are popularly known as decision-making statements. Since these statements control the flow of execution, hence they are also called control statements
IF STATEMENT It is powerful two-way decision making statement, used along with an expression
IF Example PROBLEM Write a C Program to find that the given number is even or odd
Executed only when IF condition is true IF-ELSE Statement Executed only when IF condition is true
If-Else Sample ......... if(code == 1) x = x + 1; if(code == 2) Only IF Condition Using If-Else Condition ......... if(code == 1) x = x + 1; if(code == 2) y = y +1; ........ ......... if(code == 1) x = x + 1; else y = y +1; ........
Example Write a C program to find the small of two numbers using if-else statement
Applying De-Morgan Law While implementing decision statements, we often face situations where the logical NOT operator is applied to a compound logical expression like !(x&&y || !z). However, a positive logic is easy to apply. In those cases, we apply DE- MORGAN’s LAW Remove parenthesis by applying NOT operator to every logical expression, while complementing relational operator
Example !(x&&y || !z) That is x becomes !x !x becomes x && becomes || || becomes && Ex !(x && y || !z) becomes !x || !y && z !(x <=0 || !condition) becomes x>0 && condition
Nesting of If-Else Statement When a series of decisions are involved, we may have to use more than one if…else statement in nested form. If condition-1 is false, statement-3 will be executed otherwise it continues to perform second test. If condition -2 is true, statement-1will be evaluated; otherwise statement-2will be evaluated and then control is transferred to statement-x
Example of Nested If-Else (Flow-chart)
Find Largest of 3 numbers using nested if-else
Sample program Write a C program to find largest of 3 numbers using nested if-else with the help of given flow chart
Dangling Else Problem One of the classic problem encountered when we start using nested if…else statements is dangling else. This occurs when a matching else is not available for an if. The answer is very simple, always match an else to the most recent unmatched if in the current block. In some cases, false condition may not be required, in that case else can be omitted. NOTE else is always paired with most recent unpaired if
Dangling Else Problem (contd.)
Dangling Else Problem (contd.)
The Else-If Ladder There is another way of putting if’s together when multiple decisions have to be taken. In that case, chain of if’s in which statement associated with each else is an if. This construct is known as the else if ladder. The conditions are evaluated from the top, downwards. As soon as true condition is found, statement associated with it is executed and control is transferred to statement-x (skipping rest of the ladder)
Else-If Ladder Flowchart if(marks >= 75) grade="honors"; else if (marks >= 60) grade="first division"; else if (marks >=45) grade="second division"; else if (marks >=30) grade="third division"; else grade="fail"; printf ("%s", grade);
Sample Program Consumption Units Rate of Charge 0-200 An electric distribution company charges its domestic consumer as follows Write a C program which reads no. of units consumed and give amount to be paid by customer using else-if ladder. 150, 225, 375, 520, 625 Consumption Units Rate of Charge 0-200 Rs. 0.50 per unit 201-400 Rs. 100 + Rs. 0.65 per unit 401-600 Rs. 200 + Rs. 0.85 per unit 601 and above Rs. 400 + Rs. 1.00 per unit
Indentation Rules Align vertically else clause with their matching if clause Use braces on separate lines to identify block of statements Indent the statements to the right inside the braces Align the opening and closing braces Use appropriate comments to signify the beginning and end of code blocks Code only one clause or statement in one line
Indentation Rules Sample
The switch statement When one of many alternatives to be selected, we can use if statement to control the selection. However, complexity of such a program increases dramatically when number of alternatives increases. The program becomes difficult to read and follow. C has a in-built multi-way decision statement known as switch. The switch tests value of given variable (or expression) against a list of case values, when a match is found, block of statement associated with that case is executed
Switch Sample, BREAK & DEAFULT BREAK statement is used to exit from loop or switch and control is passed to the first statement beyond loop or switch. BREAK statement is optional. Two or more case labels may follow same statements. DEFAULT label is also optional. If present executed only when no matching case is found. There can be only 1 default.
Switch Case Example index=marks/10; switch(index) { case 10: case 9: case 8: grade=“honours”; break; case 7: case 6: grade=“first div”; break; case 5: grade=“sec. div”; break; case 4: grade=“third div”; break; default: grade=“fail”; } printf(“%s”, grade);
The ? : Operator The C language has an unusual operator, useful for making two-way decisions. The combination of ? : popularly known as conditional operator (ternary operator)
Examples y = (x > 2) ? (2 * x +5) : (1.5 * x + 3) The conditional operator may be nested for evaluating more complex assignment decisions 4x + 100 for x < 40 Salary = 300 for x = 40 4.5x + 150 for x > 40 This complex equation can be written as salary = (x != 40) ? ((x<40) ? (4*x + 100) : (4.5*x + 150)) : 300;
Example (contd.) The same can be evaluated using if…else statements IF (X <= 40) IF (X < 40) SALARY = 4 * X +100; ELSE SALARY = 300; ELSE SALARY = 4.5 * X +150;
The 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 unconditionally. In its general form, the goto statement is written as goto label; where the label is an identifier that is used to label the target statement to which the control is transferred. Control may be transferred to anywhere within the current function. Each labeled statement within the function must have a unique label, i.e., no two statement can have the same label.
GOTO EXAMPLE
Decision Making and Looping Suppose we need to calculate sum of squares of all integers between 1 and 10. We can write program using if & goto statements Initializes the variable n. Computes square of n and add to sum Test the value of n to check whether it is equal to 10 or not. If it is equal to 10, then print the result. If n<10, increment by one and compute again. loop N = 10 end of loop
Looping & Its Structure Loops are used to execute a block of code several times There are 3 types of loops in C While Do-while For loop
While Loop
Flow Chart of While Loop
Example of While Loop Output 1 2 3 4 5 6 7 8 9
Problem Y=Xn N is positive integer Write a C program to evaluate the equation using while loop Y=Xn N is positive integer
Solution
Do-while statement A do-while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested.
Flow Chart of Do-While
Do-While Example
Another Example
While versus Do-While
While versus Do-While
Problem Write a C Program to find and print first n – Fibonacci numbers using do-while loop 1 1 2 3 5 8 13 21 Write a C program to find factorial of number n using while loop
For Loop Like While loop, for loop is entry controlled loop. i.e. conditions are checked if found true then and then only code is executed
Working The initialization statement is executed only once at the beginning of the for loop. Then the test expression is checked by the program. If the test expression is false, for loop is terminated. But if test expression is true then the code/s inside body of for loop is executed and then update expression is updated. This process repeats until test expression is false.
Flow Chart
Problem Write a C program to find factorial of number n using while loop Write Programs to print following output using for loops
Some More Problems
Factorial using while loop
Factorial using for loop
Fibonacci Series using while loop
Fibonacci Series using for loop
C Program to print right triangle using for loop Expected Output Actual Output
C Program to print number pattern Expected Output Actual Output
C Program to print simple triangle
C Program to print Upside Down Triangle
C Program to print hollow diamond
Problems
One MORE PROBLEM