TP_2_Answers (1)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Larbi Tebessi University- Tebessa

Department of mathematics and computer science, L1

Algorithms and data structure

Lab2: Conditional Statements


1-
- Review the provided code.
- Identify and correct any syntax errors or logical mistakes.
- After correcting the code, explain what the program does.

#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number > 0)
printf("The number is positive\n");
else if (number < 0)
printf("The number is negative\n");
else
printf("The number is zero\n")
}

1. Solution :

Identified and Corrected Errors:


1. Formatting:
• Adding proper indentation and line breaks makes the code easier to read.
2. Missing Semicolon:
• In the original code, the last printf statement (for "The number is zero") is missing a
semicolon. In C, each statement must end with a semicolon, we should add it.
3. Braces for if-else Blocks:
• Adding braces {} around each if, else if, and else block is generally good practice, even if
the block contains only one statement. This helps prevent errors if additional
statements are added later.
4. return 0; at the End of main():
• It’s a good practice to include return 0; at the end of the main function to indicate
successful program termination.
Explanation of What the Program Does:
This program prompts the user to enter an integer and then checks if the number is positive,
negative, or zero. It uses an if-else statement to determine the sign of the number and displays the
result to the user.

2. Parity of Product
Write a program that prompts the user for two numbers and then informs whether their product is negative or
positive. Remark: You should not calculate the product of the two numbers.

2. Solution :
Description:
• This program utilizes the printf function to exhibit messages. The scanf function to gather
user input.
• It verifies whether either of the numbers is zero, as, in that scenario the product would also be
zero.
• If both numbers are either positive or negative then their product will be positive.
• However if one number is positive and the other is negative their product will be negative.

1. Checking if the two variables have the same sign

#include <stdio.h>
int main() {
int nbr1, nbr2;
// Ask the user to input two numbers
printf("Enter the first number: ");
scanf("%d", &nbr1);
printf("Enter the second number: ");
scanf("%d", &nbr2);
// Determine the sign of the product
if (nbr1 == 0 || nbr2 == 0) {
printf("The product is zero.\n");
} else if ((nbr1 > 0 && nbr2 > 0) || (nbr1 < 0 && nbr2 < 0)) {
printf("The product is positive.\n");
} else {
printf("The product is negative.\n");
}

return 0;

}
2. Checking if the two variables have different signs
#include <stdio.h>
int main() {
int nbr1, nbr2;
// Ask the user to input two numbers
printf("Enter the first number: ");
scanf("%d", &nbr1);
printf("Enter the second number: ");
scanf("%d", &nbr2);

// Determine the sign of the product


if (nbr1 == 0 || nbr2 == 0) {
printf("The product is zero.\n");
} else if ((nbr1 < 0 && nbr2 > 0) || (nbr1 > 0 && nbr2 < 0)) {
printf("The product is negative.\n");
} else {
printf("The product is positive.\n");
}

return 0;
}

Description Of the Update:


• The modified else if condition now checks if one number is negative and the other is
positive. In such cases, the product would be negative.
The final else block now covers cases where both numbers are either positive or negative,
resulting in a positive product
3. Photocopying
A reprographics shop charges 5 DA for the first ten photocopies, 4 DA for the next twenty, and 3 DA
for any additional copies. Write a program that asks the user for the number of photocopies made
and displays the total invoice price.

3. Solution
Description:
• This program prompts the user to enter the number of photocopies they need.
• The program then calculates the cost of the ten copies, the twenty copies and any
additional copies based on the provided rates (5 DA, 4 DA and 3 DA respectively). The
program presents a breakdown of the cost, for each category ( ten, next twenty additional)
as well as the total price.
• To clearly outline each part of the cost calculation variables such, as first_ten_copies,
next_twenty_copies, additional_copies, first_ten_price, next_twenty_price and
additional_price are utilized.

#include <stdio.h>

