# 3/13/2012. ESc101: Multiple statement execution using loops. Loops are used when instructions are repeated. while statement can be used for a loop

Save this PDF as:

Size: px
Start display at page:

Download "3/13/2012. ESc101: Multiple statement execution using loops. Loops are used when instructions are repeated. while statement can be used for a loop"

## Transcription

1 ESc101: Multiple statement execution using loops Instructor: Krithika Venkataramani Semester 2, The content of most of these slides are taken from the lecture slides of Prof. Arnab Bhattacharya 1 2 Loops are used when instructions are repeated while statement can be used for a loop Print all numbers between 1 and 100 that are divisible by 7 Algorithm 1. Initialize x = 1 2. Test if x is divisible by 7 3. If yes, display x 4. Increment x 5. If x <= 100, go back to step 2 Requires loops - instructions that are repeated a number of times Each time (called an iteration), some variable may change For a loop to stop, either of these must be specified Number of times the loop runs Stopping condition while ( condition ) statements condition evaluates to a boolean The statements in the loop are executed as long as condition is true Any expression acts as condition Value of condition, if initially true, must change at some appropriate later point to false Otherwise, infinite loop is created 3 4 1

2 Example of a while-statement Algorithm: Find sum of first N natural numbers Print all numbers between 1 and 100 that are divisible by 7 x = 1; while (x <= 100) if ((x % 7) == 0) printf ( %d, x); x++; 1. Input N 2. Sum = 0 3. If N < 1, go to step 8 4. I = 1 5. Sum = Sum + I 6. I = I If I <= N, go back to step 5 8. Print Sum 5 6 Sum of first N natural numbers using a while loop printf( \nenter number N ); scanf( %d, &N); / x= 1; //initializing sum = 0; //initializing if (N<1) //error check: to ensure N is a natural number printf( \nn is not a natural number: enter only a natural number ); else //if N is a Natural number while (x<=n) sum = sum + x; //if number is less than or equal to N, add it to sum x++; // go to the next number printf( \nsum = %d, sum); 7 Lab 1: Q2 algorithm using loop Take as input 4 numbers. Print arithmetic mean & harmonic mean. Print the maximum of the two means. Algorithm: 1. Initialize j = 1, arithmetic_mean = 0, inverse_harmonic_mean = 0 2. Input a number, n 3. Add number, n, to arithmetic_mean 4. If n is positive and harmonic mean is valid, add 1/n to inverse_harmonic_mean 5. Otherwise, harmonic mean is not valid 6. Increment j 7. If j <= 4, go back to Step 2 8. arithmetic_mean = arithmetic_mean/4 9. if valid, divide inverse_harmonic_mean by if valid, harmonic mean = 1/inverse_harmonic_mean 8 2

3 Lab 1: Q2 sample solution using while loop Lab 1: Q2 sample solution using while loop (cont.) #include<stdio.h> int main() float n, arithmetic_mean=0, inverse_harmonic_mean=0, harmonic_mean = 0; int flag = 1, j= 1; while (j<=4) printf( Enter the %d number,j); scanf( %f,&n); arithmetic_mean = arithmetic_mean + n; 9 if ((n>0)&&(flag==1)) inverse_harmonic_mean = inverse_harmonic_mean+ 1/n; else flag = 0;//invalid harmonic mean j++; arithmetic_mean = arithmetic_mean/4; if (flag==1) //valid harmonic mean inverse_harmonic_mean = inverse_harmonic_mean/4; harmonic_mean = 1/inverse_harmonic_mean; 10 Lab 1: Q3 sample solution using a loop Lab 1: Q3 sample solution using a loop Take a 5 digit integer as input from the user. Count the total number of zeroes in it and print the result. Algorithm: 1. Input the integer 2. Initialize zero_count to 0 3. Find the remainder of integer by dividing using If remainder is zero, then increment zero_count by 1 5. Divide the integer by Use the quotient as the new integer 7. If integer!=0, go to Step 3 8. Display zero_count int n, count=0; printf("enter the FIVE DIGIT integer\n"); scanf("%d",&n); while (n!=0) //checking if the last digit it is zero if(n%10 == 0) count++; n=n/10; //integer with one less digit //printing the results printf("number of zeros: %d\n",count);

