More examples for Control statements

Similar documents
UIC. C Programming Primer. Bharathidasan University

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

Computer Programing. for Physicists [SCPY204] Class 02: 25 Jan 2018

DECISION CONTROL AND LOOPING STATEMENTS

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

Midterm Exam. CSCI 2132: Software Development. March 4, Marks. Question 1 (10) Question 2 (10) Question 3 (10) Question 4 (10) Question 5 (5)

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

Assoc. Prof. Dr. Tansu FİLİK

EECE.2160: ECE Application Programming Spring 2018

EECE.2160: ECE Application Programming Fall 2017

EECE.2160: ECE Application Programming Spring 2016 Exam 1 Solution

Decision Making -Branching. Class Incharge: S. Sasirekha

Chapter 2. Section 2.5 while Loop. CS 50 Hathairat Rattanasook

Introduction. C provides two styles of flow control:

{C} Programming. Part 1/2 Basics Variables, Conditions, Loops, Arrays, Pointer basics

Decision Making and Loops

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

Week 4 Selection Structures. UniMAP Sem II-11/12 DKT121 Basic Computer Programming 1

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

Worksheet 4 Basic Input functions and Mathematical Operators

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

Programming for Electrical and Computer Engineers. Loops

Q1: Multiple choice / 20 Q2: C input/output; operators / 40 Q3: Conditional statements / 40 TOTAL SCORE / 100 EXTRA CREDIT / 10

Copy: IF THE PROGRAM or OUTPUT is Copied, then both will have grade zero.

Control Structure: Loop

Programming Language A

Branching is deciding what actions to take and Looping is deciding how many times to take a certain action.

Government Polytechnic Muzaffarpur.

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

Module 4: Decision-making and forming loops

Conditional Statement

Laboratory 4. INSTRUCTIONS (part II) I. THEORETICAL BACKGROUND

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Dr. R. Z. Khan, Associate Professor, Department of Computer Science

Problem # 1. calculate the grade. Allow a student the next grade if he/she needs only 0.5 marks to obtain the next grade. Use else-if construction.

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

PESIT Bangalore South Campus Hosur Road (1km before Electronic City), Bengaluru Department of Basic Science and Humanities

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

Q1: C input/output; operators / 46 Q2: Conditional statements / 34 Q3: While and do-while loops / 20 TOTAL SCORE / 100 Q4: EXTRA CREDIT / 10

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

SELECTION STATEMENTS:

Chapter 5: Control Structures

Introduction to Programming

Computer Programming. Decision Making (2) Loops

16.216: ECE Application Programming Fall 2013

Engineering 12 - Spring, 1998

Comments. Comments: /* This is a comment */

Lecture 6. Statements

CSE 5A Introduction to Programming I (C) Homework 4

Computers Programming Course 7. Iulian Năstac

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

What we have learned so far

16.216: ECE Application Programming Fall 2015 Exam 1 Solution

BSM540 Basics of C Language

Assoc. Prof. Dr. Tansu FİLİK

C: How to Program. Week /Mar/05

Precedence and Associativity Table. % specifiers in ANSI C: String Control Codes:

PDS: CS Computer Sc & Engg: IIT Kharagpur 1. for Statement

BRANCHING if-else statements

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

& Technology. Expression? Statement-x. void main() int no; scanf("%d", &no); if(no%2==0) if(no%2!=0) Syllabus for 1. of execution of statements.

'C' Programming Language

CMSC 104 -Lecture 11 John Y. Park, adapted by C Grasso

UNIT 4. CONTROL FLOW. Programming Year Grade in Industrial Technology Engineering. Paula de Toledo. David Griol

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

Dalhousie University CSCI 2132 Software Development Winter 2018 Midterm Examination II March 12 15:37-16:24

Manju Muralidharan Priya. CS4PM Web Aesthetics and Development WEEK 12

Slides adopted from T. Ferguson Spring 2016

Concept of algorithms Understand and use three tools to represent algorithms: Flowchart Pseudocode Programs

Subject: PIC Chapter 2.

Introduction to Programming

Decision Making and Branching

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

C Programming. The C Preprocessor and Some Advanced Topics. Learn More about #define. Define a macro name Create function-like macros.

Assoc. Prof. Dr. Tansu FİLİK

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Chapter 3: Arrays and More C Functionality

CS 314 Principles of Programming Languages. Lecture 9

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

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015

Q1: Multiple choice / 20 Q2: C input/output; operators / 40 Q3: Conditional statements / 40 TOTAL SCORE / 100 EXTRA CREDIT / 10

Functions Introduction to Algorithms and Programming II School of Computer Science Term: Summer 2013 Instructor: Dr. Asish Mukhopadhyay

University of California San Diego Department of Electrical and Computer Engineering. ECE 15 Midterm Exam

16.216: ECE Application Programming Fall 2011

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

Introduction to Computing Lecture 07: Repetition and Loop Statements (Part II)

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Basic Science and Humanities

Example: Structure, Union. Syntax. of Structure: struct book { char title[100]; char author[50] ]; float price; }; void main( )

UNIVERSITY OF WINDSOR Fall 2007 QUIZ # 2 Solution. Examiner : Ritu Chaturvedi Dated :November 27th, Student Name: Student Number:

Practice Sheet #07 with Solutions

ESC 101N: Fundmentals of Computing ( IInd Semester) Mid Sem II Examination PM, Monday 7th March, 2011

AMCAT Automata Coding Sample Questions And Answers

ECET 264 C Programming Language with Applications

Flow Control. CSC215 Lecture

NCSU ECE 209 Sections 602 Exam 1 Fall September, I have neither given not received unauthorized assistance on this test.