int main() {
int copies;
float total_price = 0.0;
float first_ten_price, next_twenty_price, additional_price;
int first_ten_copies, next_twenty_copies, additional_copies;

// Ask the user for the number of photocopies


printf("Enter the number of photocopies made: ");
scanf("%d", &copies);

if (copies <= 10) {


first_ten_copies = copies;
next_twenty_copies = 0;
additional_copies = 0;

first_ten_price = first_ten_copies * 5;
next_twenty_price = 0;
additional_price = 0;
} else if (copies <= 30) {
first_ten_copies = 10;
next_twenty_copies = copies - 10;
additional_copies = 0;

first_ten_price = 10 * 5;
next_twenty_price = next_twenty_copies * 4;
additional_price = 0;
} else {
first_ten_copies = 10;
next_twenty_copies = 20;
additional_copies = copies - 30;

first_ten_price = 10 * 5;
next_twenty_price = 20 * 4;
additional_price = additional_copies * 3;
}

// Calculate the total price


total_price = first_ten_price + next_twenty_price + additional_price;

// Display the detailed cost breakdown


printf("Cost breakdown:\n");
printf("First 10 copies (5 DA each): %.2f DA\n", first_ten_price);
printf("Next 20 copies (4 DA each): %.2f DA\n", next_twenty_price);
printf("Additional copies (3 DA each): %.2f DA\n", additional_price);
printf("Total price: %.2f DA\n", total_price);

return 0;
}
4. Quadratic Equation Solver

Write a program to solve the equation ax2 + bx + c = 0, considering all special cases.

4. Solution

Description :

• The comment block at the beginning explains the overall purpose of the program.
• Each section of the code is preceded by comments that explain what that part of the code
is doing.
• The code is structured to be straightforward and easy to follow, with clear variable names
and step-by-step logic.
• The program handles different cases:
- When 'a' is 0, the equation is linear, not quadratic.
- For quadratic equations, it calculates the discriminant (Delta).
- Based on the discriminant value, the program determines:
* Two real and distinct roots,
* One real and repeated root,
* Or two complex roots.
The user is prompted to input the values of a, b, and c, and the program outputs the roots of
the equation.

/*
Quadratic Equation Solver
This program solves equations of the form ax^2 + bx + c = 0.

*/

#include <stdio.h>
#include <math.h>

int main() {
float a, b, c, Delta, x1, x2, R_part, i_part;

// Input: Ask the user to enter the coefficients a, b, and c


printf("Enter coefficients a, b and c of the equation ax^2 + bx + c = 0: ");
scanf("%f %f %f", &a, &b, &c);

// Check if 'a' is zero which means the equation is linear, not quadratic
if (a == 0) {
printf("The equation is not quadratic, but linear.\n");
// If 'b' is also zero, the equation has no solution or infinite solutions
if (b == 0) {
if (c == 0) {
printf("Infinite solutions.\n");
} else {
printf("No solution.\n");
}
} else {
// Calculate and display the root for linear equation
x1 = -c / b;
printf("The solution is: %f\n", x1);
}
} else {
// Calculate the discriminant (Delta)
Delta = b*b - 4*a*c;

// Check the nature of the discriminant to determine the root type


if (Delta > 0) {
// Two distinct real roots
x1 = (-b + sqrt(Delta)) / (2*a);
x2 = (-b - sqrt(Delta)) / (2*a);
printf("Two distinct real roots: %.2f and %.2f\n", x1, x2);
} else if (Delta == 0) {
// One real and repeated root
x1 = -b / (2*a);
printf("One real and repeated root: %.2f\n", x1);
} else {
// Two complex roots
R_part = -b / (2*a);
i_part = sqrt(-Delta) / (2*a);
printf("Two complex roots: %.2f + %.2fi and %.2f - %.2fi\n", R_part, i_part, R_part, i_part);
}
}

return 0;
}
5. Which Day?
Write a program that allows displaying the day corresponding to a number from 1 to 7 entered by the
user. Solve this problem using two methods: nested if statements and a switch statement.

