Switch statement For selecting one choice from a list of choices switch statement evaluates an expression to determine a value Match the value with one.

Slides:



Advertisements
Similar presentations
Functions in C++. Functions  Groups a number of program statements into a unit & gives it a name.  Is a complete and independent program.  Divides.
Advertisements

CMSC 2021 C++ I/O and Other Topics. CMSC 2022 Using C++ Stream I/O Default input stream is called cin Default output stream is called cout Use the extraction.
CS 1620 File I/O. So far this semester all input has been from keyboard all output has been to computer screen these are just two examples of where to.
1 Text File I/O Chapter 6 Pages File I/O in an Object-Oriented Language Compare to File I/O in C. Instantiate an ofstream object. Like opening.
1 11/05/07CS150 Introduction to Computer Science 1 Functions Chapter 6, page 303.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
1 6/20/2015CS150 Introduction to Computer Science 1 Functions Chapter 6, 8.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
What is the out put #include using namespace std; void main() { int i; for(i=1;i
C++ Control Flow Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th -22 nd Sept 2006.
CS 117 Spring 2002 Review for Exam 3 arrays strings files classes.
CHAPTER 5 CONTROL STRUCTURES II (Repetition). In this chapter, you will:  Learn about repetition (looping) control structures  Explore how to construct.
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
M. Taimoor Khan #include void main() { //This is my first C++ Program /* This program will display a string message on.
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
C Programming Lecture 8-2 : Function (advanced). Recursive Function (recursion) A function that calls itself (in its definition) Classic example : factorial.
File I/O ifstreams and ofstreams Sections 11.1 &
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
CHAPTER 8 CONTROL STRUCTURES Prepared by: Lec. Ghader R. Kurdi.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Define our own data types We can define a new data type by defining a new class: class Student {...}; Class is a structured data type. Can we define our.
Chapter 05 (Part III) Control Statements: Part II.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
CSC1201: Programming Language 2 Lecture 1 Level 2 Course Nouf Aljaffan (C) CSC 1201 Course at KSU1.
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
1 Simple File I/O Chapter 11 Switch Statement Chapter 12.
Functions A function groups a set of related statements under a single title. You can "call" the function using its name. You may also provide parameters.
GE 211 Dr. Ahmed Telba. // compound assignment operators #include using namespace std; int main () { a =5 int a, b=3; a = b; a+=2; // equivalent to a=a+2.
Vectors One-Dimensional Containers. Problem A file contains a sequence of names and scores: Ann92 Bob84 Chris89... Using OCD, design and implement a program.
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
Loops and Files. 5.1 The Increment and Decrement Operators.
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Function Definition: Return_DT F_name (
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
CSC1201: Programming Language 2 1 Functions. 2 Function declaration: return_type FuncName( Type arg1, Type arg2,….. Type argN) { function body } A program.
Lecture 7 Computer Programming -1-. Conditional Statements 1- if Statement. 2- if ….. else Statement. 3- switch.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
C++ Programming Michael Griffiths Corporate Information and Computing Services The University of Sheffield
ifstreams and ofstreams
Topic 6 Recursion.
CS Computer Science IA: Procedural Programming
Lecture 3 C & C++ programming.
Lecture 9 Files, Pointers
Programming Fundamentals
TOPIC 4: REPETITION CONTROL STRUCTURE
CSC1201: Programming Language 2
Additional Control Structures
Chapter 3 Even More Flow of Control 1
when need to keep permanently
CS150 Introduction to Computer Science 1
Standard Input/Output Stream
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
CPS120: Introduction to Computer Science
Fundamental Programming
CSC1201: Programming Language 2
CS150 Introduction to Computer Science 1
ifstreams and ofstreams
Lecture 3 More on Flow Control, More on Functions,
File I/O in C++ I.
Functions Chapter No. 5.
Presentation transcript:

switch statement For selecting one choice from a list of choices switch statement evaluates an expression to determine a value Match the value with one of the several possible cases break is used to jump out when match happens.

char idChar; int aNumber, bNumber, cNumber; swtich( idChar) { case ‘A’: aNumber=aNumber+1; break; case ‘B’: bNumber=bNumber+1; break; case ‘C’: cNumber=cNumber+1; default: cout<<“error”; }

If we don’t use break it executes all commands after the selected choice. break is used to skip over a part of a program. If we use break in loop it cause to jump out of the loop. continue is used in loop and cause a program to skip the rest of the loop.

#include const int Arsize=20; // define a constant integer int spaces=0; int main() { char line[Arsiz]; cout<<“enter a line of text”<<endl; cin.get(line,Arsize); for(int i=0; line[i]!=‘ \0’;i++) { cout<<line[i]; if (line[i]==‘.’) break; if ( line[i] != ‘ ‘) continue; spaces++; }

cout<<“\n”<<spaces<<endl; return 0; }

