ECET 264 C Programming Language with Applications. C Program Control

Size: px
Start display at page:

Download "ECET 264 C Programming Language with Applications. C Program Control"

Transcription

1 ECET 264 C Programming Language with Applications Lecture 7 C Program Control Paul I. Lin Professor of Electrical & Computer Engineering Technology Lecture 7 - Paul I. Lin 1 Lecture 7 C Program Controls Common Programming Errors: Syntax Errors, Logic Errors, Run-time Errors, and Undetected Errors C Program Control Structures Repetition Statements For Statement Do While Repetition Statement Selection Statements Switch multiple selection statement Break Continue Lecture 7 - Paul I. Lin 2 1

2 Lecture 7 C Program Controls C Programming Examples Example 7-1: Interest Calculation Example 7-2: ASCII Number Generation Example 7-3: Read Keyboard Inputs and Echo them on to the Monitor Screen Example 7-4: Generating 10 Random Numbers Example 7-5: Generating Seeded and Unseeded Random Numbers Example 7-6: Counting the Number of a, b, and c characters in a text file Example 7-7: A Calculator Program Lecture 7 - Paul I. Lin 3 Common Programming Errors Syntax errors Grammatical errors, such as misspelling or incorrect punctuation Can be caught by the compiler Logic errors (Caused as a result of faulty program design) Program logical errors Misuse operators, such as ==, = Program does not terminate properly or an endless loop Errors caused by inappropriate end of data Run-time errors (Errors occur during the execution of a program) Other undetected errors (Fail to perform its intended task; incorrect results) Lecture 7 - Paul I. Lin 4 2

3 Repetition Essentials Repetition is a group of statements the computer executes repeatedly while the condition remains true Counter Controlled repetition (definite repetition) A control variable (or loop counter) A proper initial value for the control variable The increment (or decrement) by which the control variable is modified each time through the loop Testing final value of the control variable to know when to end the loop Lecture 7 - Paul I. Lin 5 Repetition Essentials (cont.) Sentinel Controlled repetition (indefinite repetition) The precise number of repetitions is not known in advance The loop includes statement(s) that obtain ending condition data each time the loop is performed The ending condition is determined through a distinct input data called sentinel value which indicates end of data Lecture 7 - Paul I. Lin 6 3

4 Repetition Structures A loop is a form of repetition in which a sequence of statements is repeated a number of times. Repetition structures: are to take actions until the condition fails. while for do while Lecture 7 - Paul I. Lin 7 while Loop Repetition Structures (cont.) Control variables used in the loop control testing must be initialized Testing for the termination condition is done at the top of the while() loop while (1) endless loop which is equivalent to #define true 1 while(true). or for ( ; ; ). Lecture 7 - Paul I. Lin 8 4

5 for Loop for statement is a repetition statement provides a leading-test construct with initialization and re-initialization provisions for loop allows to repeat the statements for a fixed number of times Basic Format: for(initialization; end_cond_checking; update) s1; s2; sn; Lecture 7 - Paul I. Lin 9 for Loop (cont.) Form 1: Null Statement (can be used as a short time delay routine) for (i = 0; i< 10; i++) ; Form 2: Simple Statement for (i = 0; i < 10; i++) sum += 1; i =0 NO statement to be executed Loop continuation condition 10 is a final value of control variable ONE statement to be executed i< 10? False True sum += 1 i ++ Lecture 7 - Paul I. Lin 10 5

6 for Loop (cont.) Form 3: Compound Statement for (init; end_cond_checking; update) s1; s2; Form 4: Nested for Loops for ( ; ;) /* End Less Loop */ for (init; end_cond_checkig; update) s1; s2; s3; for (init; end_cond_checking; update) s4; More than ONE statement to be executed Include more then one FOR statement to be executed Lecture 7 - Paul I. Lin 11 Example 7 1 Interest Calculation This C program computes compound interest using the FOR loop. A person invests $ in a saving account yielding 3% of interest. Assuming that all interest is left on deposit in the account, calculate and print the amount of money in the account at the end of each year for 10 years using the following equation: a = p(1+r) n where p is the original amount invested r is the annual interest rate n is the number of year a is the amount on deposit at the end of the nth year Lecture 7 - Paul I. Lin 12 6

