IP Lecture 3 ConditionalStatements (Autosaved)
IP Lecture 3 ConditionalStatements (Autosaved)
statements
Course Code: CSC1102 &1103 Course Title: Introduction to Programming
Character Input/Output
The if statement
if ( expression )
program statement
no If expression is true
expression (non-zero), executes
statement.
yes If gives you the choice
of executing statement
Program statement or skipping it.
Example - if
remainder = number_to_test % 2;
if ( remainder == 0 ){
cout<<"The number is even“<<endl;}
else{
cout<<"The number is odd“<<endl;}
return 0;
}
Logical operators
Example: 5 || 0 is 1
Precedence of operators
Precedence
!, ++, --, (type)
*, /, % Example for operator precedence:
+, - a > b && b > c || b > d
Is equivalent to:
<, <=, >, >=, ==, != ((a > b) && (b > c)) || (b > d)
&&
||
=
Example: compound relational
test
/* Program to determine if a number is even or odd
and also the number cannot be negative */
int main (){
int number_to_test, remainder;
cout<<“Enter your number to be tested: ”<<endl;
cin>>number_to_test;
remainder = number_to_test % 2;
if (number_to_test >= 0){
if (remainder == 0 ){
cout<<"The number is even“<<endl;}
else{
cout<<"The number is odd“<<endl;}
}
else{
cout<< “Not valid”;}
return 0;
}
Example:3
Example:4
Flowchart to determine if a year is a leap
year
Start
Input year
rem_4 = year % 4;
rem_100 = year % 100;
rem_400 = year % 400;
End
Example: compound relational
test
// Program to determine if a year is a leap year or not
int main ()
{
int year, rem_4, rem_100, rem_400;
cout<<"Enter the year to be tested: “<<endl;
cin>>year;
rem_4 = year % 4;
rem_100 = year % 100;
rem_400 = year % 400;
return 0;
}
Nested if
statements
Multiple choices – else-if
int number;
if ( expression 1)
program statement 1
if negative
else if ( expression 2)
program statement 2
else
program statement 3
else if zero
Statement list on
switch (operator) a case can miss !
{
...
case '*':
case 'x':
printf ("%.2f\n", value1 * value2);
break;
...
}
Example - switch
The conditional operator
condition ? expression1 : expression2
maxValue = ( a > b ) ? a : b;
Equivalent to:
if ( a > b )
maxValue = a;
else
maxValue = b;
Example 1
#include <iostream>
#include <string>
using namespace std;
int main() {
double marks; // take input from users
cout << "Enter your marks: ";
cin >> marks;
// ternary operator checks if
// marks is greater than 40
string result = (marks >= 40) ? "passed" :
"failed";
cout << "You " << result << " the exam.";
return 0;
}
Example 2
#include <iostream>
#include <string>
using namespace std;
int main() {
int number = 0;
string result;
// nested ternary operator to find whether
// number is positive, negative, or zero
result = (number == 0) ? "Zero" : ((number > 0) ? "Positive" :
"Negative");
cout << "Number is " << result;
return 0;
}