UNIT 2 PROBLEMS SOLVING USING C PROGRAMMING LANGUAGE

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

Transcription:

More examples for Control statements C language possesses such decision making capabilities and supports the following statements known as control or decision-making statements. 1. if statement 2. switch statement 3. Conditional operator statement if Statement The if statement is a powerful decision making statement and is used to control the flow of execution of statements. It is basically a two-way decision statement and is used in conjunction with an expression. Syntax Example main() int x=5; if (x > 1) x=x+10; printf("%d", x); if (conditional) block of statements executed if conditional is true; else block of statements if condition false; if else statement The if...else statement is an extension of the simple if statement. The general form is

if (condition) True-block statement(s); else False-block statement(s); If the condition is true, then the true-block statement(s), immediately following the if statement are executed; otherwise the false-block statement(s) are executed. void main(void) int a, b; char ch; printf("choice:\n"); printf("(a) Add, (S) Subtract, (M) Multiply, or (D) Divide?\n"); ch = getchar( ); /* getchar() is function which read only one character and assign it to ch */ printf("\n"); printf("enter a: "); scanf("%d", &a); printf("enter b: "); scanf("%d", &b); if(ch=='a') printf("%d", a+b); else if(ch=='s') printf("%d", a-b); else if(ch=='m') printf("%d", a*b); else if(ch=='d' && b!=0) printf("%d", a/b); if-else-if statement : (Example) void main(void) int numb; printf("type any Number : "); scanf("%d", &numb); if(numb > 0) printf("%d is the positive number", numb);

else if(numb < 0) printf("%d is the Negative number", numb); else printf("%d is zero",numb); Switch Statement: The switch and case statements help control complex conditional and branching operations. The switch statement transfers control to a statement within its body. Syntax: switch (expression) case item_1: case item_2: case item_n: default: statements; statements; statements; statement; /* next statement in sequence will be executed after any break */ item_1, item_2,.item_n are fixed integer or character or any enumerated values, and not variable names.

Example: #include <stdio.h> main( ) int numb; printf( Type any Number: ); scanf( %d,&numb); switch(numb % 2) /* selector can be an expression or just one variable*/ case 0 : printf("the number %d is even \n", numb); case 1 : printf("the number %d is odd \n", numb); /* note that default is optional */ Ternary condition The? (ternary condition) operator is a more efficient form for: expressing simple if statements. It has the following form (expression and not a complete statement): expression1? expression2 : expression3 Example: (Assignment statement) int a=5; int b=13; int res; res = (a>b)? a : b; if a is greater than b (is true) then res has the value of: a else the: res has value of b. Example: printf("%s\n", grade>60? "passed" : "failed"); It means: if grad > 60 then print "passed" else print "failed"

break statement break statement is used to exit from a loop or a switch, control passing to the first statement beyond the loop or a switch. With loops, break can be used to force an early exit from the loop, or to implement a loop with a test to exit in the middle of the loop body. A break within a loop should always be protected within an if statement which provides the test to control the exit condition.) Example (Program segment) for(i=0;i<=10;i++) if(i==5) printf( \n%d,i); /* next statement in sequence */ Output: 0 1 2 3 4 continue statement: Continue is similar to the break statement but it only works within loops where its effect is to force an immediate jump to the loop control statement.

Like a break, continue should be protected by an if statement. Example: ( program segment ) for(i=0;i<10;i++) /* start of loop */ if(i==5) continue; /* when i=5 continue to end of loop and continue loop from to 6*/ printf( \n%d,i); /* if i==5 branch to this point and continue the loop until end loop Output: 0 1 2 3 4 6 7 8 9 terminated successfully */

Homework-2 ( Prof. Dr. Yahia Halabi) You should submit it before exam-1 (Maximum: 12 PM 5 PM)- one week after the first exam scheduled to you ( exactly next Thursday)). Multiway selection means switch statements in C: The general format of a switch statement is as follows: switch (expression) case value : statements; case value : statements; //as many more such cases as needed default : statements; //the open-end option An example of program with switch statements in C: Now write another program in C language, which demonstrates the use of switch statement. For this type, using the build-in text editor, a program in C language, named char_id.c. Here is the listing of this C program, after it is typed in and ready for running: // This C program named char_id.c is to recognise a char using switch stmt // Author... (type here your name) // Date... (type here the current date) // For... (institution, course, purpose) //--------------------------------------------------------------------------- #include <stdio.h> //Handles the keyboard input and screen output void main( ) char input_ch; printf("\nthis program recognizes a character being typed\n"); scanf ("%c", &input_ch);

printf ("\n"); switch (input_ch) case '+': printf("this is the add operator.\n"); case '-': printf("this is the minus operator.\n"); case '*': printf("this is the multiply operator.\n"); case '/': printf("this is the divide operator.\n"); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': printf ("The character typed is a digit.\n"); case 'A': case 'E': case 'I': case 'O': case 'U': case 'a': case 'e': case 'i': case 'o': case 'u': case '\n':case '\t': case ' ': case '\v': case '\f': printf ("The character typed is a control one.\n"); default : printf("this is an unidentified char.\n"); printf("\nthank you for using this program. BYE!\n"); Run this program as shown above and try to do it by: if else statement. Enter different characters for different runs, then modify your program to be used by you to enter different inputs and use also loops ( for, while, do..while). If you do this, this mean that you understood all the material we discussed in the class. This is your second homework before exam. Extra grades if your program contains the following: Enter 1 for variable_1 if you want to use switch or enter 2 to use( if or if else or if else if) and : Also: enter for another variable_2 if you want to use (for), 2 if you want to use (while) and 3 if you want to use (do.. while).