Elements of C in C++ data types if else statement for loops. random numbers rolling a die

Similar documents
Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Functions and Recursion

Chapter 3 - Functions

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

CS2141 Software Development using C/C++ C++ Basics

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

C++ PROGRAMMING SKILLS Part 4: Arrays

The following list represents the written codes in order:

Simulations. buffer of fixed capacity using the STL deque. modeling arrival times generating and processing jobs

Review of Important Topics in CS1600. Functions Arrays C-strings

Lab Instructor : Jean Lai

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

Lab # 02. Basic Elements of C++ _ Part1

Programming I Lecture 7

Programming. C++ Basics

Pointers and Strings Prentice Hall, Inc. All rights reserved.

Topic 2: C++ Programming fundamentals

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

Objectives. In this chapter, you will:

Exercise: Using Numbers

Chapter 3 - Functions

C Functions. 5.2 Program Modules in C

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Computer Science II Lecture 1 Introduction and Background

Chapter 3. Numeric Types, Expressions, and Output

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Introduction to Programming

C++ Quick Reference. switch Statements

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

A First Program - Greeting.cpp

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

Scientific Computing

CSCS 261 Programming Concepts Exam 1 Fall EXAM 1 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

Integer Data Types. Data Type. Data Types. int, short int, long int

Summary of basic C++-commands

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Chapter 2 - Control Structures

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter

Informatik I (D-ITET) Übungsstunde 5, Hossein Shafagh

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

2. Distinguish between a unary, a binary and a ternary operator. Give examples of C++ operators for each one of them.

Quadratic Sorting Algorithms

C++ Programming: From Problem Analysis to Program Design, Third Edition

Chapter 10 - Notes Applications of Arrays

Chapter 2 - Control Structures

Welcome to MCS 360. content expectations. using g++ input and output streams the namespace std. Euclid s algorithm the while and do-while statements

Computer Department. Question (1): State whether each of the following is true or false. Question (2): Select the correct answer from the following:

Lecture 3 Tao Wang 1

1. C++ Overview. C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions.

Getting started with C++ (Part 2)

Outline. Review of Last Week II. Review of Last Week. Computer Memory. Review Variables and Memory. February 7, Data Types

Expressions, Input, Output and Data Type Conversions

Introduction to Programming using C++

Introduction to Programming EC-105. Lecture 2

8. Floating-point Numbers II

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Programming Language. Functions. Eng. Anis Nazer First Semester

Chapter 3 Problem Solving and the Computer

Partha Sarathi Mandal

Engineering Problem Solving with C++, Etter/Ingber

Fundamentals of Programming CS-110. Lecture 2

Chapter 15 - C++ As A "Better C"

Outline. Functions. Functions. Predefined Functions. Example. Example. Predefined functions User-defined functions Actual parameters Formal parameters

Pointer Arithmetic. Lecture 4 Chapter 10. Robb T. Koether. Hampden-Sydney College. Wed, Jan 25, 2017

Lab 6. Review of Variables, Formatting & Loops By: Dr. John Abraham, Professor, UTPA

Hashing. mapping data to tables hashing integers and strings. aclasshash_table inserting and locating strings. inserting and locating strings

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

CS242 COMPUTER PROGRAMMING

Chapter Four: Loops II

Chapter 2 - Control Structures

int x = 5; double y = 3; // Integer division rounds the result down to the nearest whole number. cout << "1a: " << x / 3 << endl; //1

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

CS 117 Programming II, Spring 2018 Dr. Ghriga. Midterm Exam Estimated Time: 2 hours. March 21, DUE DATE: March 28, 2018 at 12:00 PM

Chapter 7 Arithmetic


Fixed-Point Math and Other Optimizations

Hashing. inserting and locating strings. MCS 360 Lecture 28 Introduction to Data Structures Jan Verschelde, 27 October 2010.

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

C++ Programming Lecture 11 Functions Part I

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Fundamentals of Programming Session 25

Transcription:

Elements of C in C++ 1 Types and Control Statements data types if else statement for loops 2 Simulations random numbers rolling a die 3 Functions and Pointers defining a function call by value and call by reference pointers and references MCS 360 Lecture 2 Introduction to Data Structures Jan Verschelde, 30 August 2017 Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 1 / 31

Elements of C in C++ 1 Types and Control Statements data types if else statement for loops 2 Simulations random numbers rolling a die 3 Functions and Pointers defining a function call by value and call by reference pointers and references Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 2 / 31

data types We can classify numerical data types as int : a subset of the integer numbers, double : double precision floating-point. The family of int types breaks up in 2 families: 1 bool, char, wchar t and unsigned integers size t, 2 short int (16), int (32), and long int (64 bits). The first bit is normally used for the sign. A floating-point number consists of a sign, fraction (or significand) and an exponent: float: 23 bits in fraction, 8 bits in exponent double: 52 bits in fraction, 11 bits in exponent long double: 63 bits in fractions, 15 bits in exponent Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 3 / 31

