Problem Solving and 'C' Programming

Similar documents
Problem Solving and 'C' Programming

Problem Solving and 'C' Programming

Chapter 4. Flow of Control

Flow Control. CSC215 Lecture

COMP 208 Computers in Engineering

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Introduction. C provides two styles of flow control:

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Dept. of CSE, IIT KGP

CHAPTER 9 FLOW OF CONTROL

MODULE 2: Branching and Looping

REPETITION CONTROL STRUCTURE LOGO

3 The L oop Control Structure

Structured Programming. Dr. Mohamed Khedr Lecture 9

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

n Group of statements that are executed repeatedly while some condition remains true

Loops / Repetition Statements

Course Outline Introduction to C-Programming

Lecture 7 Tao Wang 1

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Computers Programming Course 7. Iulian Năstac

Decision Making -Branching. Class Incharge: S. Sasirekha

C Programming Class I

Lecture 10. Daily Puzzle

CHAPTER : 9 FLOW OF CONTROL

Algorithms, Data Structures, and Problem Solving

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

M1-R4: Programing and Problem Solving using C (JAN 2019)

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control

Lecture 6. Statements

Chapter 5: Control Structures

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Module 4: Decision-making and forming loops

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

CS1100 Introduction to Programming

BCA-105 C Language What is C? History of C

Computers in Engineering. Moving From Fortran to C Part 2 Michael A. Hawker

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

Computers in Engineering COMP 208. Roots of a Quadratic in C 10/25/2007. Moving From Fortran to C Part 2 Michael A. Hawker

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Second Term ( ) Department of Computer Science Foundation Year Program Umm Al Qura University, Makkah

Sudeshna Sarkar Dept. of Computer Science & Engineering. Indian Institute of Technology Kharagpur

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

4.1. Structured program development Overview of C language

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Unit 3 Decision making, Looping and Arrays

from Appendix B: Some C Essentials

Example: Monte Carlo Simulation 1

Introduction to C/C++ Lecture 3 - Program Flow Control

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -CONTROL FLOW : LOOP- SPRING 2015, SEON-JU AHN, CNU EE

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Programming for Engineers Iteration

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

CSE 130 Introduction to Programming in C Control Flow Revisited

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

A Look Back at Arithmetic Operators: the Increment and Decrement

Unit 5. Decision Making and Looping. School of Science and Technology INTRODUCTION

Java Basic Programming Constructs

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

C Programming Basics

Course Title: C Programming Full Marks: Course no: CSC110 Pass Marks: Nature of course: Theory + Lab Credit hours: 3

Assignment: 1. (Unit-1 Flowchart and Algorithm)

SELECTION STATEMENTS:

Day06 A. Young W. Lim Wed. Young W. Lim Day06 A Wed 1 / 26

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

CS10001: Programming & Data Structures. Dept. of Computer Science & Engineering

Programming for Electrical and Computer Engineers. Loops

Fundamentals of Computer Programming Using C

C: How to Program. Week /Mar/05

LESSON 6 FLOW OF CONTROL

Princeton University Computer Science 217: Introduction to Programming Systems The Design of C

I BCA[ ] SEMESTER I CORE: C PROGRAMMING - 106A Multiple Choice Questions.

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

IS12 - Introduction to Programming Lecture 12: Loops and Tables. Relational Operators > < >= <=

Introduction to C Language

Maltepe University Computer Engineering Department. Algorithms and Programming. Chapter 4: Conditionals - If statement - Switch statement

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

Theory of control structures

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

C Programming Decision Making

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

Unit 3. Operators. School of Science and Technology INTRODUCTION

Technical Questions. Q 1) What are the key features in C programming language?

C - Basic Introduction

Repetition Structures II

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

C Program. Output. Hi everyone. #include <stdio.h> main () { printf ( Hi everyone\n ); }

Internet & World Wide Web How to Program, 5/e by Pearson Education, Inc. All Rights Reserved.

Transcription:

Problem Solving and 'C' Programming Targeted at: Entry Level Trainees Session 05: Selection and Control Structures 2007, Cognizant Technology Solutions. All Rights Reserved. The information contained herein is subject to change without notice. C3: Protected

About the Author Created By: Jeyshankar Perumal (125623) Credential Information: Version and Date: Technical Skills: UNIX/C/C++/Oracle Experience: 8.5 Years PSC/PPT/1107/1.0

Icons Used Questions Tools Hands on Exercise Coding Standards Test Your Understanding Reference Try it Out A Welcome Break Contacts

Problem Solving and 'C' Programming Session 05: Overview Introduction: This session explains the various program constructs (statements) available in C. These program constructs are used to process the input data to output data.

Problem Solving and 'C' Programming Session 05: Objective Objective: After completing this Session you will be able to:» Write a simple program» Write program using conditional statements» Write program using looping and iteration