4 Algorithm to display digits in reverse order while loop to display digits in reverse order Input an integer. Display the digits of the integer in reverse order. Algorithm 1. Input an integer 2. If negative integer, take the absolute value and display - 3. Find the remainder of division by Display the remainder 5. Divide the integer by 10 and use the quotient as new integer 6. If integer is not equal to 0, go back to Step 3 if (n<0) n = -n; // get absolute value printf( - ); //display for negative integer while (n!=0) remainder = n%10; printf( %d, remainder); //display the last digit n = n/10; //new integer has one less digit, without the last digit Algorithm to find geometric mean Input n positive numbers and find their geometric mean geometric mean = (x 1 x 2 x 3 x n ) 1/n Algorithm: 1. Input n 2. Initialize j to 1 and geometric mean to Input number 4. Update geometric mean by multiplying it with the (number) 1/n 5. Increment j 6. If j < = n, go back to Step 3 7. Display geometric mean 15 while loop to find Geometric Mean j = 1; geometric_mean = 1; while (j<=n) printf( Enter number %d:,j); scanf( %f, &number); if (number > 0) //updates and increments only for positive numbers geometric _mean = geometric_mean * pow(number, 1.0/n); j++; printf( Geometric mean = %f, geometric_mean); 16 4

5 Computation of power for statement Standard functions to compute power are present pow(x,y) function computes x y Requires #include <math.h> compilation using gcc lm e.g. gcc lm geomean.c for ( initialization ; condition ; update ) statements condition evaluates to a boolean The statements in the loop are executed as long as condition is true initialization initializes variables update updates the condition Value of condition, if initially true, must change at some appropriate point of time later to false Otherwise, infinite loop is created Example using for-statement Sample program Print all numbers between 1 and 100 that are divisible by 7 for (x = 1; x <= 100; x++) if ((x % 7) == 0) printf ( %d, x); Find the sum of first N natural numbers using a for loop. printf( Enter the natural number N: ); scanf( %d, &N); sum = 0; for (i = 1, i<=n, i++) sum = sum + i; printf( \nsum of %d Natural numbers = %d,n, sum);

6 Equivalence of while and for statements for loop to find geometric mean while and for statements are equivalent for ( initialization ; condition ; update ) statements ; translates to initialization ; while ( condition ) statements ; update ; It is a matter of convenience and ease on the choice of loop geometric_mean = 1; for (j = 1; j <=n; j++) printf( Enter number %d:,j); scanf( %f, &number); if (number > 0) //updates mean only for positive numbers geometric _mean = geometric_mean * pow(number, 1/n); else j--; //increments only for positive numbers printf( Geometric mean = %f, geometric_mean); for loop to display digits in reverse order break brings execution out of loop if (n<0) n = -n; // get absolute value printf( - ); //display for negative integer for ( ; n!=0; n=n/10) // there is no initialization remainder = n%10; printf( %d, remainder); //display the last digit break statement can be used within a loop break brings execution out of the loop break is generally used when loop is not to be executed under certain circumstances (condition) while (condition1) for (initialization; condition1; update) statements1; if (condition2) break; statement2; statements1; if (condition2) break; statement2;

7 break brings execution out of loop Sample program using break The loop is exited straightaway using a break statement Find the first number between 103 and 145 divisible by 23 x = 103; while ( x <= 145) for (x = 103; x <= 145; x++) if ((x % 23) == 0) printf ( %d, x); break ; if ((x % 23) == 0) printf ( %d, x); break ; x++; After the number is found, it does not make sense to continue break immediately exits the loop 25 Compute the sum of the geometric series for n terms until the sum does not change beyond a specified value a + a r + ar 2 + ar 3 + r is between 0 and 1 sum = 0; for (i = 1; i <= n; i++) term = a * pow(r, i - 1); if (term <= Spec_value) break; sum = sum + term; 26 continue statement continue can be used in loops continue allows the next iteration to be executed in the loop The statements after continue are not executed in the current iteration of the loop continue is generally used when certain statements (e.g. statements2 below) are not to be executed under certain circumstances (e.g. condition2 below) while (condition1) statements1; if (condition2) continue; statements2; for (initialization; condition1; update) statements1; if (condition2) continue; statements2; 27 Using continue for updating geometric mean j = 1; geometric_mean = 1; while (j<=n) // loop to compute geometric mean of n numbers printf( Enter number %d:,j); scanf( %f, &number); if (number <= 0) continue; //For non-positive numbers, don t update mean geometric _mean = geometric_mean *pow(number,1/n); j++; //ensures increment only if number is positive printf( Geometric mean = %f, geometric_mean); 28 7