7 Example 7 1 (cont.) Interest Calculation /* Calculating compound interest*/ #include <stdio.h> #include <math.h> /* function main begins program execution */ int main() double amount; /* amount on deposit */ double principal = 500.0; /* starting principal */ double rate = 0.03; /* annual interest rate */ int year; /* year counter */ /* output table column head */ printf( "%4s%21s\n", "Year", "Amount on deposit" ); Lecture 7 - Paul I. Lin 13 Example 7 1 (cont.) Interest Calculation /* calculate amount on deposit for each of ten years */ for ( year = 1; year <= 10; year++ ) /* calculate new amount for specified year */ amount = principal * pow( rate, year ); /* output one table row */ printf( "%4d%21.2f\n", year, amount ); /* end for */ return 0; /* indicate program ended successfully */ Lecture 7 - Paul I. Lin 14 7

8 Example 7 1 (cont.) Interest Calculation Lecture 7 - Paul I. Lin 15 Example 7 2 ASCII Number Generation Write a C program to generate ASCII numbers (0 to 9) and display them as both decimal and hex number on the screen: %c -- the format specified reserves a default length of spaces for printing a character %d -- the format specified reserves a default length of spaces for printing a decimal number %x -- the format specified reserves a default length of spaces for printing a hex number Lecture 7 - Paul I. Lin 16 8

9 Example 7 2 (cont.) ASCII Number Generation #include <stdio.h> void main() char ascii; for (ascii = '0'; ascii <= '9'; ascii++) printf("ascii %c = Decimal %d = Hex %x \n", ascii, ascii, ascii); Lecture 7 - Paul I. Lin 17 Example 7 2 (cont.) ASCII Number Generation Output: ASCII 0 = Decimal 48 = Hex 30 ASCII 1 = Decimal 49 = Hex 31 ASCII 2 = Decimal 50 = Hex 32 ASCII 3 = Decimal 51 = Hex 33 ASCII 4 = Decimal 52 = Hex 34 ASCII 5 = Decimal 53 = Hex 35 ASCII 6 = Decimal 54 = Hex 36 ASCII 7 = Decimal 55 = Hex 37 ASCII 8 = Decimal 56 = Hex 38 ASCII 9 = Decimal 57 = Hex 39 Lecture 7 - Paul I. Lin 18 9

10 Example 7 3: Read Keyboard Input and Echo them on to Monitor Screen /* char0.c A simple for loop for controlling the activities of the keyboard input and screen output. */ #include <stdio.h> #define NEWLINE '\n' void main() char name[30]; int c; /*Execute following forever, CTRL C to stop*/ for(;;) printf("\nplease enter your name: "); gets(name); puts("is this your name?"); puts(name); printf("\nplease enter a digit: "); c = getchar(); puts("\nis this the digit?"); putchar(c); putchar(newline); fflush(stdin); /* Flush the keyboard buffer */ /* end of char0.c */ Lecture 7 - Paul I. Lin 19 Example 7 3: Read Keyboard Input and Echo them on Monitor Screen (cont.) Output: Please enter your name: Paul Lin Is this your name? Paul Lin Please enter a digit:2 Is this the digit? 2 Please enter your name: You entered Lecture 7 - Paul I. Lin 20 10

11 Example 7 4 Generating 10 Random Numbers /* This program seeds the random-number generator with the time, then displays 10 random integers */ #include <stdlib.h> #include <stdio.h> #include <time.h> int main( void ) int i; /* Seed the random-number generator with current time so that the numbers will be different every time we run the program. */ srand( (unsigned)time( NULL ) ); /* Display 10 numbers. */ for( i = 0; i < 10; i++ ) printf( " %6d\n", rand() ); Lecture 7 - Paul I. Lin 21 Example 7 4 (cont.) Generating 10 Random Numbers Sample Output: Lecture 7 - Paul I. Lin 22 11

12 Example 7 5: Generating Seeded and Unseeded Random Numbers /* randgen.c - Generating seeded and unseeded pseudo random numbers */ #include <stdio.h> #include <math.h> #include <stdlib.h> void main(void) int n; /* Generate 4 unseeded pseudo random numbers*/ for(n = 1; n < 5; n++) printf("%d\t", rand()); puts("\n"); /* Generate time() function seeded peudo random numbers */ srand((unsigned)time(null)); Lecture 7 - Paul I. Lin 23 Example 7 5: Generating Seeded and Unseeded Random Numbers (cont.) for(n = 1; n < 5; n++) printf("%d\t", rand()); puts("\n"); /* Reset peudo random generator */ srand(1); for(n = 1; n < 5; n++) printf("%d\t", rand()); puts("\n"); Lecture 7 - Paul I. Lin 24 12