Basic Program Constructs The basic program constructs in C are statements and functions. Statements in C:» Simple statement: An expression becomes statement when it is followed by a semicolon (;) Example: a = 8; c = a + b; ; /*Null statement*/

Basic Program Constructs (Contd.)» Compound Statements / Blocks: Compound statements are used to group statements into an executable unit. It consists of one or more individual statements enclosed within the braces {}.

Sequence The statements in the program are executed in sequence by default. For example a program which consists of only declaration statements, input-output statements, and one or more simple expression statements are executed in a sequential manner. The order of execution can be changed by the use of selection and control statements.

Selection Selection statements are used to alter the normal sequential flow of control. It provides the ability to decide the order of execution. Selection constructs in C:» if statement» Conditional / ternary operator statement (? :)» switch statement

if Statement The if statement allows you to establish decision-making into your programs. Programs may require certain logical test to be carried out at some particular point. The tests and subsequent decisions are made by evaluating a given expression as either true (non zero) or false (zero). An expression may involve arithmetic, relational, logical operators.

if Statement (Contd.) The if statement has three basic forms:» Simple if-else» Nested if» if-else if ladder

Simple if-else Statements Syntax: if (expression) { statements1; } else { statements2; } Expression can be arithmetic, logical, relational expression or a variable. The else part is optional.

Simple if-else Statements (Contd.) Following is the example of simple if-else statement: if (a<b) max = b; else max = a; printf( max = %d,max);

Short-circuit Evaluation Whenever the expression using && and are evaluated, the evaluation process stops as soon as the outcome, true or false is known. For example:» expr1 && expr2 If the value of expr1 is zero, the evaluation of expr2 will not occur (0 AND anything is 0)» expr1 expr2 If expr1 has non-zero value, the evaluation of expr2 will not occur (1 OR anything is 1)

Nested if Statement if statement can contain another if statement in its body. Syntax: if (expression) { statements1; if (expression) statements-1; } else { statements2; if (expression) statements-2; }

Nested if Statement: Example Program to find the maximum of 3 numbers: if (a>b) if (a>c) printf( largest = %d, a); else printf( largest = %d, c); else if (c>b) printf ( largest = %d, c); else printf ( largest = %d, b);

if else if Ladder Statement Syntax: if (expression) statements1; else if (expression) statements2; else if (expression) statements3; else statements4;

if else if Ladder Statement (Contd.) Example: if (mark >= 75) printf( Honours\n ); else if(mark >=60) printf( First Class\n ); else if (mark >=50) printf( Second Class\n ); else if (mark >=45) printf( Third Class\n ); else printf( Fail\n );

Conditional Operator Statement Efficient form for expressing simple if statements. It takes 3 expressions / operands. Syntax: [variable =] expr1? expr2: expr3; This simply states: if (expr1 is true) then expr2 else expr3

switch Statement It is a multiway conditional statement generalizing the if-else statement. A switch statement allows a single variable to be compared with several possible case labels which are represented by constant values. If the variable matches with one of the constants, then an execution jump is made to that point.

switch Statement (Contd.) Syntax: switch (expression) { case item 1: statement 1; break; case item 2: statement 2; break; case item n: statement n; } default : break; statement;

switch Statement (Contd.) expression may contain a constant value, variable, array variable, pointer variable, or any expression but must be an integer valued expression. Items which represent the case labels must be an integer constant or character constant. Default case is optional. The break is needed to terminate the switch after the execution of particular choice. Otherwise the next case would get evaluated.

switch Statement: Example switch (op) { case + : } case - : case * : case / : default: c=a + b; break; c=a - b; break; c=a * b; break; c=a / b; break; printf ( Invalid operator );

Iteration Real world applications require some set of instructions that loops within the program, performing repetitive actions on a stream of data. C supports following loop statements:» for statement» while statement» do-while statement

for Statement This statement is used to repeat a statement or a set of statements until some condition satisfied. Syntax: for (exp1; exp2; exp3) { } statement / block of statements;

for Statement: Valid Examples for (x=0; ((x>3) && (x<9)); x++) for (x=0, y=4; ((x>3) && (y<9)); x++, y+=2) for (x=0, y=4, z=4000; z ; z/=10) for (;c<=20;c=c+2) for (c=2;;++c) /*infinite loop*/ for (;c<=20;) for (;;) /*infinite loop*/

Nested for Statement There are many situations in which it is very convenient to have a loop contained within another loop. Such loops are called nested loops. For each and every iteration through the outer loop, the inner loop runs completely.

Nested for Statement (Contd.) Example: for (i=1;i<=3;i++) { } printf( \n i = %d,i); for (j=1;j<=3; j++) printf ( \n j = %d,j); j is the inner loop variable and i is the outer loop variable.