8 Using continue for updating geometric mean geometric_mean = 1; for (j = 1; j <=n; j++) // loop to compute geometric mean printf( Enter number %d:,j); scanf( %f, &number); if (number <= 0) j--; //increment count only for positive numbers continue; //For non-positive numbers, don t update mean geometric _mean = geometric_mean * pow(number, 1/n); printf( Geometric mean = %f, geometric_mean); 29 More on for loop for (; ; ) creates an infinite loop However, you can exit the loop using break Display numbers from 34 to 55 using for (; ; ) a = 34; for ( ; ;) printf( %d, a); a++; if (a>55) break; 30 More on for loop for (a =0; a<=20; ) also creates an infinite loop if value of a does not change to >20 within the loop update statements can be within the loop for (a = 0; a <=20; ) a++; printf( %d, a); a = a+1; //multiple update statements printf( %d, a); Comma operator Lowest precedence of all operators comma operator links a list of related expressions together left to right evaluation Value of the combined expression = value of the right-most expression sum = (x=10, y= 5, x+y); sum = 15 Can be used for exchanging values t =x, x=y, y = t; Used in loops for multiple expressions for (n = 1, m = 1; n<=m; n++, m++) while (n!=0, m!=0) equivalent to while (m!=0)

9 do-while loop do-while loop example do statement; while (expression); statement is executed first, and then expression in evaluated if expression is TRUE, the statement is executed again Print all numbers between 1 and 100 that are divisible by 7 x =1; do if ((x % 7) == 0) if expression is FALSE, the loop terminates In general, do-while loops are less frequently used printf ( %d, x); x++; while (x<=100) Nested loops Nested loops: Using loops within loops Example: print multiplication table Formatting: printf( %4d, x) displays an integer in 4 spaces If x has more than 4 digits, all digits are displayed If x has less than 4 digits, spaces are placed before the integer int row=1, column, y; //program to print multiplication table do column = 1; do y = row *column; printf( %4d,y); column++; while (column <=10) printf( \n ); //prints new line after one row of multiplication table row++; while (row <=12)

10 Sample program Use nested loops to find the sum of the series below, until the sum does not change more than a specified value for x <1 37 Series sum using nested loops sum = 0; for (i = 1; ; i++) factorial = 1; power = 1; for (j = 1; j <=I; j++) factorial = factorial * (-j); power = power*x; term = -1* power/factorial; if (((term<0)&&(term >= - specified_value)) ((term>0)&&(term <= specified_value)) ) break; sum = sum + term; 38 Nested Loop Example Algorithm for nested loop example Write a program to display the following output ***** **** *** ** * Algorithm Flowchart Program 5 lines to be displayed. One less star in each line, starting with 5 stars. Star replaced by space in the beginning. 1. Initialize linecount =1. 2. Initialize charactercount=1. 3. If charactercount<linecount, print space. 4. Otherwise print star. 5. Increment charactercount. 6. If charactercount <=5, go back to Step Otherwise increment linecount and display in a new line. Go back to Step

11 Flowchart on nested loop example Code for nested loop Start Line count = 1 Char count = 1 Char count < Line count? No Print * Yes Print Increment Char count Yes Char count<=5? No Start new line. Increment line count. Line count<=5? Yes No End 41 int j, k; for(j=1;j<=5;j++) /*for displaying 5 lines*/ for(k=1;k<=5;k++)/*for displaying 5 characters in each line*/ if(k<j) printf( );/*display blank space at beginning*/ else printf( * );/*display star at the end*/ printf( \n ); /*new line after 5 characters*/ 42 11

### 3/13/2012. Writing Simple C Programs. ESc101: Decision making using if-else and switch statements. Writing Simple C Programs

