[go: up one dir, main page]

0% found this document useful (0 votes)
2 views19 pages

cp lec 04 (1)

This document outlines a lab focused on conditional statements in C language, detailing arithmetic, assignment, and relational operators. It includes examples of if and if-else statements, along with practical tasks for students to implement, such as checking if a number is even or odd and converting centimeters to inches. The lab aims to enhance understanding of controlling program flow using conditional logic in C programming.

Uploaded by

ayenawall15
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views19 pages

cp lec 04 (1)

This document outlines a lab focused on conditional statements in C language, detailing arithmetic, assignment, and relational operators. It includes examples of if and if-else statements, along with practical tasks for students to implement, such as checking if a number is even or odd and converting centimeters to inches. The lab aims to enhance understanding of controlling program flow using conditional logic in C programming.

Uploaded by

ayenawall15
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Department of Mechatronics and Control Engineering

University of Engineering and Technology Lahore

LAB 4: CONDITIONAL STATEMENTS IN C LANGAUGE


MCT-142L: Computer Programming-I Lab

OBJECTIVE:
This lab will introduce conditional statements in C Language. At the end of this lab, you should be able to:

• Arithmetic, Assignment and Relational Operators in C


• Construct conditional statements in C
• Apply conditional statements to control program flow.

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:

Operator Description Example Result


int a = 10, b = 20;
+ Adds two operands int c = a + b; c = 30
int a = 10, b = 20;
- Subtracts second operand from the first int c = a - b; c = -10
int a = 10, b = 20;
* Multiplies both operands int c = a * b; c = 200
int a = 5, b = 10;
/ Divides numerator by denominator int c = b / a; c=2
Modulus operator: remainder of integer int a = 5, b = 10;
% division int c = b % a; c=0
int x = 10;
++x Pre-increment: increments before use int c = ++x; c = 11 (x becomes 11)
int x = 10;
x++ Post-increment: uses value, then increments int c = x++; c = 10 (x becomes 11)
int x = 10;
--x Pre-decrement: decrements before use int c = --x; c = 9 (x becomes 9)
int x = 10;
x-- Post-decrement: uses value, then decrements int c = x--; c = 10 (x becomes 9)

1|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Augmented Assignment Operators

The following table shows variants of the assignment operators supported by the C language.

Operator Description Example


Simple assignment operator. Assigns values from right c = a + b will assign the value of a
=
side operands to left side operand + b to c
Add and assignment operator. It adds the right operand to
+= c += a is equivalent to c = c + a
the left operand and assign the result to the left operand.
Subtract and assignment operator. It subtracts the right
-= operand from the left operand and assigns the result to the c-= a is equivalent to c = c - a
left operand.
Multiply and assignment operator. It multiplies the right
*= operand with the left operand and assigns the result to the c *= a is equivalent to c = c * a
left operand.
Divide and assignment operator. It divides the left operand
/= with the right operand and assigns the result to the left c /= a is equivalent to c = c / a
operand.
Modulus and assignment operator. It takes modulus using
%= c %= a is equivalent to c = c % a
two operands and assigns the result to the left operand.

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?

< Less than x<y Is x less than y?

>= Greater than or equal to x>=y Is x greater than or equal to y?

<= Less than or equal to x<=y Is x less than or equal to y?

== Equal to x==y Is x equal to y?

!= Not equal to x!=y Is x not equal to 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).

2|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Output of a relational operator:

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 output is:


0
1
0
5

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:

3|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

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;

printf("Enter Score in Test-I : ");


scanf("%f", &test1);

printf("Enter Score in Test-II : ");


scanf("%f", &test2);

printf("Enter Score in Test-III : ");


scanf("%f", &test3);

avg = (test1 + test2 + test3) / 3;

printf("Your Average Score is: %f", avg);

if(avg >= 90) {


printf("\nCongratulations on a High Average!");
}

return 0;
}

4|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

One sample execution of the program is shown here:


Enter Score in Test-I : 95
Enter Score in Test-II : 92
Enter Score in Test-III : 90
Your Average Score is: 92.333333
Congratulations on a High Average!

Another execution of the program is as under:


Enter Score in Test-I : 80
Enter Score in Test-II : 70
Enter Score in Test-III : 85
Your Average Score is: 78.333333

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

Take three test


scores

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:

5|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

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

Check the code:


#include <stdio.h>

int main() {
int x;

printf("Enter a number: ");


scanf("%d", &x);

if(x > 0) {
printf("x is positive\n");
printf("Positive numbers are great!\n");
}

6|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

printf("Thanks for your time.\n");

return 0;
}

