Lecture - Notes - II - B Operators
Lecture - Notes - II - B Operators
int main() {
int number ;
(number%2==0)?cout<<"number is even":cout<<
"number is odd";
return 0;
}
switch
• used instead of if-else when there are more than two
alternatives/conditions available.
syntax
switch(variable or integer expression) {
case constant1:
block of statements;
break;
case constant2:
block of statements;
break;
... .
default:
block of statements; }
execution flow
https://www.programiz.com/cpp-
programming/switch-case
example
int main(){
char vowel;
cout << "enter a vowel: ";
cin >> vowel;
switch(vowel) {
case 'a': cout << “first vowel is a";
break;
case 'e': cout << “first vowel is e";
break;
case 'i': cout << “first vowel is i";
break;
case 'o': cout << “first vowel is o";
break;
case 'u': cout << “first vowel is u";
break;
default : cout << "no vowel was entered";
}
return 0; }
Repetition
• Iteration / Looping
• loops are:
do … while statement
for statement
while
syntax
int main()
{
int n, sum=0;
return 0;
}
do … while
• a variant of while
syntax
do
{
Block of statements;
}
while (test expression)
execution flow
• execute block of statements first.
int main()
{
int n,sum=0;
do {
sum += n;
n++;
} while(n < 10);
return 0;
}
for
syntax
int main()
{
int n, sum=0;
return 0;
}
example 2
a program to find the sum of natural numbers
#include <iostream>
using namespace std;
int main() {
int n, sum = 0;
cout << “enter a positive integer: ";
cin >> n;
for (int i = 1; i <= n; ++i) {
sum += i;
}
cout << "Sum = " << sum;
return 0;
}