13 Example 7 5: Generating Seeded and Unseeded Random Numbers (cont.) Lecture 7 - Paul I. Lin 25 Example 7 6: Counting the Number of a, b, and c Characters /* if0.c - Counting A, B, C characters */ #include <stdio.h> #define SIZE 81 #define FORMAT "A = %d, B = %d, C = %d\n" void main() int i; int a, b, c; // counters char ch, s[size]; a = b = c = 0; Lecture 7 - Paul I. Lin 26 13

14 Example 7 6: Counting the Number of a, b, and c Characters (cont.) for(;;) // Run forever; Enter <Ctrl C> to exit puts("enter a string"); gets(s); for(i = 0; (ch = s[i])!= '\0'; i++) if((ch == 'A') (ch == 'a')) a++; if((ch == 'B') (ch == 'b')) b++; if((ch == 'C') (ch == 'c')) c++; printf(format, a, b, c); Lecture 7 - Paul I. Lin 27 Example 7 6: Counting the Number of a, b, and c Characters (cont.) Output: You entered Enter a string The C Programming Language A = 3, B = 0, C = 1 Enter a string Lecture 7 - Paul I. Lin 28 14

15 do while while loop tests for the termination condition at the top of the while() loop before the body of the loop performed do while loop always executes its loop body at least once before testing the termination conditions do while loop is good to perform counting, adding, searching, sorting, monitoring, etc Lecture 7 - Paul I. Lin 29 do while (cont.) Syntax: Form 1: Simple Statement do statement; while (condition); Form 2: Compound Statements do s1; s2; s3; while (condition); Lecture 7 - Paul I. Lin 30 15

16 do while (cont.) Using Relational and Logical operators for Checking Ending Condition: do.. while(1) /* Endless loop */ do.. while(a > b) /* a greater than b */ do.. while(a <= b) /* a less or greater than b */ do.. while(a!= b) /* a not eaual to b */ do.. while(a == b) /* a equal to b */ do.. while(a < (c + b)) /* a less than c + b */ do.. while(!a) /* while not a */ do.. while(a && b) /* while a and b are both nonzero or true */ do.. while(a b) /* while either a or b is nonzero or true */ Lecture 7 - Paul I. Lin 31 switch A multiple selection statement Consists of a series of case labels, and optional default case Multi-way branch (a chain of if-else statement) To select among several different cases break is used to end each case to exit the switch The default case is optional Lecture 7 - Paul I. Lin 32 16

17 switch (cont.) General form of switch(n) Syntax: switch (n) case 1: statement 1; break; case n: statement n; break; default: statement; where n can only be an integer, unsigned integer, or character type variable Lecture 7 - Paul I. Lin 33 switch (cont.) Example: int j = 3; switch(j) case 1: printf( case 1 \n ); break; case 2: printf( case2 \n ); break; default: printf( case others \n ); break; Lecture 7 - Paul I. Lin 34 17

18 Example 7 7 A Calculator Program Problem Statement You are asked to write a C program that can be used as a calculator program. The requirement of this program is as follows: It will run under a DOS virtual machine using text based user interface. It will prompt the user to enter two numbers It then asks for one of the calculation: addition, subtraction, multiplication, or division The program calculates the result Displays answer and repeats the same calculation Analysis Three variables are required switch, case, multi-decision making is preferred Endless loop, Ctrl C to exit the loop Lecture 7 - Paul I. Lin 35 Example 7 7 A Calculator Program (cont.) /* switch0.c */ #include <stdio.h> #include <stdlib.h> void main() float n1, n2, result; char op[2]; while(1) /* Enter <Ctrl C> to exit */ fflush(stdin); puts("hit any key to continue, Ctrl C to exit\n"); getchar(); /* waiting for user to input */ printf("\nenter a number: "); scanf( %f, &n1); /* Console input */ printf("\nenter second number: "); scanf( %f, &n2); /* Console input */ Lecture 7 - Paul I. Lin 36 18