What is the output of the following code int i,j; int counter=0; int total=0; int n; cin>>n; for(i=0; i<n ; i++) { if( counter % 2 ) continue; for( j=0; j< n-i; j++) { total+= counter – j; if ( ! (j % 2) ) continue; counter ++; }

cout<<total;

Writing to a Text File We need to declare the header file, which is fstream The fstream header file defines an ofstrem class for handling the output. ofstream outFile; outFile.open(“sample.txt”); char name[20]; cin>> name; outFile<<name;

cout<<“enter a file name “<<endl; cin>>name; ofstream fout; fout.open(name); if (! fout) // if ( !fout.is_open()) { cout<<“ file does not exist”<<endl; exit(1); } // if file exist open it otherwise it creates the file // we check whether it was successful or not double number; cin>>number; fout<<number; fout.close();

Reading from Input File We need to declare the header file, which is fstream The fstream header file defines an ifstrem class for handling the input file

#include #include //file I/O #include // for exit() const int size=60; int main() { char filename[size]; ifstream infile; cout<<“enter a file name”; cin.getline(filename,size); infile.open(filename); if( !infile.is_open()) { cout<<“not open”; exit(1); }

double value; double sum=0.0; int count=0; infile>>value; while ( infile.good()) // while good input { ++count; sum+=value; infile>>value; } if (infile.eof()) cout<<“end of file”<<endl; else if( infile.fail()) cout<<“data mismatch \n”;

else cout<<“with no reason terminate \n”; if (count==0) cout<<“ no data \n”; else { cout<<count<<endl; cout<<“sum = “<<sum; cout <<“Average= “<<sum/count<<endl; } infile.close(); return 0; }

Function Definition Syntax typeName functionName(parameterList) { statements; return value; }

#include int simple(int val1, int val2); // int main() { int a,b,sum; cout<<“enter two numbers”<<endl; cin>>a>>b; sum=simple(a,b); cout<<“the sum is = “<<sum; } int simple ( int val1, int val2) { int total; total=val1+val2; return total; }

int simple( int a,b); // not acceptable int simple( int, char); We can send array to function as a parameter.

#include const int ArSize=8; int sum_arr(int arr[], int n); int main() { int numbers[ArSize]={1,3,4,8,9,-1,2,0}; int sum=sum_arr(numbers,ArSize); cout<<“sum of the numbers is “<<sum; } int sum_arr(int arr[ ],int n) { int total=0; for(int i=0;i<ArSize;i++) total+= arr[i]; return total; }

We can write int sum_arr(int *arr, int n);

Function and Pointers double (*pf) (int ); // pf points to a function that return double; double *pf(int); // pf is a function that return a pointer to a // double

double pam( int ); double (*pf) (int); pf = pam; double ned(double); int ted (int); double (*pf)(int) pf= ned; /// ? pf= ted; /// ?

double pam(int); double (*pf) (int); pf=pam; double x=pam(4); double y=(*pf) (5); // call pam; We can write double y= pf(5);

#include double betsy(int); double pam(in); void estimate (int lines, double (*pf)(int)); void main() { int code; cout<<“how many line of code do you need?\n”; cin>>code; cout<<“ here is betsy estimate\n”; estimate(code, betsy); cout<<“ here is pam estimate\n”; estimate(code, pam); }

double betsy( int lns) { return 0.05 * lns; } double pam(int lns) { return 0.03*lns *lns*lns; } void estimate(int lns, double (*pf)(int)) { cout<<lns<<“lines will take “; cout<<(*pf)(lns)<<“hours(s) \n”; }

Recursive function In C++ a function can call itself. Note that main() can’t call itself. Recursive function are used in backtracking. Also are used in Artificial Intelligence.

Example for void function void recurs( argumentList) { statemts1; if (test) recurs (arguments); statements2; }

More Example #include long factorial ( int n); int void main() { int number; long fac_num; cout<<“enter a number less than 11”; cin>>n; fac_num=factorial(n); cout<<“factorial of “<<n<<“ is “<<fac_num; }

long factorial ( int n) { if (n <= 1) return 1; else return (n*factorial(n-1)); }

Write a program to read some numbers and print out them in reverse order. Input zero to quit. We are not allowed to use array.

void print_reverse(int n ) { cout<<“enter a number : zero for quit”<<endl; cin>>n; if( n ==0) return; print_reverse(n); cout<<n; }

Write a program to print out all the string of size n of 0, 1. ( n is an input);

include void all_string(int n, int max_size, int arr[ ]) { if(n==max_size) { for( int i=0; i<max_size; i++) cout<<arr[i]; cout<<endl; return; } arr[n]=0; all_string(n+1,max_size; arr); arr[n]=1; all_string(n+1,max_size;arr); }

int void main(); { int size; cout<<“enter an positive number”; cin>>size; if( size < 1) { cout<<“error”; exit(1); } int array=new int[size]; all_string(0,size,array); }

Write a program to print out power set of set {1,2,…,n} ( n is an input). Write a Maze program. Write a program to find all m-subset of an n-set.

Inline function When the time execution of a function is short it’s better to declare it as an inline function #include inline double square(double x) { return x*x; }

int main() { double a,b; double c=13.0; a= square(5.0); b=square( ); cout<<a<< “ “<<b; return 0; }

Call by Value & Call by Reference void swap ( int a, int b) { int temp; temp=a; a=b; b=temp; } int main() { int num1=4, num2=9; swap(num1,num2); cout<<num1<< “ “ <<num2; }

void swap1(int &a, int &b) { int temp; temp=a; a=b; b=temp; } void swap2(int *a, int *b) { int temp; temp=*a; *a=*b; *b=temp; }

int main() { int num1=4, int num2=9; swap1(num1,num2); cout<<num1<<“ “<<num2; swap2( &num1, &num2); cout<<num1<<“ “<<num2; }

When Using Reference Argument To allow you to alter a data in the calling function To speed up the program by passing a reference instead of an entire data object

Function Overloading Having more than one function with the same name. list of argument of a function are called signature of a function. We can have more than one function with the same name but they must have different signatures.

void print ( char * str, int length); void print( double d, int length); void print( long l, int d); void print (long v, int length);