‘C’ Programming Khalid Jamal.

Slides:



Advertisements
Similar presentations
Control Statements. Define the way of flow in which the program statements should take place. Control Statements Implement decisions and repetitions.
Advertisements

1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
UNIT II Decision Making And Branching Decision Making And Looping
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
The University of Texas – Pan American
Spring 2005, Gülcihan Özdemir Dağ Lecture 3, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 3 Outline 3.1 Introduction.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Structural Program Development: If, If-Else Outline.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
CPS120: Introduction to Computer Science Decision Making in Programs.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Lecture 2: Logical Problems with Choices. Problem Solving Before writing a program Have a thorough understanding of the problem Carefully plan an approach.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
Decision making statements. Decision making statements are used to skip or to execute a group of statements based on the result of some condition. The.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
Control Statements in C 1.Decision making statements 2.Looping statements 3.Branching statements
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Decision Making and Branching (cont.)
Control Flow Statements
CPS120: Introduction to Computer Science Decision Making in Programs.
Decision Making and Branching
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied. Suppose you want to execute some code/s 10 times.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 3 Structured Program Development in C C How to Program, 8/e, GE © 2016 Pearson Education, Ltd. All rights reserved.1.
Chapter 4 – C Program Control
CNG 140 C Programming (Lecture set 3)
The if…else Selection Statement
REPETITION CONTROL STRUCTURE
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Statements (6 of 6) A statement causes an action to be performed by the program. It translates directly into one or more executable computer instructions.
Lecture 3- Decision Structures
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Relational Operators A relational operator compares two values. The values can be any built-in C++ data type, such as Character Integer Floating point.
Quick Test What do you mean by pre-test and post-test loops in C?
Programming Fundamentals
Programming Fundamentals
Chapter 6: Conditional Statements and Loops
JavaScript: Control Statements.
JavaScript: Control Statements I
Control Structures.
Arrays, For loop While loop Do while loop
Lecture 2: Logical Problems with Choices
Chapter 4: Control Structures I (Selection)
CS1100 Computational Engineering
Structured Program
Chapter 6 Decision Making and Looping
Chapter 4 - Program Control
Loops in C.
CSC215 Lecture Control Flow.
Week 3 – Program Control Structure
Chapter8: Statement-Level Control Structures April 9, 2019
Chap 7. Advanced Control Statements in Java
CSC215 Lecture Control Flow.
REPETITION Why Repetition?
Structural Program Development: If, If-Else
Presentation transcript:

‘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