19 Example 7 7 A Calculator Program (cont.) printf("\nselect an operator +,-,*, x, / or \\: "); scanf( %s, op); switch(op[0]) case '+': result = n1 + n2; printf("%f\n", result); break; case '-': result = n1 - n2; printf("%f\n", result); break; case '*': case 'x': case 'X': result = n1 * n2; printf("%f\n", result); break; case '/': case '\\': result = n1 / n2; printf("%f\n", result); break; default: puts("wrong operator entered"); Lecture 7 - Paul I. Lin 37 Example 7 7 A Calculator Program (cont.) Output: Hit any key to continue Enter a number: 12.0 Enter second number: 20.0 Select an operator +,-,*, x, / or \: * Hit any key to continue Lecture 7 - Paul I. Lin 38 19

20 Summary Common Program Errors C Program Control More Repetition Statements For Statement Do While Repetition Statement More Selection Statements Switch multiple selection statement Next - Break and Continue statement Equality operator (==) and assignment operator (=) Lecture 7 - Paul I. Lin 39 Question? Answers lin@ipfw.edu Lecture 7 - Paul I. Lin 40 20

ECET 264 C Programming Language with Applications

ECET 264 C Programming Language with Applications ECET 264 C Programming Language with Applications Lecture 6 Control Structures and More Operators Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture

More information

بسم اهلل الرمحن الرحيم

بسم اهلل الرمحن الرحيم بسم اهلل الرمحن الرحيم Fundamentals of Programming C Session # 10 By: Saeed Haratian Fall 2015 Outlines Examples Using the for Statement switch Multiple-Selection Statement do while Repetition Statement

More information

Chapter 4 C Program Control

Chapter 4 C Program Control 1 Chapter 4 C Program Control Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 4 C Program Control Outline 4.1 Introduction 4.2 The Essentials of Repetition

More information

ECET 264 C Programming Language with Applications

ECET 264 C Programming Language with Applications ECET 264 C Programming Language with Applications Lecture 9 & 10 Control Structures and More Operators Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.ecet.ipfw.edu/~lin

More information

Computers Programming Course 7. Iulian Năstac

Computers Programming Course 7. Iulian Năstac Computers Programming Course 7 Iulian Năstac Recap from previous course Operators in C Programming languages typically support a set of operators, which differ in the calling of syntax and/or the argument

More information

Lecture 9 - C Functions

Lecture 9 - C Functions ECET 264 C Programming Language with Applications Lecture 9 C Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 9- Prof. Paul I. Lin

More information

Loop Controls, Decision Making, Functions, and Data Array Processing

Loop Controls, Decision Making, Functions, and Data Array Processing 3 Loop Controls, Decision Making, Functions, and Data Array Processing 3-1 Standard Input and Output 3-1 3-2 Standard Mathematics and Utility Functions 3-5 3-3 Flow of Control 3-10 3-4 Decision Making

More information

Chapter 4 C Program Control

Chapter 4 C Program Control Chapter C Program Control 1 Introduction 2 he Essentials of Repetition 3 Counter-Controlled Repetition he for Repetition Statement 5 he for Statement: Notes and Observations 6 Examples Using the for Statement

More information

Lecture 3. More About C

Lecture 3. More About C Copyright 1996 David R. Hanson Computer Science 126, Fall 1996 3-1 Lecture 3. More About C Programming languages have their lingo Programming language Types are categories of values int, float, char Constants

More information

Dept. of CSE, IIT KGP

Dept. of CSE, IIT KGP Control Flow: Looping CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Types of Repeated Execution Loop: Group of

More information

Chapter 3 Structured Program Development

Chapter 3 Structured Program Development 1 Chapter 3 Structured Program Development Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 3 - Structured Program Development Outline 3.1 Introduction

More information

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1 CSE123 LECTURE 3-1 Program Design and Control Structures Repetitions (Loops) 1-1 The Essentials of Repetition Loop Group of instructions computer executes repeatedly while some condition remains true Counter-controlled

More information

C: How to Program. Week /Apr/23

C: How to Program. Week /Apr/23 C: How to Program Week 9 2007/Apr/23 1 Review of Chapters 1~5 Chapter 1: Basic Concepts on Computer and Programming Chapter 2: printf and scanf (Relational Operators) keywords Chapter 3: if (if else )

More information

Fundamentals of Programming Session 8

Fundamentals of Programming Session 8 Fundamentals of Programming Session 8 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Programming for Engineers Iteration

Programming for Engineers Iteration Programming for Engineers Iteration ICEN 200 Spring 2018 Prof. Dola Saha 1 Data type conversions Grade average example,-./0 class average = 23450-67 893/0298 Grade and number of students can be integers

More information

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch Lecture 3 CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions Review Conditions: if( ) / else switch Loops: for( ) do...while( ) while( )... 1 Examples Display the first 10

