Lesson 3: Selection: If, ?, Switch
Lesson 3: Selection: If, ?, Switch
Selection: if , ?, switch
Linear
programs
Selection
If. Syntax
diagram
If – special
forms
Selection operators are ' ?’ and ' : ‘. Both used together.
Format: < expresie_1 > ? <expresie_2> :
<expresie_3>
expresie_1 is evaluated. If is no-zero, expresie_2 is executed.
Else (if is equal to 0) expresie_3 is executed.
Examples :
If operation
Expresie Valoare
x > y ? z=x : z=y z - maxim dintre x şi y
x >= 0 ? z=x : z=-x z - modulul lui x
AND (&&)
X Y X && Y
False False False
False True False
True False False NOT (!)
True True True X !X
Logical
OR (||) False True
operators X Y X || Y True False
False False False
False True False
True False False
True True True
Scrieți un program care va
#include <stdio.h>
determina dacă 3 numere
introduse pot forma lungimile
int main() laturilor unui triunghi oarecare
{
float a,b,c;
printf("Sides: ");
scanf("%f %f %f", &a, &b, &c);
printf("Operation:");
q = getchar();
printf("Operators: ");
scanf("%f %f", &a, &b);
switch(q)
{ case '+' : c=a+b; break;
case '-' : c=a-b; break;
case '*' : c=a*b; break;
case '/' : c=a/b; break;
}
printf("%f %c %f = %f\n", a,q,b,c);
return 0;
}
Problem 1:
Roman numbers of length two
Problem 2
A correct roman number, Calculate solutions of quadratic
Problems formed from two digits is equation using switch / case
given.
Write a program to find it’s
arabic equivalent.
Example: VI – 6, IX - 9
#include <stdio.h>
#include <math.h>
int main()
{
float a, b, c;
The solution float root1, root2, imaginary;
(problem 2) float discriminant;
printf("Enter values of a, b, c : ");
scanf("%f %f %f", &a, &b, &c);
/* Calculate discriminant */
discriminant = (b * b) - (4 * a * c);
discriminant = (b * b) - (4 * a * c);
switch(discriminant > 0)
{
case 1:
The solution root1 = (-b + sqrt(discriminant))
(problem 2) / (2 * a);
root2 = (-b - sqrt(discriminant))
/ (2 * a);
printf("Two real roots: %.2f and %.2f",
root1, root2);
break;
case 0:
switch(discriminant < 0)
{
case 1:
root1 = root2 = -b / (2 * a);
imaginary = sqrt(-discriminant) / (2 * a);
printf("Two distinct complex roots:
%.2f + i%.2f and %.2f - i%.2f",
root1, imaginary, root2, imaginary);
The solution break;
(problem 2) case 0:
root1 = root2 = -b / (2 * a);
printf("Two equal real roots :
%.2f and %.2f", root1, root2);
break;
}
}
return 0;
}