Writing Simple C Programs ESc101: Decision making using if- and switch statements Instructor: Krithika Venkataramani Semester 2, 2011-2012 Use standard files having predefined instructions stdio.h: has

### Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

### 14 MAKING DECISIONS IN C

14 MAKING DECISIONS IN C 14.1 INTRODUCTION So far we have seen that in C programs the instructions are executed in the same order in which they appear in the program. Each instruction is executed once

### Computer Programming. Loops(2) do-while, for

Computer Programming Loops(2) do-while, for Topics Repeating Statements (review) while loop (review) do-while loop for loop Infinite loops Examples Repeating Statements In many cases same operations are

### CSI 333 Lecture 2 Introduction to C: Part I 2 1 / 16

CSI 333 Lecture 2 Introduction to C: Part I 2 1 / 16 Basics of C Remark: Skim Chapters 1 through 6 of Deitel & Deitel. You will notice the following: C is (more or less) a subset of Java. (So, you are

### Sources: On the Web: Slides will be available on:

C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

### Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

### Repetition and Loops. Additional Python constructs that allow us to effect the (1) order and (2) number of times that program statements are executed.

New Topic Repetition and Loops Additional Python constructs that allow us to effect the (1) order and (2) number of times that program statements are executed. These constructs are the 1. while loop and

### 3/13/2012. Esc101: Strings. String input and output. Array of characters: String

Esc101: Strings Instructor: Krithika Venkataramani Semester 2, 2011-2012 The contents of most of these slides are from the lecture slides of Prof. Arnab Bhattacharya 1 2 Array of characters: String String

### Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

### What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

### C programming: exercise sheet L2-STUE (2011-2012)

C programming: exercise sheet L2-STUE (2011-2012) Algorithms and Flowcharts Exercise 1: comparison Write the flowchart and associated algorithm that compare two numbers a and b. Exercise 2: 2 nd order

### cin >> num1 >> num2 >> num3 >> num4 >> num5; sum = num1 + num2 + num3 + num4 + num5; average = sum / 5.

Lesson Outcomes At the end of this chapter, student should be able to: Understand the requirement of a loop Understand the Loop Control Variable (LCV) Use increment (++) and decrement (--) operators Program

### GTU Questions. Computer Programming & Utilization. Chief Course Coordinator Prof. Mitul K.Patel. (Head of Department & Assistant Professor)

GTU Questions Computer Programming & Utilization Chief Course Coordinator Prof. Mitul K.Patel (Head of Department & Assistant Professor) Course Coordinator Prof. Vrutti D. Shah (Assistant Professor) Lab

### Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

### Branching. We ll continue to look at the basics of writing C++ programs including. Overview

Branching Overview We ll continue to look at the basics of writing C++ programs including Boolean Expressions (need to know this before we can using branching and looping!) Branching J.S. Bradbury CSCI

### Indicates the end of data when the number of data is not known in advance Must be distinct from the data but be of the same type

Program Control Essentials of repetition Loop control variable Counts the number of repetitions in the counter-controlled loop Controls the execution of loop Sentinel value Indicates the end of data when

### Control structures in C

Control structures in C Lecture Topics Conditional constructs Iterative constructs Examples Style Lecture materials Textbook 13.3-13.5 Homework None Machine problem MP1.1 due February 2 at 5pm submitted

### MPATE-GE 2618: C Programming for Music Technology. Unit 1.3

MPATE-GE 2618: C Programming for Music Technology Unit 1.3 More operators e ++ and -- are increment and decrement operators ++i or i++ is equivalent to i = i + 1; --i or i-- is equivalent to i = i - 1;

### PE1 Worksheet. 3) What are the three control structures for writing an algorithm in pseudocode?

PE1 Worksheet Problem solving 1) What are the four stages of problem solving by programming? What shall be done in each stage? Stage 1: Stage 2: Stage 3: Stage 4: 2) What is the top-down design strategy

### MIT Aurangabad FE Computer Engineering

MIT Aurangabad FE Computer Engineering Unit 1: Introduction to C 1. The symbol # is called a. Header file c. include b. Preprocessor d. semicolon 2. The size of integer number is limited to a. -32768 to

### Looping Exercises Deciding Which Loop to Use