More information

C Program Control. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

C Program Control. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan C Program Control Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline The for repetition statement switch multiple selection statement break

More information

Decision Making and Loops

Decision Making and Loops Decision Making and Loops Goals of this section Continue looking at decision structures - switch control structures -if-else-if control structures Introduce looping -while loop -do-while loop -simple for

More information

COMP 208 Computers in Engineering

COMP 208 Computers in Engineering COMP 208 Computers in Engineering Lecture 14 Jun Wang School of Computer Science McGill University Fall 2007 COMP 208 - Lecture 14 1 Review: basics of C C is case sensitive 2 types of comments: /* */,

More information

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

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018. Week 2 Branching & Looping Gaddis: Chapters 4 & 5 CS 5301 Spring 2018 Jill Seaman 1 Relational Operators l relational operators (result is bool): == Equal to (do not use =)!= Not equal to > Greater than

More information

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

Day06 A. Young W. Lim Wed. Young W. Lim Day06 A Wed 1 / 26 Day06 A Young W. Lim 2017-09-20 Wed Young W. Lim Day06 A 2017-09-20 Wed 1 / 26 Outline 1 Based on 2 C Program Control Overview for, while, do... while break and continue Relational and Logical Operators

More information

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

More information

Chapter 2 - Introduction to C Programming

Chapter 2 - Introduction to C Programming Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic

More information

LAB 5: REPETITION STRUCTURE(LOOP)

LAB 5: REPETITION STRUCTURE(LOOP) LAB 5: REPETITION STRUCTURE(LOOP) OBJECTIVES 1. To introduce two means of repetition/loop structures; counter-controlled and sentinelcontrolled. 2. To introduce the repetition structures; for, while, do-while

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 2.11 Assignment Operators 2.12 Increment and Decrement Operators 2.13 Essentials of Counter-Controlled Repetition 2.1 for Repetition Structure 2.15 Examples Using the for

More information

A Look Back at Arithmetic Operators: the Increment and Decrement

A Look Back at Arithmetic Operators: the Increment and Decrement A Look Back at Arithmetic Operators: the Increment and Decrement Spring Semester 2016 Programming and Data Structure 27 Increment (++) and Decrement (--) Both of these are unary operators; they operate

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

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

n Group of statements that are executed repeatedly while some condition remains true Looping 1 Loops n Group of statements that are executed repeatedly while some condition remains true n Each execution of the group of statements is called an iteration of the loop 2 Example counter 1,

More information

C++ Programming Applied to Robotics, Mark Aull Lesson 2: Intro to Visual Studio, debugger Intro to C++, variables, conditionals, loops, strings

C++ Programming Applied to Robotics, Mark Aull Lesson 2: Intro to Visual Studio, debugger Intro to C++, variables, conditionals, loops, strings C++ Programming Applied to Robotics, Mark Aull Lesson 2: Intro to Visual Studio, debugger Intro to C++, variables, conditionals, loops, strings As in the first lesson, open visual studio, start a new empty

More information

Introduction to C Language

Introduction to C Language Introduction to C Language Instructor: Professor I. Charles Ume ME 6405 Introduction to Mechatronics Fall 2006 Instructor: Professor Charles Ume Introduction to C Language History of C Language In 1972,

More information

BSM540 Basics of C Language

BSM540 Basics of C Language BSM540 Basics of C Language Chapter 9: Functions I Prof. Manar Mohaisen Department of EEC Engineering Review of the Precedent Lecture Introduce the switch and goto statements Introduce the arrays in C

More information

Tail recursion. Decision. Assignment. Iteration

