cp lec 04 (1)
cp lec 04 (1)
OBJECTIVE:
This lab will introduce conditional statements in C Language. At the end of this lab, you should be able to:
APPARATUS:
• Laptop\PC with following tools installed
o Visual Studio Code with C/C++ and Code Runner Extensions
o C/C++ mingw-w64 tools for Windows 10
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume variable a holds
10 and variable b holds 20 then:
The following table shows variants of the assignment operators supported by the C language.
Relational Operators
Other than calculations, computer programs can compare and decide the calculations based on comparison
result. To compare two or more variables, we use Relational Operators. The list of relational operators is given
here:
Relational
Description Expression Expression Meaning
Operator
> Greater than x>y Is x greater than y?
It is important to note that double equal sign i.e. == is relational operator which checks
whether the two operands are equal or not and on the other hand single equal sign i.e. =
is assignment operator which assigns a value to variable(s).
The result of a relational operator expression is either True or False. In C programming language, True and
1 are same and likewise False and 0. This is also known as Boolean Data Type which can have value only
True or False. See the output of following code:
#include<stdio.h>
int main()
{
int x=10,y=5;
printf("%d\n", x==y);
printf("%d\n", x>=y);
printf("%d\n", y==7);
printf("%d\n", y);
return 0;
}
The first line assigns the values to variable x and y using assignment operator = . The second line is a Boolean
Expression as it involves Relational Operator. x==y means whether x is equal to y or not and of course they
are not equal and hence the output is 0 which indicates False. The third line is x>=y which means whether x
is greater than or equal to y or not. x having value 10 is greater than y having the value 5 and hence the output
is 1 which indicates True.
The next line is y==7 means whether value of y is equal to 7 or not and y having the value of 5 is not equal
to 7 and hence the output is 0 which indicates False. It is very important to note that y==7 checks whether
the variable y is equal to 7 or not and it never assigns 7 to y. Therefore, when value of y is printed after y==7
line, it still is 5.
The if statement:
The if statement is used to execute a part of the code based on some condition being true. If the condition is
false, then that part will not be executed. It can be shown in a flow chart as:
if condition is
true?
YES
NO
Do This
The program below shows an example of an if statement. The program asks user to enter three test scores
(out of hundred), and the program calculates their average. If the average is greater than 90, the program
congratulates the user on obtaining a high score.
#include <stdio.h>
int main() {
float test1, test2, test3, avg;
return 0;
}
If you see carefully the two outputs of the same program, in one case congratulation message is displayed
while it is not displayed for the second case. This is all because of the condition used in the program using if
statement is true in first case and false in second. The flowchart of above program can be shown like this:
Start
Calculate avg
if (avg>=90)
YES
Congratulations
NO
Message
END
Note carefully the syntax of the if statement. The braces {} indicate the block of if statement which will be
executed when condition of if statement is True. Here is syntax of if statement:
if(condition){
Statements
There can be as many statements as required to execute after the condition is true. In flow chart it is shown
below:
if condition is
true?
YES
Do This
NO
And Do This
Do This Too
int main() {
int x;
if(x > 0) {
printf("x is positive\n");
printf("Positive numbers are great!\n");
}
return 0;
}
The condition x>0 is true and we see the output lines. What do you think will be the output if entered
number is negative? Think about that before entering a negative number!
Enter a number: -5
Thanks for your time.
The third message of thanks is displayed even if the condition is false. See carefully the code that the first two
print statements are inside the {}. Therefore, the first two printf statements are dependent on the condition
and will be executed only if the condition is true (also known as Block of the if statement), while the third
printf statement is not the part of the Block of the if statement and will be executed independent of the
condition being true or false.
if condition is
true?
YES
NO Do Task 1
Do Task 2
Do Task 3
The Task-1 and Task-2 will be executed if the condition is true and the Task-3 will be executed every time.
Multiple if statements:
NO
Do Task 1
NO Do Task 2
The two if statements are independent here. There can be following scenarios:
Checking for a number being even or odd is simply a check whether number
is divisible by 2 or not i.e. remainder after division by 2 is 0 or not
Enter a positive integer >> 3
Sample Output 1
3 is Odd!
Enter a positive integer >> 24
Sample Output 2
24 is Even!
if-else statement:
In the if-else statement, a condition in the form of a Boolean expression is evaluated. If the expression is
true, a statement or block of statements is executed. If the expression is false, a separate block of statements
is executed. The syntax of the if-else statement is as under:
if(condition){
Statement(s)
else{
Statement(s)
Do Task 2 Do Task 1
#include <stdio.h>
int main() {
int x;
if(x >= 0) {
printf("x is positive\n");
printf("Positive numbers are great!\n");
}
else {
printf("x is negative\n");
printf("Negative numbers are scary!\n");
}
return 0;
}
See carefully how different printf statements are part of different blocks. The last printf statement will be
executed every time we run the code.
3 is Odd!
Enter a positive integer >> 24
Sample Output 2
24 is Even!
We can find the square root of the number using sqrt() function in math.h header file. But if we try to
pass a negative number as input argument, it will have the output as nan which stand for not a number.
In some programming languages it generates an error. For this code:
#include <stdio.h>
#include <math.h>
int main() {
printf("Square root of -4 is: %f",sqrt(-4));
return 0;
But we know that the square root of -4 is 2j. So, for this program you will take a number from the user and
then apply an if-else statement to check whether input number is positive or negative. If it is positive,
simply use sqrt() and display the result. If entered number is negative, make it positive, use sqrt() and
then display the result appending a 'j' with it.
or:
a*=-1
Enter a number: 8
Sample Output 1
Square root of 8 is: 2.828427
Enter a number: -10
Sample Output 2
Square root of -10 is: 3.162278 j
Logical Operators
Many times, we have to make decision on the basis of multiple conditions. Logical operators are used to
combine two or more logical expressions.
As an example, if we want to see whether an entered number is between 0 and 100, we can do it as:
#include <stdio.h>
int main() {
int x;
printf("Enter a number: ");
scanf("%d", &x);
if (x >= 0 && x <= 100) {
printf("Entered number is between 0 and 100\n");
} else {
printf("Entered number is not in the range of 0 to 100\n");
}
return 0;
}
Common Mistakes:
The logical operators must be used with great care. If we want to check a number not in range 0-100 then it is
a common mistake to write as:
if (x <= 0 && x >= 100) {
printf("Entered number is between 0 and 100\n");
}
else {
printf("Entered number is not in the range of 0 to 100\n");
}
This is wrong logic as there is no number which is both less than 0 and greater than 100 at the same time. The
above can also be done as:
Note that (x <= 0 && x >= 100), and (x < 0 || x > 100) are complement of each other.
Example:
In a chemical plant, a certain chemical reaction is sensitive to the plant temperature and based on current
temperature sensed by a sensor, an indication light is turned on. Yellow light turns on if temperature crosses
100oC and a red will turn on if it goes higher than 125oC. Let's write a program which simulates the above
situation in a way that user will be asked to enter temperature, if it is higher than 100 oC a warning message
will be displayed and if it crosses 125oC, a high alert message will be displayed.
Both messages are displayed because both conditions are true. The first condition must be written this way:
if (temp > 100 && temp <=125) {
printf("Warning!!!\n");
}
if (temp > 125) {
printf("High Alert\n");
}
Max marks are 100 and you can assume that user will enter valid numbers.
In one of the previous lab you did a task to take input three sides of
a triangle and show the area of triangle. We assumed that user will
always enter a valid triangle. As we know, for a valid triangle the
condition is that sum of any two sides should be greater than the third
one. Now update that program such that it takes three sides as input and
will print the area only if it is a valid triangle otherwise it should
print that triangle is invalid.
#include <stdio.h>
int main() {
char letter = 'Z';
printf("The character stored in the variable letter is: %c\n",
letter);
return 0;
}
Carefully see the format specifier %c. The same will be used for scanf. Moreover, we can have the relational
operations between the char variables.
Every character in C has an equivalent ASCII code. For example, the ASCII code for 'A' is 65, for 'B' is 66,
and so on. You can use the printf function with the %d format specifier to print the ASCII value of a
character. Here's an example:
#include <stdio.h>
int main() {
char letter = 'Z';
printf("The ASCII value of %c is: %d\n", letter, letter);
return 0;
}
This will save the ASCII code of the char variable letter in an integer variable a.
What do you think will be the output of following two code snippets:
char letter1= 'm';
char letter2= letter1+5;
printf("%c",letter2);
https://www.ascii-code.com/
In C, a numeric value such as 8 is an integer, while '8' is a character. The integer 8 represents the numerical
value eight, but the character '8' represents the ASCII value of the digit 8, which is 56. Here's a simple example
to illustrate this:
#include <stdio.h>
int main() {
int num = 8;
char ch = '8';
printf("The integer is: %d\n", num);
printf("The character is: %c\n", ch);
printf("The ASCII value of the character is: %d\n", ch);
return 0;
Just like integers and floating-point numbers, you can perform relational operations on characters. The
results of these operations are based on the ASCII values of the characters. Here's an example:
#include <stdio.h>
int main() {
char ch1 = 'a', ch2 = 'b';
if(ch1 < ch2)
printf("%c is less than %c\n", ch1, ch2);
else
printf("%c is not less than %c\n", ch1, ch2);
return 0;
}
This program will output "a is less than b" because the ASCII value of a'(97) is less than the ASCII
value of b (98).
TASK 4.11: Convert to Upper case letter
Write a program that will take a letter from the use (a-z or A-Z) and
will display the letter in Upper Case.
Enter a letter (a-z or A-Z) : r
Sample Output 1
In Upper case it is: R
Enter a letter (a-z or A-Z) : T
Sample Output 2
In Upper case it is: T
#include <stdio.h>
int main() {
char S; //For marital Status
char G; //For Gender
int A; //For Age
return 0;
}