If user enter 5 as input, this will be the output:


Enter a number: 5
x is positive
Positive numbers are great!
Thanks for your time.

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.

It can be shown in block diagram as:

if condition is
true?
YES

NO Do Task 1

Do Task 2

Do Task 3

7|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

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:

There can be multiple if statements in a program. A scenario is shown in flowchart below:

If Condition-I is true? YES

NO
Do Task 1

If Condition-II is true? YES

NO Do Task 2

The two if statements are independent here. There can be following scenarios:

• Condition-I True and Condition-II False: Task-1 will be executed only.


• Condition-I False and Condition-II True: Task-2 will be executed only.
• Both Conditions True: Both Tasks will be executed.
• Both Conditions False: None of the Tasks will be executed.

TASK 4.1: Even or Odd Number


Write a C language program that will ask the user to enter an integer
and will display if the entered number is Even or Odd.

8|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

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)

The flowchart of if-else statement is shown here:

NO If Condition is true? YES

Do Task 2 Do Task 1

9|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Check the following code:

#include <stdio.h>

int main() {
int x;

printf("Enter a number: ");


scanf("%d", &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");
}

printf("Thanks for your time.\n");

return 0;
}

One execution of the program is shown here:


Enter a number: 34
x is positive
Positive numbers are great!
Thanks for your time.

Another execution is here:


Enter a number: -57
x is negative
Negative numbers are scary!
Thanks for your time.

See carefully how different printf statements are part of different blocks. The last printf statement will be
executed every time we run the code.

TASK 4.2: Even or Odd Number


Write a program that will take a number form user and will display
whether the number is even or odd. Use if-else statement
Enter a positive integer >> 3
Sample Output 1

10 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

3 is Odd!
Enter a positive integer >> 24
Sample Output 2
24 is Even!

TASK 4.3: Centimeter to Inch Converter


Write a program that asks the user to enter a length in centimeters. If
the user enters a negative length, the program should tell the user that
the entry is invalid. Otherwise, the program should convert the length
to inches and print out the result. There are 2.54 centimeters in an
inch.

TASK 4.4: Numbers Closed or Not!


Write a program that asks the user for two positive numbers and prints
'Entered numbers are Closed!', if the numbers differ within 10 units
from each other and prints 'Entered numbers are Not Closed!' otherwise.
Use if-else statement.
Hint: Use fabs() function from math.h header file to calculate the
absolute of a number!
Enter first number: 85
Sample Output 1 Enter second number: 80
Entered numbers are Closed!
Enter first number: 10
Sample Output 2 Enter second number: -80
Entered numbers are not Closed!

TASK 4.5: Square root of a number (both +ve and -ve)


Write a program that will take a number from user and will display the
square root of it.
Explanation:

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;

11 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

This will be the output:


Square root of -4 is: nan

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.

How to make a negative number a positive equivalent?

If variable a contains a negative number we can use:


a=a*-1

or:
a*=-1

or fabs() function from math.h header file

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

TASK 4.6: Ratio of two numbers


Write a program that will take two numbers as input (say a and b) and
will show their ratio at output (a/b).
As you know, division by zero is not possible and an error occurs for
such case. You have to incorporate this problem in a way that if second
number entered is zero, program should not calculate the ratio; instead
it should display a message that division by zero is not possible.
Enter first number: 5
Sample Output 1 Enter second number: 2
Ratio of two numbers is: 2.500000
Enter first number: 16
Sample Output 2 Enter second number: 0
Division by zero is not possible!

TASK 4.7: Perfect Square


A perfect square is the one whose square-root is an integer e.g. 16 is
perfect square and 15 is not. Write a program that will take a number
from user and will display whether it is perfect square or not.

12 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Enter a positive integer: 25


Sample Output 1
25 is a Perfect Square
Enter a positive integer: 20
Sample Output 2
20 is NOT a Perfect Square

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.

Operator Description Example More Examples


(A=1, B=0)
Called Logical AND operator. If both the a==5 && b<3
&& operands are non-zero, then the condition (A && B) is false. Will be true if a contains 5
becomes true. and b is less than 3
Called Logical OR Operator. If any of the a==5 || b<3
|| two operands is non-zero, then the condition (A || B) is true. Will be true if a contains 5
becomes true. or b is less than 3.
Called Logical NOT Operator. It is used to ! b<3
!A is false
reverse the logical state of its operand. If a Will be true if b is not less
! !B is true
condition is true, then Logical NOT operator !(A && B) is true. than 3.
will make it false.

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");
}

