Crude Video Game Simulator Algorithm

Similar documents
Couple Notes about Boolean Expressions in C

(Python) Chapter 3: Repetition

Conditional Expressions

Repetition Structures

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

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

do, while and for Constructs

Use of scanf. scanf("%d", &number);

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

Advanced Computer Programming

Controls Structure for Repetition

Dept. of CSE, IIT KGP

Decision Making and Loops

Control structures in C. Going beyond sequential

Informatics Ingeniería en Electrónica y Automática Industrial. Control flow

Programming in C. Session 4. Seema Sirpal Delhi University Computer Centre

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Why Is Repetition Needed?

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

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

C Functions. 5.2 Program Modules in C

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

Flow Control. CSC215 Lecture

Introduction. C provides two styles of flow control:

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

Loops / Repetition Statements

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

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

Structured Programming. Dr. Mohamed Khedr Lecture 9

LOOPS. Repetition using the while statement

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

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements

Chapter 4. Flow of Control

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

Chapter 2. Section 2.3 if and if-else statements. CS 50 Hathairat Rattanasook

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Programming for Electrical and Computer Engineers. Loops

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

CSC 270 Survey of Programming Languages

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

Condition Controlled Loops. Introduction to Programming - Python

Looping. Arizona State University 1

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

21-Loops Part 2 text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie

YOLOP Language Reference Manual

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

Computers Programming Course 7. Iulian Năstac

Conditional Statement

C Programming Basics

3 The L oop Control Structure

Module 4: Decision-making and forming loops

Chapter 4: Making Decisions

3.2 for loop. Counting Loop

Chapter 4: Making Decisions

DECISION CONTROL AND LOOPING STATEMENTS

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

To become familiar with array manipulation, searching, and sorting.

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

Chapter 13 Control Structures

Chapter 3 Structured Program Development

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

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

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

Introduction to Computer Science Unit 3. Programs

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

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14

Problem Solving and 'C' Programming

ECE 122. Engineering Problem Solving with Java

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

CS150 Intro to CS I. Fall Fall 2017 CS150 - Intro to CS I 1

There are several files including the start of a unit test and the method stubs in MindNumber.java. Here is a preview of what you will do:

Chapter 4: Control structures. Repetition

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

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Expression and Operator

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

C 101. Davide Vernizzi. April 29, 2011

Programming for Engineers Iteration

New York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case. Instructions:

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

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

BEGINNER PHP Table of Contents

Review for Test 1 (Chapter 1-5)

Unit 7. 'while' Loops

METHODS EXERCISES GuessNumber and Sample run SumAll Sample Run

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

University of Maryland College Park Dept of Computer Science CMSC106 Fall 2016 Midterm I

LECTURE 04 MAKING DECISIONS

Chapter 4: Control structures

Loop structures and booleans

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

- If you want to repeat the same blocks of code over and over you have two choices. Copy

Welcome! COMP s1. Programming Fundamentals

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

Java Outline (Upto Exam 2)

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Transcription:

Crude Video Game Simulator Algorithm The following program will simulate free games at an arcade. The player will enter his/her score for 5 levels of play. The sum of these is their game score. If this exceeds 100,000, then the player gets a free game. The player continues to get free games if they exceed 100,000, and their total score is the sum of all of their game scores. This algorithm simulates this process and prints out the player s total score at the end of the game.

#include <stdio.h> int main() { int temp_score, game_score, total_score; int level, done = 0; total_score = 0; //Initialize player s total score. //Continue playing games until user fails to earn a free game while (done == 0) { // Initialize player s game score and level. game_score = 0; // Tabulate game score for all 5 levels for (level=1; level<=5; level++) { printf( What was your score on level %d?\n",level); scanf("%d", &temp_score); game_score = game_score + temp_score; // Compute new total score and stop if player has failed // to earn a free game. total_score = total_score + game_score; if (game_score < 100000) done = 1; else printf( Congratulations, you have won a free game!\n ); printf( Game Over! Your total score is %d\n", total_score); return 0;

The Comma Operator The comma operator allows multiple statements to execute on a single line. To do this, simply separate the two statements with a comma: stmt1, stmt2; An example of this would be: i = 0, j = 0; All this does is execute the leftmost statement first, followed by the rightmost statement. In most situations, you can just as easily write out two separate statements: i = 0; j = 0; The only situation where using the comma operator may be desirable is in a for loop. If you want to initialize two variables or increment two variables, you could do something like: for (i=0, j=0; i+j<20; i+=2, j--) {... My advice would be that unless you find a compelling reason to use the comma operator, don't use it. The example of page 98 of the text shows a potential problem of doing so.

Do-While Loop This is the third and last loop you will see. Here is the general syntax: do stmt; while (<bool exp>); Typically, the statement will be a block, so usually, we have: do { stmt1; stmt2;... stmtn; while (<bool exp>); stmta; Here is how this construct is evaluated when run: 1) Execute statements 1 through n. 2) Check the boolean expression. 3) If it is true, go back to step 1, otherwise continue execution with statement A. The key difference between this construct and the while construct is that the body of the loop must be executed at least once here. If you have this type of situation and it is easier for you to check the boolean condition AFTER you have executed a block of statements than before, then this loop may be a suitable choice.

