CHAPTER 3 ML FUNDAMENTALS OF PROGRAMMING With C++ HANDOUT v1 0
CHAPTER 3 ML FUNDAMENTALS OF PROGRAMMING With C++ HANDOUT v1 0
Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 2 of 68 Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 3 of 68
Fundamentals of Programming with C++ MicroLink Informa on Technology College 2016 (2024 GC) Fundamentals of Programming with C++ MicroLink Informa on Technology College 2016 (2024 GC)
A statement causes an action to be performed. In C++, a statement controls the sequence of execution,
evaluates an expression, or does nothing (the null statement). The basic structure of any program can be
represented like this:
Begin
Statement
Statement
Statements
Simple Compound Selection Iterative Jump
Statement Statement Statement Statement Statement
do-while
simple if for loop while loop goto
loop
nested if
1. Simple Statement
A simple statement is a computa on terminated by a semicolon. Variable de ni ons and semicolon- terminated
expressions are representa ves pf this category.
Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 4 of 68 Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 38 of 68
Fundamentals of Programming with C++ MicroLink Informa on Technology College 2016 (2024 GC) Fundamentals of Programming with C++ MicroLink Informa on Technology College 2016 (2024 GC)
x++; // this has a side-e ect First expression is evaluated. If the outcome is nonzero then statement is executed. Otherwise, nothing
m+3; //useless statement b/c it has no side-e ect; result is just discarded
happens. For example, when dividing two values, we may want to check that the denominator is nonzero:
The simplest statement is the null statement which consists of just a semicolon: if (count != 0)
average = sum / count;
; // null statement To make mul ple statements dependent on the same condi on, we can use a compound statement:
2. Compound Statement if (balance > 0) {
Compound statement is a unit of code consis ng of zero or more statements; hence the name compound. interest = balance * creditRate;
This consists of an opening brace, an op onal declara on and de ni on sec on, and an op onal statement balance += interest;
sec on, followed by a closing brace. }
For example: ✓ A variant form of the if statement allows us to specify two alterna ve statements: one which is
executed if a condi on is sa s ed and one which is executed if the condi on is not sa s ed. This is
{ int min, i = 10, j = 20; called the if-else statement and has the general form:
if (expression)
min = (i < j ? i : j);
statement1;
cout << min << '\n'; else
statement2;
}
✓ First expression is evaluated. If the outcome is nonzero then statement1 is executed. Otherwise,
Compound statements are useful in two ways: statement2 is executed.
For example:
(i) They allow us to put mul ple statements in places where otherwise only single statements are
allowed, and if (balance > 0) {
(ii) They allow us to introduce a new scope (part of the program text within which a variable remains interest = balance * creditRate;
de ned in the program) in the program. For example, the scope of min, i, and j in the above balance += interest;
example is from where they are de ned ll the closing brace of the compound statement. Outside }
the compound statement, these variables are not de ned. else {
Notes: Because a compound statement may contain variable de ni ons and de nes a scope for them, it interest = balance * debitRate;
is also called a block. balance += interest;
A block does not need a semi colon. }
Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 39 of 68 Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 40 of 68
Fundamentals of Programming with C++ MicroLink Informa on Technology College 2016 (2024 GC) Fundamentals of Programming with C++ MicroLink Informa on Technology College 2016 (2024 GC)
int main ( ) { else if (ch >= 'a' && ch <= 'z')
cout << "Please type the number 8 : "; cout<<"the character "<<ch<<"Small le er le er";
cin >> x; else
if (x == 8) cout<<"the character "<<ch<<"It is a special character";
cout << "Thank you! I appreciate that." << endl;
else { 3.2 Mul ple-way Selec on
cout << "Why can't you follow simple instructions?<< endl; The switch statement provides a way of choosing between a set of alterna ves, based on the value of an expression.
} The general form of the switch statement is:
}
switch (expression) {
Note: If statements may be nested by having an if statement appear inside another if statement. For case constant 1:
example: statements;
.....
if (callHour > 6) {
case constant n:
if (callDura on <= 5)
statements;
charge = callDura on * tarrif1;
default:
else
statements;
charge = 5 * tarrif1 + (callDura on - 5) * tarrif2;
}
}
✓ First expression (called the switch tag or case selector) is evaluated, and the outcome is compared to
else
each of the numeric constants (called case labels), in the order they appear, un l a match is found.
charge = atFee;
The statements following the matching case are then executed. Note the plural: each case may be
followed by zero or more statements (not just one statement). Execu on con nues un l either a
✓ A frequently-used form of nested if statements involve the else part consis ng of another if-else break statement is encountered or all intervening statements un l the end of the switch statement
statement like:
are executed. The nal default case is op onal and is exercised if none of the earlier cases provide a
void main( ) {
match.
Char ch;
Cout<<"Enter a character"<<endl;
Cin>>ch; E.g.1 The following example prompts user to enter an operator and 2 operands and generate the
expression result with the selected operator on the operands.
if (ch >= 0 && ch <= 9) int main () {
cout<<"the character "<<ch<<"is a number"; int operand1, operand2;
else { char operator;
if (ch >= 'A' && ch <= 'Z') cout <<"enter two numbers"<<endl;
cout<<"the character "<<ch<<"capital le er"; cin >> operand1>>operand2;
else { cout <<"enter one of the these operators ‘+’ , ’*’ , ‘/’ , ‘%’ "<<endl;
if (ch >= 'a' && ch <= 'z') cin >> operator;
cout<<"the character "<<ch<<"Small le er le er"; switch (operator) {
else case '+':
cout<<"the character "<<ch<<"It is a special character"; cout<<operand1 + operand2;
} break;
} case '-':
} cout<<operand1 - operand2;
For improved readability, it is conven onal to format such cases as follows: break;
if (ch >= '0' && ch <= '9') case '*':
cout<<"the character "<<ch<<"is a number"; cout<<operand1 * operand2;
else if (cha >= 'A' && ch <= 'Z') break;
cout<<"the character "<<ch<<"capital le er"; case '/':
Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 41 of 68 Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 42 of 68
Fundamentals of Programming with C++ MicroLink Informa on Technology College 2016 (2024 GC) Fundamentals of Programming with C++ MicroLink Informa on Technology College 2016 (2024 GC)
cout<<operand1 / operand2; for (expression1; expression2; expression3)
break;
for (ini aliza on; expression; variable update)
default:
cout << "unknown operator: " << operator << ‘\n'; ✓ First expression1 is evaluated. Each me round the
break; loop, expression2 is evaluated. If the outcome is
} nonzero then statement is executed and expression3
} is evaluated. Otherwise, the loop is terminated.
It should be obvious that any switch statement can also be wri en as mul ple else-if statements. The above ✓ The most common use of for loops is for situa ons
statement, for example, may be wri en as: where a variable is incremented or decremented
with each itera on of the loop.
int main () {
int operand1, operand2;
//calculates the sum of numbers from 1 through n
char operator;
double result; void main ( ) {
cout <<" Enter two Integers "<<endl; int sum = 0, n;
cin >> operand1>>operand2; cout << "Enter the maximum number" << endl;
cout <<"Enter one of the arithme c operators ‘+’ , ’*’ , ‘/’ , ‘%’ "<<endl; cin >> n;
cin>> operator; for (int i = 1; i <= n; ++i)
if (operator == '+') sum += i;
cout<<operand1 + operand2;
cout << "the sum of numbers from 1 to << n << " is =: " << sum;
else if (operator == '-')
cout<< operand1 - operand2; }
else if (operator == 'x' || operator == '*')
E.g. 1
cout<< operand1 * operand2;
else if (operator == '/') #include<iostream >//displays the squares of the numbers [1,20]
cout<< operand1 / operand2; #include<iomanip.h> // for setw( ),
else void main ( ) {
cout << "unknown operator: " << operator << '\n'; int n;
} for (n=1; n<=20; n++) {
cout << setw(4) << n;
int sq = n*n;
However, the switch version is arguably neater in this case. In general, preference should be given to the
cout<<setw (6) << sq<<endl;
switch version when possible. The if-else approach should be reserved for situa on where a switch cannot
} //end of loop
do the job (e.g., when the condi ons involved are not simple equality expressions, or when the case labels
} // end of program.
are not numeric constants).
Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 43 of 68 Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 44 of 68
Fundamentals of Programming with C++ MicroLink Informa on Technology College 2016 (2024 GC) Fundamentals of Programming with C++ MicroLink Informa on Technology College 2016 (2024 GC)
cout << "The sum of all the numbers from 1 to "; E.g 2
cout << limit << " is " << sum; // An example of a while loop
return 0; #include <iostream>
}
Using namespace std:
int main () {
4.2 The while statement int number;
The while statement (also called the while loop) provides a cout << "Please type a number bigger than 10 : ";
way of repea ng a statement while a condi on holds. cin >> number;
Syntax: while (number <= 10) {
while ( expression ) cout << "No, bigger than 10! Try again: ";
Statements;
cin >> number;
}
✓ First expression (called the loop condition) is }
evaluated. If the outcome is nonzero then statement
(called the loop body) is executed and the whole
process is repeated. Otherwise, the loop is 4.3 The do...while statement
terminated. The do statement (also called do loop) is similar to the while statement, except that its body is executed first
and then the loop condition is examined.
//the while logic for summing numbers from 1 through n Syntax: do
void main ( ) { statement;
int sum =0, i=1, n; while (expression);
cout << "Enter the maximum number" << endl;
cin >> n; ✓ First statement is executed and then expression is evaluated. If the outcome of the latter is nonzero
while ( i <= n ) then the whole process is repeated. Otherwise, the loop is terminated.
sum += i++; ✓ The do loop is less frequently used than the while loop. It is useful for situations where we need the
cout << "The sum of numbers from 1 to << n << " is =: " << sum; loop body to be executed at least once, regardless of the loop condition.
} //the DO while logic for summing numbers from 1 through n
void main() {
E.g. 1 int sum = 0,i=1,n;
cout<<"Enter the maximum number"<<endl;
//a program to display numbers from 100 to 1
cin>>n;
#include<iostream.h>
do
#include <iomanip.h>
sum += i++;
void main ( ) {
cout<<"the sum of numbers from 1 to <<n<<"is =:"<<sum;
int x = 100;
}
while (x>=1) {
cout<< setw(4)<<x<<endl; E.g.1
x--; //the following program displays “Hello’’ un l one presses ‘N’
} //end of while loop
return; #include<iostream.h>
} //end of main prog #include<conio.h>
void main ()
{
char ch;
Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 45 of 68 Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 46 of 68
Fundamentals of Programming with C++ MicroLink Informa on Technology College 2016 (2024 GC) Fundamentals of Programming with C++ MicroLink Informa on Technology College 2016 (2024 GC)
do { cout << "Correct!" << endl;
else
cout<<"Hello!\n"; cout << "No, try again!" << endl;
cout<<"Do you want to display more Hello's (Y/N) "; }
while (answer != 2*x + 30 - x);
cin >>ch; }
}
} while (ch != 'N');
getch(); 4. Jump statements
} 4.5.1 Break statement
This statement causes an exist from a loop or decision block. It takes the control from the inner block to the
E.g. 2 outer (out of the following closing brace). In switch statement it is used to exit from the switch statement. A
/* this prog asks the user to type a number from 1 to 10 (inclusive) and refuses to accept any number break statement only applies to the loop or switch immediately enclosing it. It is an error to use the break
outside that range. */
statement outside a loop or a switch.
#include <iostream.h>
void main () { E.g. /* this prog converts characters from small case to upper case if they are wri en in small
int my_number; cases. The loop body will be prematurely terminated by the break statement if ‘N’ is
int valid; // 1 if the number is valid, pressed,
// 0 otherwise
cout << "Please enter a number from 1 to 10 : "; */
do
#include<iostream.h>
{ cin >> my_number;
valid = 1; // by default #include<conio.h>
if (my_number < 1)
valid = 0; #include<ctype.h>
if (my_number > 10) void main( ) {
valid = 0;
if (valid == 0) char ch;
cout << "I said from 1 to 10! Try again : ";
} for( int i=1; i<=26;i++) {
while (valid == 0); cout<<"Enter a character ";
cout << "Thank you." << endl;
} cin>>ch;
char up=toupper(ch); // converts character from
4.4 Nested Loop Statements
We can stick/nest one loop statement inside another one. In such cases, the resulting loop statement is cout<<"upper case "<<up; // lower case to upper one
called a nested loop statement. In principle, you can have as many loops nested inside each other as you
cout<<"\nCon nue [Y/N] ";
like.
cin>>ch;
//this prog demonstrates the nesting of loop statements
#include <iostream.h> if (ch = = 'N')
void main () {
break; // exit out of loop.
int x, answer;
for (x = 1; x <= 10; x++) { }
cout << "Question " << x << endl;
cout << "What is the answer to " << 2*x cout<<"Thanks";
<< " + " << (30 - x) << " ? : "; getch();
do {
cin >> answer; }
if (answer == 2*x + 30 - x)
Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 47 of 68 Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 48 of 68
Fundamentals of Programming with C++ MicroLink Informa on Technology College 2016 (2024 GC) Fundamentals of Programming with C++ MicroLink Informa on Technology College 2016 (2024 GC)
4.5.2 The con nue statement ✓ For a function whose return type is void, expression should be empty:
The continue statement terminates the current itera on of a loop and instead jumps to the next itera on. It
applies, just like the break statement, to the loop immediately enclosing the con nue statement. In while int main (void) {
and do loops, the next itera on commences from the loop condi on. In a for loop, the next itera on cout << "Hello World\n";
return 0;
commences from the loop’s third expression. }
E.g. //the following program displays even natural numbers below 100
#include<iostream>
#include<iomanip.h>
#include<conio.h>
void main () {
for (int i=1; i<=100; i++) {
if (i%2!= 0)
con nue;
else
cout<<setw(4)<<i<<endl;
}
getch();
}
out:
//etc...
return;
Note:
✓ The only function we have discussed so far is main, whose return type is always int. The return
value of main is what the program returns to the operating system when it completes its
execution.
Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 49 of 68 Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 50 of 68
Fundamentals of Programming with C++ MicroLink Informa on Technology College 2016 (2024 GC) Fundamentals of Programming with C++ MicroLink Informa on Technology College 2016 (2024 GC)
8. If the originally x=2 ,y=1 and z=1, what are the value of x, y, z after executing the following code?
Switch(x) {
case 0 : x = 2;
Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 51 of 68 Prepared by: Eyasu G.Z. (MSc, MA) Department of Computer Science, Arada Giorgis Campus, A.A. Page 52 of 68