13 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

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:

if (x < 0 || x > 100) {


printf("Entered number is not in the range of 0 to 100\n");
}
else {
printf("Entered number is between 0 and 100\n");
}

Note that (x <= 0 && x >= 100), and (x < 0 || x > 100) are complement of each other.

Yet another way to achieve the same is:


if (!(x >= 0 && x <= 100) ){
printf("Entered number is not in the range of 0 to 100\n");
}
else {
printf("Entered number is between 0 and 100\n");
}

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.

If we write it this way:


#include <stdio.h>
int main() {
float temp;
printf("Enter temperature(in Celsius): ");
scanf("%f", &temp);
if (temp > 100) {
printf("Warning!!!\n");
}
if (temp > 125) {
printf("High Alert\n");
}
return 0;
}

And input 130 as temperature, this will be the output:


Enter temperature(in Celsius): 130
Warning!!!
High Alert

14 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

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");
}

TASK 4.8: Average Marks with customized message


Write a program that will ask for the marks of five subjects and will
print the average of the marks. Moreover, a message will be printed out
depending upon average marks as:
If average is greater than or equal to 80 → You are an outstanding
student.
If average is greater than or equal to 70 but less than 80 → You are a
good student.
If average is greater than or equal to 60 but less than 70 → You are
an average student.
If average is greater than or equal to 50 but less than 60 → You are a
below-average student.
If average is greater than or equal to 40 but less than 50 → You are a
poor student.
If average is less than 40→ You need extra ordinary efforts

Max marks are 100 and you can assume that user will enter valid numbers.

Enter five subjects' marks: 74,68,82,65,87


Sample Output 1 Average of five subject marks is: 75.2
You are a good student

TASK 4.9: Area of a Triangle with check that it is a Valid Triangle

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.

Enter 1st side of triangle >> 6


Sample Output 1 Enter 2nd side of triangle >> 3

15 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Enter 3rd side of triangle >> 2

It is not a valid triangle...


Enter 1st side of triangle >> 4
Enter 2nd side of triangle >> 3
Sample Output 2 Enter 3rd side of triangle >> 5

The area of triangle is 6 sq. units

TASK 4.10: Maximum of three input numbers


Write a program that will take three numbers as input and will print
the maximum of three numbers at output. You have to use three if
statements.
Enter first integer: 12
Enter second integer: 16
Sample Output 1
Enter third integer: 5
16 is the largest

16 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

THE char DATATYPE:


In C programming, a char is a data type that is used to represent single characters. That includes alphabets
(like ‘A’, ‘a’), digits (like ‘2’, ‘3’) and special characters (like ‘@’, ‘#’, ‘%’). The char data type uses 1 byte
of memory, which means it can represent a total of 256 different values enough to cover all ASCII characters.
Here’s a simple example of how to use the char data type:

#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.

ASCII Codes of Characters:

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;
}

We can also use the type casting as:


int a = (int)letter;

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);

char letter1= 'm';


char letter2= letter1-'a'+'A';
printf("%c",letter2);

You can find the list of 256 ASCII codes here:

https://www.ascii-code.com/

Understanding Numeric and Character Representations:

17 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

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;

Relational Operations on Character Variables:

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

TASK 4.12: Insurance Eligibility


A company insures its employees in the following cases:
• If the employee is married
• If the employee is unmarried, male & above 30 years of age
• If the employee is unmarried, female & above 25 years of age
Write a program which takes marital status, gender and age as input
from user. After checking the given conditions, the output of the

18 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

program will a message stating whether he/she is eligible for insurance


or not.
Enter your marital status (M/U): U
Enter your gender (M/F): F
Sample Output 1 Enter your age: 28
Congratulations!
You are eligible for the insurance.
Enter your marital status (M/S): U
Enter your gender (M/F): M
Sample Output 2 Enter your age: 22
We are Sorry!
You are not eligible for the insurance.
You can use this code and complete the condition part:

#include <stdio.h>

int main() {
char S; //For marital Status
char G; //For Gender
int A; //For Age

printf("Enter your marital status (M/U): ");


scanf(" %c", &S);

printf("Enter your gender (M/F): ");


scanf(" %c", &G);

printf("Enter your age: ");


scanf("%d", &A);

if(S == 'M' ||) { //Complete the condition


printf("Congratulations!\n");
printf("You are eligible for the insurance.\n");
} else {
printf("We are Sorry.\n");
printf("You are not eligible for the insurance.\n");
}

return 0;
}

19 | P a g e Computer Programming-I Lab

You might also like