Our favorite sum program...using a do-while /* Arup Guha 9/17/03 This program sums up the odd numbers in between 1 and 100, inclusive and prints this sum to the screen. */ #include <stdio.h> int main() { // Initialize variables. int val = 1; int sum = 0; // Add successive odd numbers. do { sum = sum + val; val = val + 2; while (val < 100); // Print out the result. printf("1+3+5+...+99=%d\n",sum); return 0;

Guessing Game! /* Arup Guha 9/17/03 This program allows the user to guess a secret number from 1 to 100. The user is told if their guess is too low or high and is allowed to guess again. */ #include <stdio.h> int main() { int secret_number; int guess; // Create secret number randomly. secret_number = 1+rand()%100; // Prompt user for a guess. printf("guess a number(1-100)\n"); do { // Read in guess and print out // appropriate response. scanf("%d", &guess) if (guess < secret_number) printf("your guess is too low!\n"); else if (guess > secret_number) printf("your guess is too high\n"); while (guess!= secret_number); // Print out winning message. printf("you guessed correctly!\n"); return 0;

The goto statement As the book says, generally speaking, this statement should not be used. There are a few instances where it makes code a bit more efficient and reduces the number of nested structures, but in my experience, when most introductory programmers use gotos, they don't do so efficiently and their code generally becomes confusing to them. The break and continue statements Both of these statements can be used to aid flow control in loops. In particular, here is what they do: break: Will break you out of the inner-most loop in which the break statement resides. continue: Will skip the following code within the inner-most loop in which the continue statement resides, returning the flow of control to the top of that loop.

Break Statement Example In the following code segment we will attempt to pick 10 random numbers. Each of the number picked must be greater than all the previous values picked. Each value will simply be printed to the screen. value = rand(); max = value; printf("number 1 = %d\n", value); for (i=2; i<=10; i++) { while (1) { if (value > max) { max = value; break; value = rand(); printf("number %d = %d\n", i, value);

Switch Statement This statement, just like the if statement, allows for conditional execution. The general construct is as follows: switch (<integer expression>) { case <value1>: <stmts1> break; case <value2>: <stmts2> break;... default: <stmtsn> stmta The manner in which this expression is evaluated is as follows: 1) The integer expression is evaluated. 2) If this expression is equal to value1, then <stmts1> are executed and the break statement carries the execution to stmta. 3) Otherwise, each value is compared th the integer expression value until one is found to match. At that point, the corresponding set of statements is executed and then the break carries execution to stmta. 4) If no listed value is equal to the value of the expression, then the default case is executed.

Couple notes: The lists of values may not include ranges of values, but only single values. Also, the break statements are not required, but without them, then several cases may get executed. This generally limits the use of case statements to situations where you know an expression will equal one of a few integer values and based on that want to execute a certain segment of code. You can emulate a case statement with an appropriate if statement. Here is an example of a case statement: switch (answer) { case 1: printf("you have selected #1.\n"); break; case 2: printf("you have selected #2.\n"); break; case 3: printf("you have selected #3.\n"); break; default: printf("invalid selection.\n");

Example using a continue statement In this segment of code, we add up n values entered by the user that are valid test scores in between 0 and 100, inclusive: count = 0; while (count < n) { scanf("%d", &score); if (score < 0 score > 100) continue; count++; sum = sum + score;

The Conditional Operator The general syntax of an expression using the conditional operator is as follows: <boolean expr1>? <arith expr2> : <arith expr3> This expression is evaluated as follows: 1) The boolean expression is evaluated. 2) If it is true, the entire expression evaluates to <arith expr2> 3) If it is false, the entire expression evaluates to <arith expr3> Basically, this is a short-hand notation to calculate an expression that could be calculated in an if statement. Here is an example of a segment of code that assigns x to the minimum of x and y, and y to the maximum of x and y. (Assume max and min are declared variables also.) max = (x < y)? x : y; min = (x > y)? x : y; Although this type of expression can shorten code, I believe it makes code more difficult to read at the expense of saving a couple lines of writing. Based on that observation, I do not recommend its use. (Though, you should understand the syntax of it in case you see it used in other peoples' code.)

Common Programming Errors w/loops 1) Creating infinite loops 2) putting a ; right at the end of a loop structure. (e.g. for (i=0;i<10;i++);) 3) Forgetting to put { around the loop body. 4) Creating an incorrect boolean expression. (e.g. using an && instead of an, or using the boolean expression with an opposite value of the one you should use.) 5) Off by one error - loop runs one too many or too few times. 6) Not using the loop index effectively inside of the body of the loop. 7) Forgetting to print a menu in a loop, or some other task that should be repeated each loop iteration.