Looping Exercises Deciding Which Loop to Use At this time you have learned four looping constructs (also called repetition statements). Each of these four loops are ideal to use in different situations.

### Fundamentals of Programming

Fundamentals of Programming Introduction to the C language Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) The C language

### 6.096 Lab 1. Due: 7 January 12:30:00. September 20, 2011

6.096 Lab 1 Due: 7 January 1:30:00 September 0, 011 1 Additional Material 1.1 Constants A constant is an expressions with a fixed value. Kinds of constants: Literals: used to express particular values

### C Programming Dr. Hasan Demirel

C How to Program, H. M. Deitel and P. J. Deitel, Prentice Hall, 5 th edition (3 rd edition or above is also OK). Introduction to C Programming Dr. Hasan Demirel Programming Languages There are three types

### 9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending

### Dept. of CSE, IIT KGP

Programming in C: Basics CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Types of variable We must declare the

### Engineering Problem Solving with C++, Etter/Ingber

Engineering Problem Solving with C++, Etter/Ingber Chapter 3 Control Structures 1 Control structures Algorithm Development Conditional Expressions Selection Statements Repetition Statements Structuring

### Two-way selection. Branching and Looping

Control Structures: are those statements that decide the order in which individual statements or instructions of a program are executed or evaluated. Control Structures are broadly classified into: 1.

### Pseudocode. Pseudocode. Guide for Pseudocode. Computers in Engineering Pseudocode and C Language Review. Example Pseudocode.

Computers in Engineering Pseudocode and C Language Review Pseudocode Pseudocode is an artificial and informal language that helps you develop algorithms Pseudocode is similar to everyday English; it is

### Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

### Chapter 4 C Program Control

Chapter 4 C Program Control Objectives of this chapter: Repetitions will be considered in greater detail for.. repetition do while repetition Also multiple selection switch case statement will be learned.

### 6.087 Lecture 3 January 13, 2010

6.087 Lecture 3 January 13, 2010 Review Blocks and Compound Statements Control Flow Conditional Statements Loops Functions Modular Programming Variable Scope Static Variables Register Variables 1 Review:

### Control Structure. Pseudocode: Input number If number is even Then Print even Else print odd. Flowchart: Begin. End. Print Odd. number even?

Control Structure Normally, a program is executed in a sequential manner.however, in many cases, a program has to choose among alternative statements C++ provides constructs that enable the programmer

### FORM 1 (Please put your name, section # (10am- 001/2pm-002, and form # on the scantron!!!!) CS 161 Exam I:

FORM 1 (Please put your name, section # (10am- 001/2pm-002, and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each): 1. The following statement is legal: cout >> Hello, my name is

### Punctuation in C. Identifiers and Expressions. Identifiers. Variables. Keywords. Identifier Examples

Identifiers and Expressions CSE 130: Introduction to C Programming Spring 2005 Punctuation in C Statements are terminated with a ; Groups of statements are enclosed by curly braces: { and } Commas separate

### OUTCOMES BASED LEARNING MATRIX

Course: CTIM371 Programming in C++ OUTCOMES BASED LEARNING MATRIX Department: Computer Technology and Information Management Course Description: This is the first course in the C++ programming language.

### LAB 1 REPRESENTATION OF NUMBERS AND INTRODUCTION TO C

LAB 1 REPRESENTATION OF NUMBERS AND INTRODUCTION TO C 1. LAB OBJECTIVE The objective of this lab is to review binary numbers and to review/introduce you to the C programming language and the MATLAB environment.

### While Loop. 6. Iteration

While Loop 1 Loop - a control structure that causes a set of statements to be executed repeatedly, (reiterated). While statement - most versatile type of loop in C++ false while boolean expression true

### M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE NOTE: IMPORTANT INSTRUCTIONS: 1. Question Paper in English and Hindi and Candidate can choose any one language. 2. In case of discrepancies in

### Chapter 4 Operators & Arithmetic

Chapter 4 Operators & Arithmetic 4-1 Arithmetic in C++ Arithmetic expressions can be made up of constants, variables, operators and parentheses. The arithmetic operators in C++ are as follows + (addition)

### Programming and Data Structures

Programming and Data Structures Tutorial sheet: 2 Topics: Decision Making, Looping and Branching Q 1. (a) What is wrong with the following loop while ( n

### CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

### A First Book of C++ Chapter 2 Data Types, Declarations, and Displays

A First Book of C++ Chapter 2 Data Types, Declarations, and Displays Objectives In this chapter, you will learn about: Data Types Arithmetic Operators Variables and Declarations Common Programming Errors

### Going from Python to C

Going from Python to C Darin Brezeale December 8, 2011 Python is a high-level, interpreted language. C has many of the same types of programming constructs as in Python: arrays, loops, conditionals, functions,

### Chapter 8. Statement-Level Control Structures

Chapter 8 Statement-Level Control Structures Chapter 8 Topics Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions 8-2 1 Levels of Control Flow Within

### CS1010 Programming Methodology A beginning in problem solving in Computer Science. Aaron Tan http://www.comp.nus.edu.sg/~cs1010/ 20 July 2015

CS1010 Programming Methodology A beginning in problem solving in Computer Science Aaron Tan http://www.comp.nus.edu.sg/~cs1010/ 20 July 2015 Announcements This document is available on the CS1010 website

### COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012

Binary numbers The reason humans represent numbers using decimal (the ten digits from 0,1,... 9) is that we have ten fingers. There is no other reason than that. There is nothing special otherwise about

### C for Mathematicians. James A. Carlson & Jennifer M. Johnson

C for Mathematicians James A. Carlson & Jennifer M. Johnson (c) January 5, 2001 Contents 1. The Basics of Programming in C................................... 1 1. Algorithms....................................................

### COMPSCI 210 Part II Decisions & Iterations

Agenda COMPSCI 210 Part II Decisions & Iterations Based on slides @ McGraw-Hill Agenda: Decision-making statements: he if statement he switch statement Iterations he for statement he while statement he

### VB.NET Programming Fundamentals

Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements

### Borland C++ Compiler: Operators

Introduction Borland C++ Compiler: Operators An operator is a symbol that specifies which operation to perform in a statement or expression. An operand is one of the inputs of an operator. For example,

### INTRODUCTION TO FLOWCHARTING

CHAPTER 1 INTRODUCTION TO FLOWCHARTING 1.0 Objectives 1.1 Introduction 1.2 Flowcharts 1.3 Types of Flowcharts 1.3.1 Types of flowchart 1.3.2 System flowcharts 1.4 Flowchart Symbols 1.5 Advantages of Flowcharts

### Elementary Number Theory and Methods of Proof. CSE 215, Foundations of Computer Science Stony Brook University http://www.cs.stonybrook.

Elementary Number Theory and Methods of Proof CSE 215, Foundations of Computer Science Stony Brook University http://www.cs.stonybrook.edu/~cse215 1 Number theory Properties: 2 Properties of integers (whole

### Tutorial on C Language Programming

Tutorial on C Language Programming Teodor Rus rus@cs.uiowa.edu The University of Iowa, Department of Computer Science Introduction to System Software p.1/64 Tutorial on C programming C program structure:

### 1. True or False? A natural number is the number 0 or any number obtained by adding 1 to a natural number.

CS Illuminated, 5 th ed. Chapter 2 Review Quiz 1. True or False? A natural number is the number 0 or any number obtained by adding 1 to a natural number. 2. True or False? The category of numbers called

### Introduction to C Programming S Y STEMS

Introduction to C Programming CS 40: INTRODUCTION TO U NIX A ND L I NUX O P E R AT ING S Y STEMS Objectives Introduce C programming, including what it is and what it contains, which includes: Command line

### Binary. ! You are probably familiar with decimal

Arithmetic operations in assembly language Prof. Gustavo Alonso Computer Science Department ETH Zürich alonso@inf.ethz.ch http://www.inf.ethz.ch/department/is/iks/ Binary! You are probably familiar with

### We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.

### REPETITION WITH PYTHON

REPETITION WITH PYTHON José M. Garrido Department of Computer Science May 2015 College of Computing and Software Engineering Kennesaw State University c 2015, J. M. Garrido Repetition with Python 2 Repetition

### Chapter 6 Repetition

Chapter 6 Repetition 6-1 Repetition in C++ The final control/logic structure is repetition: Repetition repeating a block of code until a condition is met There are three repetition statements available

### QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1

QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For

### C AND C++ PROGRAMMING

C AND C++ PROGRAMMING Bharathidasan University A Courseware prepared by University Informatics Centre Part I - Programming in C Getting Started This courseware is intended to be an introduction to C programming

### PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

PROGRAMMING IN C CONTENT AT A GLANCE 1 MODULE 1 Unit 1 : Basics of Programming Unit 2 : Fundamentals Unit 3 : C Operators MODULE 2 unit 1 : Input Output Statements unit 2 : Control Structures unit 3 :

### Introduction to Java

Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

### CS 241 Data Organization Coding Standards

CS 241 Data Organization Coding Standards Brooke Chenoweth University of New Mexico Spring 2016 CS-241 Coding Standards All projects and labs must follow the great and hallowed CS-241 coding standards.

### Solutions to Assessment: Basic Programming Constructs

Solutions to Assessment: Basic Programming Constructs Question 1: Specify the minimum number of comparisons required to find the largest number among a set of 3 integers X, Y and Z. We already know how

### Example of a Java program

Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);

### Programming for MSc Part I

Herbert Martin Dietze University of Buckingham herbert@the-little-red-haired-girl.org July 24, 2001 Abstract The course introduces the C programming language and fundamental software development techniques.

### Statements and Control Flow

Contents 1. Introduction 2. Types and Variables 3. Statements and Control Flow 4. Reading Input 5. Classes and Objects 6. Arrays 7. Methods 8. Scope and Lifetime 9. Utility classes 10. Introduction to

### Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Example Assume the following specification: Input: read a number N > 0 Output:

### Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Example Introduction to Programming (in C++) Loops Assume the following specification: Input: read a number N > 0 Output: write the sequence 1 2 3 N (one number per line) Jordi Cortadella, Ricard Gavaldà,

### ALGORITHMS AND FLOWCHARTS

ALGORITHMS AND FLOWCHARTS A typical programming task can be divided into two phases: Problem solving phase produce an ordered sequence of steps that describe solution of problem this sequence of steps

### Flowchart Techniques

C H A P T E R 1 Flowchart Techniques 1.1 Programming Aids Programmers use different kinds of tools or aids which help them in developing programs faster and better. Such aids are studied in the following

### Chapter 2: Problem Solving Using C++

Chapter 2: Problem Solving Using C++ 1 Objectives In this chapter, you will learn about: Modular programs Programming style Data types Arithmetic operations Variables and declaration statements Common

### Python to C/C++ Fall 2011

Python to C/C++ Fall 2011 1. Main Program Python: Program code is indented after colon : def main(): body of program C/C++: Have more setup overhead. C: Both require #include directives to access libraries

### Overview of a C Program

Overview of a C Program Programming with C CSCI 112, Spring 2015 Patrick Donnelly Montana State University Programming with C (CSCI 112) Spring 2015 2 / 42 C Language Components Preprocessor Directives

### 3.0 INTRODUCTION 3.1 OBJECTIVES

Software UNIT 3 CONCEPT IN PROGRAMMING LANGUAGE Structure Page No. 3.0 Introduction 58 3.1 Objectives 58 3.2 Problem, Algorithm, Program and Programming Language 59 3.3 Concept of a Programming Language

### Data Representation Binary Numbers

Data Representation Binary Numbers Integer Conversion Between Decimal and Binary Bases Task accomplished by Repeated division of decimal number by 2 (integer part of decimal number) Repeated multiplication

### Number Systems and. Data Representation

Number Systems and Data Representation 1 Lecture Outline Number Systems Binary, Octal, Hexadecimal Representation of characters using codes Representation of Numbers Integer, Floating Point, Binary Coded

### [Page 70 (continued)] a. are used to document a program and improve its readability. [Page 71]

[Page 70 (continued)] Exercises 2.7 Discuss the meaning of each of the following objects: a. std::cin b. std::cout 2.8 Fill in the blanks in each of the following: a. are used to document a program and

### SANKALCHAND PATEL COLLEGE OF ENGINEERING, VISNAGAR ODD/EVEN ACADEMICSEMESTER (2014-15) ASSIGNMENT / QUESTION BANK (2110003) [F.Y.B.E.

SANKALCHAND PATEL COLLEGE OF ENGINEERING, VISNAGAR ODD/EVEN ACADEMICSEMESTER (2014-15) ASSIGNMENT / QUESTION BANK Subject: Computer Programming and Utilization (2110003) [F.Y.B.E.: ALL BRANCHES] Unit 1

### Final Exam Review. CS 1428 Fall Jill Seaman. Final Exam

Final Exam Review CS 1428 Fall 2011 Jill Seaman 1 Final Exam Friday, December 9, 11:00am to 1:30pm Derr 241 (here) Closed book, closed notes, clean desk Comprehensive (covers entire course) 25% of your

### Lecture P1: Introduction to C

Learning to Program Lecture P1: Introduction to C Programming is learned with practice and patience. Don t expect to learn solely from these lectures. Do exercises. Experiment and write lots of code. printf("this

### while for ! do while ! set an accumulator variable to 0 ! add the next number to it inside the loop

Week 7: Advanced Loops while Loops in C++ (review) while (expression) statement statement may be a compound statement (a block: {statements) Gaddis: 5.7-12 CS 1428 Fall 2014 Jill Seaman 1 for if expression

### Writing Control Structures

Writing Control Structures Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 5-1 Objectives After completing this lesson, you should be able to do the following: Identify

### Introduction to Problem Solving Techniques

UNIT 1 Introduction to Problem Solving Techniques Structure 1.0 Introduction 1.1 Procedure (steps involved in problem solving) 1.2 Algorithm 1.3 Flow Chart 1.4 Symbols used in Flow Charts 1.5 Pseudo Code

### C++ Basics. C++ Basics: Names: Identifiers. Names: Identifiers. Display 2.1 A C++ Program (1 of 2) Display 2.1 A C++ Program (2 of 2)

C++ Basics C++ Basics: 2.1 Variables and Assignments Variables and Assignments Input and Output Data Types and Expressions Simple Flow of Control Program Style A C++ variable can hold a number or other

### 1. Constants. 2. Variables. 3. Reserved words or key words. 4. Constants. Character set in C

Character set in C We should use only the following characters in writing a C program. These characters can be combined to create C words. Alphabet: A, B, C, D.. Z, a, b, c, d..z Numeric digits: 0, 1,

### C PROGRAMMING: THE IF, WHILE, DO-WHILE, FOR AND ARRAY WORKING PROGRAM EXAMPLES (with some flowcharts)

Main < C & C++ 2D Array 3 C & C++ Functions Part 1 > Site Index Download C PROGRAMMING: THE IF, WHILE, DO-WHILE, FOR AND ARRAY WORKING PROGRAM EXAMPLES (with some flowcharts) 1. Compiler: VC++ Express

### In this Chapter you ll learn:

Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then stop. Lewis

### Computer Programming I

Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,

### The While Loop. Objectives. Textbook. WHILE Loops

Objectives The While Loop 1E3 Topic 6 To recognise when a WHILE loop is needed. To be able to predict what a given WHILE loop will do. To be able to write a correct WHILE loop. To be able to use a WHILE

### 6. Control Structures

- 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,

### Introduction to Programming Block Tutorial C/C++

Michael Bader Master s Program Computational Science and Engineering C/C++ Tutorial Overview From Maple to C Variables, Operators, Statements Functions: declaration, definition, parameters Arrays and Pointers

### IMPERATIVE PROGRAMMING C LANGUAGE

J.NAWROCKI, M. ANTCZAK, H. ĆWIEK, W. FROHMBERG, A. HOFFA, M. KIERZYNKA, S. WĄSIK IMPERATIVE PROGRAMMING C LANGUAGE EX. 1. Write in C language programs described below, compile them and tentatively debug:

### The switch Statement. Multiple Selection. Multiple Selection (cont.)

The switch Statement Topics Multiple Selection switch Statement char Data Type and getchar( ) EOF constant Reading Section 4.7, 4.12 Multiple Selection So far, we have only seen binary selection. if (

### Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero THEN the Average is Sum divided by Count Conditions