while Statement The while is an entry controlled loop statement. Syntax: while (expression) { Statements; } Expression can be a constant value, variable or any expression. As long as the expression is true, the body of the loop is executed repeatedly.

while Statement (Contd.) Example: 1.while(x--){ }; 2.while(x = x+1){ }; 3.while(x) { }; 4.while(1); 5.while ( (ch = getche( ))!= q ) putchar(ch);

do while Statement The do.. while is an exit controlled loop statement. Syntax: do { statement (s); }while (expression); The body of the loop is executed at least once, even though the expression is false for the first time.

do while Statement (Contd.) Example: int d=1; do { printf ( %d \n, d); ++d; } while (d<=10);

break Statement break statements causes the execution of the current enclosing switch case or loop to terminate. Example: for(loop=0;loop<50;loop++) { } if (loop==10) break; /*control will come out*/ /*of the loop.*/ printf("%d\n",loop); only numbers 0 through 9 are printed.

continue Statement continue statement is used to terminate the current iteration and to continue the loop with the next iteration. Example: for (loop=0;loop<100;loop++) { } if (loop==50) continue; printf ("%d\n",loop); The numbers 0 through 99 are printed except 50.

exit() Terminates the program. Syntax: void exit( int status) Before terminating the program, it performs the following tasks:» Closes all files» Writes buffered output» Call any registered exit function Status can be EXIT_SUCESS (normal termination) or EXIT_FAILURE (abnormal termination)

Q & A Allow time for questions from participants

Try it Out - 1 Problem Statement: Write a program to print temperature in Celsius and Fahrenheit starting from 0 F incremented by 20F up to 300 fahrenheit

Try it Out - 1 (Contd.) Code: #include <stdio.h> main() { int lower, upper, step; float fahr, celsius; lower = 0 ; upper = 300; step = 20 ; fahr = lower; } while ( fahr <= upper ) { celsius = (5.0 / 9.0) * (fahr - 32.0); printf("%4.0f %6.1f\n", fahr, celsius); fahr = fahr + step; } getchar(); Refer File Name : <ses5_1.c> for soft copy of the code

Try it Out - 1 (Contd.) How it Works: When the Program is run, The lower, upper and step variables are initialised to 0,300 and 20 Assigns the lower value to fahr variable, find out the celsius using the formula 5/9*(fahr-32) Print both celsius and fahrenheit value for 0F Increment the Fahr to 20 and again apply formula to find equivalent celsius value. The above step continues till the fahr value is greater than the upper value say 300

Q & A Allow time for questions from participants

Test Your Understanding 1. What will be the output of the following code? x=6; if (x=7) printf ( valid ); else printf ( invalid ); 2. What will be the output of the following code? a=10; (a % 2)? printf ( %d - Even,a+1) : printf ( %d Odd, a+1);

Test Your Understanding (Contd.) 3. How many asterisks will be printed if the following code is executed with x=2? switch (x) { } case 1: printf( * \n ); case 2: printf( ** \n ); case 3: printf( *** \n ); case 4: printf( **** \n );

Test Your Understanding (Contd.) 4. How many times the body of each loop will be executed? a) int i; for (i=0;i<=5;i=i+2/3) { ----; ----; } b) int m=10,n=7; while (m % n >=0) { ----; m=m+1; n=n+2; ---- }

Practice Exercises 1. Write a C program to check whether the given number is a Prime number. 2. Write a C program to find the sum of digits of a given number. 3. Write a program which accepts a number n, and then finds the sum of the integers from 1 to 2, then from 1 to 3, and so forth until it displays the sum of the integers from 1 to n.

Problem Solving and 'C' Programming Session 05: Summary if statement is a condition based decision making statement. Ternary operator is more efficient form for expressing simple if statements. switch statement is a conditional control statement that allows some particular group of statements to be chosen from several available groups. Looping allows the program to repeat a section of code any number of times or until some condition occurs. for, while, and do-while statements are repetitive control structures available in C, that are used to carry out conditional looping. break statement is used to terminate the current loop but continue statement skips the current iteration and continues the loop with the next iteration.

Problem Solving and 'C' Programming Session 05: Source C Reference Card (ANSI) C Reference Manual by Dennis Ritchie Programming in C: A Tutorial by Brian W. Kernighan, Bell Laboratories Byron Gottfried, Programming in C, Tata McGraw Hill Deitel & Deitel, C How to Program, Third Edition, Prentice Hall Disclaimer: Parts of the content of this course is based on the materials available from the Web sites and books listed above. The materials that can be accessed from linked sites are not maintained by Cognizant Academy and we are not responsible for the contents thereof. All trademarks, service marks, and trade names in this course are the marks of the respective owner(s).

You have completed the Session 05 of Problem Solving and 'C' Programming 2007, Cognizant Technology Solutions. All Rights Reserved. The information contained herein is subject to change without notice.