formatting doubles #include<iomanip> // include io manipulators double x = 1.2345e+9; double y = 456.789; cout << "x = " << x << ", y = " << y; x = 1.2345e+09, y = 456.789 cout << fixed << setprecision(2) << "x = " << x << ", y = " << y; x = 1234500000.00, y = 456.79 cout << scientific << setprecision(4) << "x = " << x << ", y = " << y; x = 1.2345e+09, y = 4.5679e+02 Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 4 / 31

Elements of C in C++ 1 Types and Control Statements data types if else statement for loops 2 Simulations random numbers rolling a die 3 Functions and Pointers defining a function call by value and call by reference pointers and references Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 5 / 31

coding a grading scale Grading scale from our course description: 90 100% = A, 80 89% = B, 70 79% = C, 60 69% = D, 0 59% = F. Input from user: score (a percentage). Output to screen: letter grade with as justification a reference to the corresponding percentage range. $ grading_scale Enter a percentage : 89.3 Score 90 equals the grade A, as 90 >= 90%. $ grading_scale Enter a percentage : 70 Score 70 equals the grade C, as 70% <= 70 <= 79%. $ grading_scale Enter a percentage : 23 Score 23 equals the grade F, as 23 <= 59%. $ Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 6 / 31

ceil() applied to a double #include<iostream> #include<math.h> using namespace std; int main() { double input; cout << "Enter a percentage : "; cin >> input; int score = ceil(input); ceil(x) returns the smallest integer not less than x Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 7 / 31

converting a double to an int There are three operations to convert a floating-point number, of type double to an integer, of type int. double input = 1.23; int ceilinput = ceil(input); // smallest largest int int castinput = (int) input; // truncated to integer int roundinput = round(input); // rounded to integer To convert an int to a double, wedoatype cast: int input = 123; double output = (double) input; The outcome of the division operator depends on the type. Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 8 / 31

a nested if else Applying the grading scale to score: char grade; if(score >= 90) grade = A ; else if(score >= 80) grade = B ; else if(score >= 70) grade = C ; else if(score >= 60) grade = D ; else grade = F ; cout << "Score " << score << " equals the grade " << grade << ", as "; Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 9 / 31

the switch statement The justification refers to the grading scale: switch(grade) { case A : cout << score << " >= 90%"; break; case B : cout << "80% <= " << score << " <= 89%"; break; case C : cout << "70% <= " << score << " <= 79%"; break; case D : cout << "60% <= " << score << " <= 69%"; break; default : cout << score << " <= 59%"; break; } cout << "." << endl; } return 0; Observe the break statement. Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 10 / 31

breaking out of a loop Recall the do-while in the greatest common divisor computation of x and y: int r; do { r = x % y; x = y; y = r; } while(r!= 0); We leave the loop as soon as remainder becomes zero: do { r = x % y; if(r == 0) break; x = y; y = r; } while(true); Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 11 / 31

Elements of C in C++ 1 Types and Control Statements data types if else statement for loops 2 Simulations random numbers rolling a die 3 Functions and Pointers defining a function call by value and call by reference pointers and references Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 12 / 31

for loops The do-while and while loops are good when the number of iterations is not known in advance. n To compute s = k: int s = 0; k=1 for(int k=1; k<=n; k++) s = s + k; is equivalent to int s = 0; int k = 1; while(k <= n) s = s + (k++); // s = s + k; k = k + 1; Important: s = s + (k++) s = s + (++k). Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 13 / 31

Elements of C in C++ 1 Types and Control Statements data types if else statement for loops 2 Simulations random numbers rolling a die 3 Functions and Pointers defining a function call by value and call by reference pointers and references Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 14 / 31

random numbers Via the C library, we generate pseudorandom numbers. Three steps: 1 include cstdlib, the C standard library 2 srand(s) set the seed of the generator to s Common practice: s is the current time. For debugging: s is fixed so get same sequence. 3 rand() returns an integer in 0..RAND MAX Use modulo operator % to limit range of numbers. For a random double in [0,1]: int r = rand() double d = double(r)/rand_max; The double(r) converts r to a double. Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 15 / 31

Elements of C in C++ 1 Types and Control Statements data types if else statement for loops 2 Simulations random numbers rolling a die 3 Functions and Pointers defining a function call by value and call by reference pointers and references Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 16 / 31

rolling a die To check if the pseudorandom numbers give a fair die, we run a simulation. $ die_freq Simulating the rolling of a die... give a positive integer : 100000 Frequency Table of 100000 times rolling a die : #0 : 16700 #1 : 16521 #2 : 16660 #3 : 16666 #4 : 16782 #5 : 16671 $ Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 17 / 31