5. Solution

Description :
The program using conditional statements performs the following operations:
1. Takes User Input: It prompts you to enter a number between 1 and 7. This number
represents a day of the week, where 1 is for Monday, 2 for Tuesday, and so on up to 7 for
Sunday.
2. Processes the Input:
• Using Nested if Statements: The program first uses a series of if and else if
statements to determine which day of the week corresponds to the number you
entered. For example, if you enter 1, it identifies it as "Monday".
• Using a switch Statement: After the if statements, it does the same task using a
switch statement. This is a different method to handle multiple conditions. The
program matches your input with a case in the switch (like case 1: for Monday) and
then executes the code associated with that case.
1. Outputs the Result: For both methods (nested if and switch), the program prints out a
message telling you which day of the week corresponds to the number you entered. For
example, if you enter 3, it prints "The date equivalent to the number 3 is: Wednesday".

#include <stdio.h>

int main() {
int day_number;

// Ask the user to input a number between 1 and 7


printf("Enter a number (1-7): ");
scanf("%d", &day_number);

// Using nested if statements


if (day_number == 1) {
printf("The day of the week that corresponds to the entered number %d is: Monday\n", day_number);
} else if (day_number == 2) {
printf("The day of the week that corresponds to the entered number %d is: Tuesday\n", day_number);
} else if (day_number == 3) {
printf("The day of the week that corresponds to the entered number %d is: Wednesday\n", day_number);
} else if (day_number == 4) {
printf("The day of the week that corresponds to the entered number %d is: Thursday\n", day_number);
} else if (day_number == 5) {
printf("The day of the week that corresponds to the entered number %d is: Friday\n", day_number);
} else if (day_number == 6) {
printf("The day of the week that corresponds to the entered number %d is: Saturday\n", day_number);
} else if (day_number == 7) {
printf("The day of the week that corresponds to the entered number %d is: Sunday\n", day_number);
} else {
printf("Invalid number. Please enter a number from 1 to 7.\n");
}

// Using a switch statement


switch (day_number) {
case 1: printf("The day of the week that corresponds to the entered number %d is: Monday\n",
day_number); break;
case 2: printf("The day of the week that corresponds to the entered number %d is: Tuesday\n",
day_number); break;
case 3: printf("The day of the week that corresponds to the entered number %d is: Wednesday\n",
day_number); break;
case 4: printf("The day of the week that corresponds to the entered number %d is: Thursday\n",
day_number); break;
case 5: printf("The day of the week that corresponds to the entered number %d is: Friday\n",
day_number); break;
case 6: printf("The day of the week that corresponds to the entered number %d is: Saturday\n",
day_number); break;
case 7: printf("The day of the week that corresponds to the entered number %d is: Sunday\n",
day_number); break;
default: printf("Invalid number. Please enter a number from 1 to 7.\n");
}
return 0;
}

.
6. Calculator
Write a program that simulates a calculator. The program takes two real numbers entered by the user.
Depending on the choice made from a menu displayed on the screen, the program calculates the
sum, product, average, minimum, or maximum of these two numbers. The menu should be presented
to the user as follows:
**************** MENU *******************
1: ----------> Sum ------------------
2: ----------> Product ----------------
3: ----------> Average ----------------
4: ----------> Minimum ----------------
5: ----------> Maximum ----------------
-----------------------------------------
Enter your choice?

6. Solution

Description :
A. With simple answer to the user
• The program starts by including the stdio.h header file, which is necessary for input and
output functions.
• It then declares float variables real1 and real2 to store the real numbers entered by the
user, and result to store the outcome of the chosen operation.
• The user is prompted to input two real numbers, which are read and stored in real1 and
real2.
• A menu is displayed, showing the available operations. The user is asked to choose one
by entering a corresponding number.
• A switch statement is used to perform the operation based on the user's choice. Each
case in the switch corresponds to an arithmetic operation.

