Conditional Operator and Exercises Chapter 2
Conditional Operator and Exercises Chapter 2
if ( x >= 0 )
cout<< “positive”;
else
cout<< “negative”;
if ( a != 0 || b !=0 )
cin>>x;
else
cin>>y;
if ( a != 0 || b !=0 )
x = a;
else
x = b;
x = ( a != 0 || b !=0? a : b );
if ( a != 0 || b !=0 )
cin>>x;
else
x = 6;
we can not use the ?: because we don’t have the same statement in
the if and the else.
if ( a > 0 )
x = a;
else if ( b == 5)
x = b;
else
x = c;
x = ( a >0 ? a : (b == 5? b: c) );
in excel:
=IF(B3<-100,"too cold","not too cold")
=IF(B3<-100,"too cold", IF(B3<0,"cold","normal"))
int x;
…
switch ( x )
{
case 3:
cout << “USA, ”;
case 2:
cout << “Canada, ”; break;
case 1:
cout << “AUSTRALIA”; break;
}
// if x is 3 the output will be: USA, Canada,
int x = 1;
switch ( x )
{
case 3:
cout << "USA\n";
case 2:
cout << "canada\n";
case 1:
cout << "Aus\n";
case 4:
cout << "lebanon\n"; break;
case 5:
cout << "KSA\n";
case 6:
cout << "FRANCE"; break;
}
return 0;
}
OUTPUT: Aus
Lebanon
Write a program that takes an integer and prints whether it is a
prime number or not a prime number.
int n, count=0;
cout<<
cin>>n;
for (int i =1 ; i <=n; i++)
if (n%i == 0)
count++;
if (count == 2)
cout<< n << “ is prime”
else
cout<< n << “ is not prime”
another solution:
for (int i = 2 ; i < n/2; i++)//no more divisor greater than n/2
if (n%i == 0)
count++;
if (count == 0)
cout<< n << “ is prime”
else
cout<< n << “ is not prime”
Another solution
int n, F = 1;
for ( int i=2; i < n/2; i++)
if (n % i == 0)
{ cout << "not prime\n" ;
F = 0;
break;
}
if (F==1)
cout << "prime\n”;
for (int i = 1; i <= 5; i++)
{
for ( int j = 1; j <= 5; j++)
cout << ‘*’;
cout << endl;
}
*****
*****
*****
*****
*****
**
***
****
*****
for (int i = 1; i <= 5; i++)
{
for ( int j = 5; j >= i ; j--)
cout << ‘*’;
cout<< endl;
}
*****
****
***
**
*
for (int i = 1; i <=5; i++)
{
for ( int j = 1; j <= 5; j++)
if (i==1 || i == 5 || j == 1 || j == 5)
cout << ‘*’;
else
cout<< ‘\t‘; // the key tab (7 spaces)
cout<< endl;
}
* * * * * i==1
* *
* *
* *
* * * * * i == 5
j==1 j==5
for (int i = 1; i <=9; i++)
{
for ( int j = 1; j <= 9; j++)
if (i==1 || i==9 || j==1 || j==9 || i == j || i+j == 10)
cout << "* ";
else
cout<< '\t'; // tab
cout<< endl;
}
* * * * * * * * * i==1
* * * *
* * * *
* * * *
* * *
* * * *
* * * *
* * * *
* * * * * * * * * i == 9
j==1 j==9
can be seen as i + j == 10 or i == 10 - j or j == 10 - i
cout<< endl;
} N
* *
* *
* *
* *
* *
* *
* *
* *
x = 4 + (5 * 3 % (7 - 3)) * 5 / 2;
x = 4 + (5 * 3 % 4) * 5 / 2;
x = 4 + (15 % 4) * 5 / 2;
x = 4 + (3) * 5 / 2;
x = 4 + 3 * 5 / 2;
x = 4 + 15 / 2;