defining a table #include<cstdlib> #include<ctime> #include<iostream> int main() { int n; std::cout << "Simulating the rolling of a die...\n"; std::cout << " give a positive integer : "; std::cin >> n; std::srand(time(0)); // set seed to time int freq[6] = {0, 0, 0, 0, 0, 0}; Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 18 / 31

updating the table for(int i=0; i<n; i++) { int d = std::rand() % 6; // std::cout << " " << d; freq[d] = freq[d] + 1; } std::cout << "\nfrequency Table" << " of " << n << " times rolling a die :\n"; for(int i=0; i<6; i++) std::cout << " #" << i << " : " << freq[i] << "\n"; } return 0; Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 19 / 31

Elements of C in C++ 1 Types and Control Statements data types if else statement for loops 2 Simulations random numbers rolling a die 3 Functions and Pointers defining a function call by value and call by reference pointers and references Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 20 / 31

defining a function A function has a prototype and a definition. Prototype of a d-sided die: int die ( int d ); // returns a number in the range 0..d-1 A definition of the function die: int die ( int d ) { int roll = rand() % d; return roll; } d is a parameter of the function die roll is a local variable of the function Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 21 / 31

Elements of C in C++ 1 Types and Control Statements data types if else statement for loops 2 Simulations random numbers rolling a die 3 Functions and Pointers defining a function call by value and call by reference pointers and references Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 22 / 31

call by value Using the function die in the simulation: for(int i=0; i<n; i++) { int d = die(6); freq[d] = freq[d] + 1; } The parameter of die is call by value: the value is copied to the parameter of die; the value of the parameter cannot change. Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 23 / 31

update with a function To update the frequency table with a function: void update ( int *t, int d ); // updates the table t with the die value d void indicates there is no return by *t we pass an address to the function void update ( int *t, int d ) { t[d] = t[d] + 1; } Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 24 / 31

call by reference In the function main(): int freq[6] = {0, 0, 0, 0, 0, 0}; for(int i=0; i<n; i++) { int d = die(6); update(freq,d); } Because freq is an array, the name freq refers to the address in memory of the first item in the array. Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 25 / 31

Elements of C in C++ 1 Types and Control Statements data types if else statement for loops 2 Simulations random numbers rolling a die 3 Functions and Pointers defining a function call by value and call by reference pointers and references Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 26 / 31

pointers double x = 1.234; double *p = &x; // address of x We have that p points to x: p &x x == *p 1.234 cout << "x = " << x << ", via p : " << *p << endl; double *q; q = &x; *q = *q + 1; // dereferencing q cout << "x = " << x << ", via p : " << *p << ", via q : " << *q << endl; x = 1.234, via p : 1.234 x = 2.234, via p : 2.234, via q : 2.234 Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 27 / 31

pointer arithmetic Arrays are consecutive items in memory: double a[3] = {1.23, 2.34, 3.45}; for(int i=0; i<3; i++) cout << " " << a[i]; cout << endl; is equivalent to double *p; p = a; for(int i=0; i<3; i++) cout << " " << *(p++); cout << endl; Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 28 / 31

references double y = 5.678; double &z = y; z is just another name for y cout << "y = " << y << ", z = " << z << endl; z = z + 1; cout << "y = " << y << ", z = " << z << endl; y = 5.678, z = 5.678 y = 6.678, z = 6.678 void swap ( double &a, double &b ) { double c = a; a = b; b = c; } Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 29 / 31

Summary + Exercises In this lecture we covered more of Chapter P. Exercises: 1 Use the pow from math.h to add a = pow(2,31) =2 31 and b =2 31. Explain the outcome of this addition. 2 Declare float x = 1.0; and double y = 1.0; and execute x = x + 1.0e-10 and y = y + 1.0e-10. Explain the difference between the outcomes. What is the machine precision for float? Andfordouble? 3 Print the ASCII table to screen, using the conversion char(i), for all integers i ranging from 0 to 255. 4 Convert the for loops in the simulation of rolling a die into while loops. Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 30 / 31

One Last Exercise 5 Consider the statements: const string one = " 一 "; const string two = " 二 "; const string three = " 三 "; const string four = " 四 "; const string five = " 五 "; const string six = " 六 "; const string seven = " 七 "; const string eight = " 八 "; const string nine = " 九 "; const string ten = " 十 "; const string numerals[] = {one, two, three, four, five, six, seven, eight, nine, ten}; Write a C++ program in a quiz for the user to recognize the Chinese numerals. An example question is type the value for 六 : Which Chinese numeral is displayed depends on a random number. The program replies with correct or wrong depending whether the answer of the user is correct or wrong. Introduction to Data Structures (MCS 360) Elements of C in C++ L-2 30 August 2017 31 / 31