Tail recursion. Decision. Assignment. Iteration Computer Programming Tail recursion. Decision. Assignment. Iteration Marius Minea marius@cs.upt.ro 7 October 2014 Two ways of writing recursion unsigned max(unsigned a, unsigned b) { return a > b? a :

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

CS110D: PROGRAMMING LANGUAGE I

CS110D: PROGRAMMING LANGUAGE I CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 5&6: Loops Lecture Contents Why loops?? While loops for loops do while loops Nested control structures Motivation Suppose that you need

More information

sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ;

sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ; INPUT AND OUTPUT IN C Function: printf() library: sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ; format_string it is

More information

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Introduction to C Programming Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline Printing texts Adding 2 integers Comparing 2 integers C.E.,

More information

LAB 5: REPETITION STRUCTURE(LOOP)

LAB 5: REPETITION STRUCTURE(LOOP) LAB 5: REPETITION STRUCTURE(LOOP) OBJECTIVES 1. To introduce two means of repetition/loop structures; counter-controlled and sentinelcontrolled. 2. To introduce the repetition structures; for, while, do-while

More information

Module 4: Decision-making and forming loops

Module 4: Decision-making and forming loops 1 Module 4: Decision-making and forming loops 1. Introduction 2. Decision making 2.1. Simple if statement 2.2. The if else Statement 2.3. Nested if Statement 3. The switch case 4. Forming loops 4.1. The

More information

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

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

More information

Structured Programming. Dr. Mohamed Khedr Lecture 9

Structured Programming. Dr. Mohamed Khedr Lecture 9 Structured Programming Dr. Mohamed Khedr http://webmail.aast.edu/~khedr 1 Two Types of Loops count controlled loops repeat a specified number of times event-controlled loops some condition within the loop

More information

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Data Types Basic Types Enumerated types The type void Derived types

More information

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

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions. Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate

More information

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

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch Flow of Control True and False in C Conditional Execution Iteration Nested Code(Nested-ifs, Nested-loops) Jumps 1 True and False in C False is represented by any zero value The int expression having the

More information

Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be.

Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be. CS 156 : COMPUTER SYSTEM CONCEPTS TEST 1 (C PROGRAMMING PART) FEBRUARY 6, 2001 Student s Name: MAXIMUM MARK: 100 Time allowed: 45 minutes Note: unless otherwise stated, the questions are with reference

More information

Day05 A. Young W. Lim Sat. Young W. Lim Day05 A Sat 1 / 14

Day05 A. Young W. Lim Sat. Young W. Lim Day05 A Sat 1 / 14 Day05 A Young W. Lim 2017-10-07 Sat Young W. Lim Day05 A 2017-10-07 Sat 1 / 14 Outline 1 Based on 2 Structured Programming (2) Conditions and Loops Conditional Statements Loop Statements Type Cast Young

More information

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

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries Hazırlayan Asst. Prof. Dr. Tansu Filik Computer Programming Previously on Bil 200 Low-Level I/O getchar, putchar,

More information

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs PDS Lab Section 16 Autumn-2017 Tutorial 3 C Programming Constructs This flowchart shows how to find the roots of a Quadratic equation Ax 2 +Bx+C = 0 Start Input A,B,C x B 2 4AC False x If 0 True B x 2A

More information

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

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code CS102: Standard I/O Our next topic is standard input and standard output in C. The adjective "standard" when applied to "input" or "output" could be interpreted to mean "default". Typically, standard output

More information

C: How to Program. Week /Apr/16

C: How to Program. Week /Apr/16 C: How to Program Week 8 2006/Apr/16 1 Storage class specifiers 5.11 Storage Classes Storage duration how long an object exists in memory Scope where object can be referenced in program Linkage specifies

More information

AMCAT Automata Coding Sample Questions And Answers

AMCAT Automata Coding Sample Questions And Answers 1) Find the syntax error in the below code without modifying the logic. #include int main() float x = 1.1; switch (x) case 1: printf( Choice is 1 ); default: printf( Invalid choice ); return

More information

Fundamentals of Computer Science. Sentinel Based Repetition

Fundamentals of Computer Science. Sentinel Based Repetition Sentinel Based Repetition 59 syntax: The while Loop Statement while (expression) statement a while loop statement is (almost) identical to a for loop statement that has no initialization or increment expressions

More information

Strings. Daily Puzzle

Strings. Daily Puzzle Lecture 20 Strings Daily Puzzle German mathematician Gauss (1777-1855) was nine when he was asked to add all the integers from 1 to 100 = (1+100)+(2+99)+... = 5050. Sum all the digits in the integers from

More information

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga C-Programming CSC209: Software Tools and Systems Programming Paul Vrbik University of Toronto Mississauga https://mcs.utm.utoronto.ca/~209/ Adapted from Dan Zingaro s 2015 slides. Week 2.0 1 / 19 What

More information

These are reserved words of the C language. For example int, float, if, else, for, while etc.

These are reserved words of the C language. For example int, float, if, else, for, while etc. Tokens in C Keywords These are reserved words of the C language. For example int, float, if, else, for, while etc. Identifiers An Identifier is a sequence of letters and digits, but must start with a letter.

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All for repetition statement do while repetition statement switch multiple-selection statement break statement continue statement Logical