/*
Calculator Program _ Simple Message
- This program performs basic arithmetic operations on two real numbers.
- The user can choose to calculate the sum, product, average, minimum, or maximum.

*/

#include <stdio.h> // Standard Input-Output header for printf and scanf functions

int main() {
float real1, real2, result; // Variables to store the two real numbers and the result
int choice; // Variable to store the user's choice

// Prompting the user to enter two real numbers


printf("Enter the first real number: ");
scanf("%f", &real1);
printf("Enter the second real number: ");
scanf("%f", &real2);
// Displaying the menu for the user to choose an operation
printf("\n");
printf("**************** MENU *******************\n");
printf("\n");
printf(" 1: -------- > Sum <-------------\n");
printf(" 2: -------- > Product <-------------\n");
printf(" 3: -------- > Average <-------------\n");
printf(" 4: -------- > Minimum <-------------\n");
printf(" 5: -------- > Maximum <-------------\n");
printf("\n");
printf("-----------------------------------------\n");

printf("\n\n");

// Asking the user to make his choice.


printf("Enter the number of operation you want to perform (1-5): ");
scanf("%d", &choice);

// Calculating the result based on the user's choice


switch (choice) {
case 1: // Sum
result = real1 + real2;
break;
case 2: // Product
result = real1 * real2;
break;
case 3: // Average
result = (real1 + real2) / 2;
break;
case 4: // Minimum
result = (real1 < real2) ? real1 : real2;
break;
case 5: // Maximum
result = (real1 > real2) ? real1 : real2;
break;
default: // Invalid choice
printf("\n");
printf("Invalid choice. Please enter a number between 1 and 5.\n");
return 1; // Exiting the program due to invalid input
}

// Displaying the result


printf("Result: %.2f\n", result);

return 0; // Indicating successful program termination


}
B. Using a detailed answer for the user :

• The program now includes a character array operation to store the name of the chosen
operation.
• Based on the user's choice in the switch statement, not only is the result calculated, but
the operation string is also updated with the corresponding operation name using
strcpy().
• Finally, the result is displayed with a message that specifies the operation, like "The result
of the Product operation is: ...".

#include <stdio.h> // Include standard input-output library

int main() {
float real1, real2, result; // Variables to store the real numbers and the result
int choice; // Variable to store the user's choice
char operation[10]; // String to store the name of the operation

// Prompting the user to enter two real numbers


printf("Enter the first real number: ");
scanf("%f", &real1);
printf("Enter the second real number: ");
scanf("%f", &real2);

// Displaying the menu for the user to choose an operation


printf("\n");
printf("**************** MENU *******************\n");
printf("\n");
printf(" 1: -------- > Sum <-------------\n");
printf(" 2: -------- > Product <-------------\n");
printf(" 3: -------- > Average <-------------\n");
printf(" 4: -------- > Minimum <-------------\n");
printf(" 5: -------- > Maximum <-------------\n");
printf("\n");
printf("-----------------------------------------\n");

printf("\n\n");

// Asking the user to make his choice.


printf("Enter the number of operation you want to perform (1-5): ");
scanf("%d", &choice);

// Performing the operation based on the user's choice


switch (choice) {
case 1: // Sum
result = real1 + real2;
strcpy(operation, "Sum");
break;
case 2: // Product
result = real1 * real2;
strcpy(operation, "Product");
break;
case 3: // Average
result = (real1 + real2) / 2;
strcpy(operation, "Average");
break;
case 4: // Minimum
result = (real1 < real2) ? real1 : real2;
strcpy(operation, "Minimum");
break;
case 5: // Maximum
result = (real1 > real2) ? real1 : real2;
strcpy(operation, "Maximum");
break;
default: // Invalid choice
printf("Invalid choice. Please enter a number between 1 and 5.\n");
return 1; // Exiting the program due to invalid input
}

// Displaying the result with the specified operation


printf("The result of the %s operation is: %.2f\n", operation, result);

return 0; // Successful program termination


}

You might also like