Professional Documents
Culture Documents
Exercises For Laboratory Work 2: X If X X If X X F
Exercises For Laboratory Work 2: X If X X If X X F
The aim of the Laboratory Work 2: to write a program in C++ using if-else
statements, to input the values of the variables from the keyboard and to display the
result of the program on the screen.
Exercises:
Write a C++ program using statements: if and else to calculate the function y = f
(x).
5 x 2 6, if 2 x 5; x 3 5 , if x 0;
1. f x 2. f x
x 7, if x 5;
3
3x 4 9, if - 3 x 0;
x tgx, if x 1.5;
x cos x, if x 1.22;
3. f x x 3 sin x, if 1.5 x 2.5; 4. f x
5x 1.7, if x 1.22;
3
3x 3 5, if x 2.5;
3x3 4 cos x, if 0 x 1;
x x , if 5 x 0;
2
7. f x 8. f x
5 sin 2 x9 , if x 1;
5 x cos x, if 0 x 2;
3
x cos 2 x sin x, if 0 x 1;
x 2 sin x x 2 1.2 , if x 0;
9. f x x 2 6 sin x , if 1 x 2; 10 f x 2
1.7 x3 7, if x 2; tg x cos x 3.5, if 2 x 6;
11. f x sin x x 6 , if 0 x 4; 12. f x 1.7 x sin x , if 0 x 2;
2
ln x 3x 7 , if x 4; cos x tgx, if 2 x 6;
13. f x x
sin 5 x * 1 x 2 ln 2 x , if 1 x 3;
14.
x x , if 1 x 1;
f x
4
e * x e 2 x , if 3 x 5;
tg 3x ln 5 x, if 1 x 4;
2
7 x 8.1, if 1 x 7;
2 x 2 3, if x 0;
15. f x 2 16. f x 4
x cos x, if x 7; 4 x 1, if - 5 x 0;
x cos x, if x 1.5;
x sin x, if x 3.28;
17. f x x 3 sin x, if 1.5 x 7.5; 18. f x
2 x 1.9, if x 3.28;
3
9 x 3 8, if x 7.5;
x 2 sin x, if 0 x 8; x cos x, if x 1.7;
19. f x 2 x 4 6, if x 8; 20. f x x 3 sin x, if 1.7 x 9.5;
2 x 3 2, if x 9.5;
3x 2.3, if 5 x 6;
2
2.4 Example:
Write a C++ program using statements: if and else to calculate the function y = f
(x).
Exercise 1:
x cos x, if x 1.5;
f x x 2 sin x, if 1.5 x 3.5;
9 x 2 8, if x 3.5;
Solution 1:
// lab2.1 in C++
#include <iostream>
#include <math.h>
int main()
{
float x, y;
cout << "Lab 2 ";
cout << '\n';
cout << "Enter x: ";
cin >>x;
cout << '\n';
if (x<0.5)
{
y = x*cos(x);
}
if (x>=1.5 && x<3.5)
{
y=x*x+sin(x);
}
if (x>=3.5)
{
y=9*x*x+8;
}
cout << "y= " << y;
return 0;
}
Run the program and you will see on the screen of monitor:
Lab 2
Enter x: 4
y= 152
or Solution 2:
// lab2.2 in C++
#include <iostream>
#include <math.h>
int main()
{
float x, y;
cout << "Lab 2 ";
cout << '\n';
cout << "Enter x: ";
cin >>x;
cout << '\n';
if (x<0.5)
{
y = x*cos(x);
}
else if (x>=1.5 && x<3.5)
{
y=x*x+sin(x);
}
else if (x>=3.5)
{
y=9*x*x+8;
}
cout << "y= " << y;
return 0;
}
Run the program and you will see on the screen of monitor:
Lab 2
Enter x: 4
y= 152
2.5 Questions
1. What is the syntax for C++ if…else statement?
2. What is the syntax for nested if…else statement?
3. Draw the flowchart of if statement.
4. How if...else statement works?
5. Draw the flowchart of if…else statement.
6. When we use conditional/ternary operator?
7. Write the example where you use conditional/ternary operator instead of a if...else
statement.