More information

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

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23. Subject code - CCP01 Chapt Chapter 1 INTRODUCTION TO C 1. A group of software developed for certain purpose are referred as ---- a. Program b. Variable c. Software d. Data 2. Software is classified into

More information

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved. Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create

More information

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

Technical Questions. Q 1) What are the key features in C programming language? Technical Questions Q 1) What are the key features in C programming language? Portability Platform independent language. Modularity Possibility to break down large programs into small modules. Flexibility

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure 2.8 Formulating

More information

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. Functions Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 5.1 Introduction 5.3 Math Library Functions 5.4 Functions 5.5

More information

Decision Making -Branching. Class Incharge: S. Sasirekha

Decision Making -Branching. Class Incharge: S. Sasirekha Decision Making -Branching Class Incharge: S. Sasirekha Branching The C language programs presented until now follows a sequential form of execution of statements. Many times it is required to alter the

More information

ECET 264 C Programming Language with Applications

ECET 264 C Programming Language with Applications ECET 264 C Programming Language with Applications Lecture 10 C Standard Library Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 10

More information

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

CS6202 - PROGRAMMING & DATA STRUCTURES UNIT I Part - A 1. W hat are Keywords? Keywords are certain reserved words that have standard and pre-defined meaning in C. These keywords can be used only for their

More information

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU CSE101-lec#12 Designing Structured Programs Introduction to Functions Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Designing structured programs in C: Counter-controlled repetition

More information

Structured Program Development

Structured Program Development Structured Program Development Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline Introduction The selection statement if if.else switch The

More information

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

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 2 (Minor modifications by the instructor) 1 Scope Rules A variable declared inside a function is a local variable Each local variable in a function comes into existence when the function

More information

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition) Structures Programming in C++ Sequential Branching Repeating Loops (Repetition) 2 1 Loops Repetition is referred to the ability of repeating a statement or a set of statements as many times this is necessary.

More information

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly

More information

Functions. Systems Programming Concepts

Functions. Systems Programming Concepts Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value

More information

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables 1 6 C Arrays 6.2 Arrays 2 Array Group of consecutive memory locations Same name and type To refer to an element, specify Array name + position number arrayname[ position number ] First element at position

More information

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University Overview of C, Part 2 CSE 130: Introduction to Programming in C Stony Brook University Integer Arithmetic in C Addition, subtraction, and multiplication work as you would expect Division (/) returns the

More information

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and #include The Use of printf() and scanf() The Use of printf()

More information

Two Dimensional Array - An array with a multiple indexs.

Two Dimensional Array - An array with a multiple indexs. LAB5 : Arrays Objectives: 1. To learn how to use C array as a counter. 2. To learn how to add an element to the array. 3. To learn how to delete an element from the array. 4. To learn how to declare two

More information

3 The L oop Control Structure

3 The L oop Control Structure 3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

More information

Repetition and Loop Statements Chapter 5

Repetition and Loop Statements Chapter 5 Repetition and Loop Statements Chapter 5 1 Chapter Objectives To understand why repetition is an important control structure in programming To learn about loop control variables and the three steps needed

More information

CS1100 Introduction to Programming

CS1100 Introduction to Programming CS1100 Introduction to Programming Arrays Madhu Mutyam Department of Computer Science and Engineering Indian Institute of Technology Madras Course Material SD, SB, PSK, NSN, DK, TAG CS&E, IIT M 1 An Array

More information

Control Structure: Loop

Control Structure: Loop Control Structure: Loop Knowledge: Understand the various concepts of loop control structure Skill: Be able to develop a program involving loop control structure 1 Loop Structure Condition is tested first

More information

Beginning C Programming for Engineers

Beginning C Programming for Engineers Beginning Programming for Engineers R. Lindsay Todd Lecture 2: onditionals, Logic, and Repetition R. Lindsay Todd () Beginning Programming for Engineers Beg 2 1 / 50 Outline Outline 1 Math Operators 2

More information

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University AN OVERVIEW OF C, PART 3 CSE 130: Introduction to Programming in C Stony Brook University FANCIER OUTPUT FORMATTING Recall that you can insert a text field width value into a printf() format specifier:

More information

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

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered )   FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING ( Word to PDF Converter - Unregistered ) http://www.word-to-pdf-converter.net FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING INTRODUCTION TO C UNIT IV Overview of C Constants, Variables and Data Types

More information

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture 18 Switch Statement (Contd.) And Introduction to

More information

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

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from INTRODUCTION TO C++ PROGRAM CONTROL Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Repetition Statement for while do.. while break and continue

More information

Flow Control. CSC215 Lecture

Flow Control. CSC215 Lecture Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

More information

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

Dr. R. Z. Khan, Associate Professor, Department of Computer Science ALIGARH MUSLIM UNIVERSITY Department of Computer Science Course: CSM-102: Programming & Problem Solving Using C Academic Session 2015-2016 UNIT-2: Handout-3 Topic: Control Structures (Selection & Repetition)

More information

Lecture 6. Statements

Lecture 6. Statements Lecture 6 Statements 1 Statements This chapter introduces the various forms of C++ statements for composing programs You will learn about Expressions Composed instructions Decision instructions Loop instructions

More information

Prepared by: Shraddha Modi

Prepared by: Shraddha Modi Prepared by: Shraddha Modi Introduction In looping, a sequence of statements are executed until some conditions for termination of the loop are satisfied. A program loop consist of two segments Body of

More information

Subject: PIC Chapter 2.

Subject: PIC Chapter 2. 02 Decision making 2.1 Decision making and branching if statement (if, if-, -if ladder, nested if-) Switch case statement, break statement. (14M) 2.2 Decision making and looping while, do, do-while statements

More information

Two Dimensional Array - An array with a multiple indexs.

Two Dimensional Array - An array with a multiple indexs. LAB5 : Arrays Objectives: 1. To learn how to use C array as a counter. 2. To learn how to add an element to the array. 3. To learn how to delete an element from the array. 4. To learn how to declare two

More information

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler

More information

C Tutorial: Part 1. Dr. Charalampos C. Tsimenidis. Newcastle University School of Electrical and Electronic Engineering.

C Tutorial: Part 1. Dr. Charalampos C. Tsimenidis. Newcastle University School of Electrical and Electronic Engineering. C Tutorial: Part 1 Dr. Charalampos C. Tsimenidis Newcastle University School of Electrical and Electronic Engineering September 2013 Why C? Small (32 keywords) Stable Existing code base Fast Low-level

More information

Computer System and programming in C

Computer System and programming in C 1 Basic Data Types Integral Types Integers are stored in various sizes. They can be signed or unsigned. Example Suppose an integer is represented by a byte (8 bits). Leftmost bit is sign bit. If the sign

More information

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

Sudeshna Sarkar Dept. of Computer Science & Engineering. Indian Institute of Technology Kharagpur Programming and Data Structure Sudeshna Sarkar Dept. of Computer Science & Engineering. Indian Institute of Technology Kharagpur Shortcuts in Assignment Statements A+=C A=A+C A-=B A=A-B A*=D A=A*D A/=E

More information

Structured Program Development in C

Structured Program Development in C 1 3 Structured Program Development in C 3.2 Algorithms 2 Computing problems All can be solved by executing a series of actions in a specific order Algorithm: procedure in terms of Actions to be executed

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 7: Introduction to C (pronobis@kth.se) Overview Overview Lecture 7: Introduction to C Wrap Up Basic Datatypes and printf Branching and Loops in C Constant values Wrap Up Lecture 7: Introduction

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure

More information

C Programming Language

C Programming Language C Programming Language Arrays & Pointers I Dr. Manar Mohaisen Office: F208 Email: manar.subhi@kut.ac.kr Department of EECE Review of Precedent Class Explain How to Create Simple Functions Department of

More information

C Program Development and Debugging under Unix SEEM 3460

C Program Development and Debugging under Unix SEEM 3460 C Program Development and Debugging under Unix SEEM 3460 1 C Basic Elements SEEM 3460 2 C - Basic Types Type (32 bit) Smallest Value Largest Value short int -32,768(-2 15 ) 32,767(2 15-1) unsigned short

More information

Control Structures. Chapter 13 Control Structures. Example If Statements. ! Conditional. if (condition) action;

Control Structures. Chapter 13 Control Structures. Example If Statements. ! Conditional. if (condition) action; Chapter 13 Control Structures Original slides from Gregory Byrd, North Carolina State University Modified slides by Chris Wilcox, Colorado State University Control Structures! Conditional n making a decision

More information

Conditional Statement

Conditional Statement Conditional Statement 1 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition Also called Branching How do we specify conditions?

More information