0% found this document useful (0 votes)
19 views11 pages

C Programming Lab: Quadratics & Debugging

Uploaded by

joelgeorge2021
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)
19 views11 pages

C Programming Lab: Quadratics & Debugging

Uploaded by

joelgeorge2021
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

Lab Report 1

Introduction to C programming

School of Engineering: University of Guelph

ENGG1410

October 6, 2024

Lab #3 - Solving quadratic equations, cartesian coordinates and debugging in C

Group #6 - Joel George, Sohum Deshpande


Problem Statements

Part 1 - Solving a quadratic equation:

In this part, we wrote a program that solves a quadratic equation in the form of the equation

2
𝑎𝑥 + 𝑏𝑥 + 𝑐 = 0. The program asks the user to enter values for a, b, and c, it checks the

discriminant to understand whether the roots are real and distinct, real and equal or imaginary.

Based on that, it either calculates the roots or tells the user that the roots are imaginary. The main

issue I had with this part was understanding how to utilize the math in order to get the desired

output from what the user provides.

Part 2 - Cartesian Coordinates:

For this section, the program takes x and y coordinates from the user and determines whether the

point is on an axis, in a quadrant (if so which quadrant) or at the origin. The coordinates are then

rounded to two decimal places before figuring out the point’s location. Figuring out what to use

to tackle this problem and calculating the dot product of the vectors and the magnitudes in order

to apply the cosine rule correctly was one issue which required some time and effort in planning.
Debugging:

Part 3 - Simulating a dice roll game:

In this part, we were given a program that simulates a dice rolling game and we were required to

debug the program. The code had multiple issues such as assignment and logic errors and

spotting all these errors was quite a challenge.

Part 4 - Calculating letter grade from students marks:

For this last section, we worked on debugging a program that calculates a student’s final grade

based on quiz, assignment and exam scores. There were a few problems for this one mainly with

the char variables and weight calculations. There was some logical errors but the overall

difficulty I found with this was that it was time consuming and you have to pay close attention to

each part.
Assumptions and constraints

Assumptions:

● For part 1 - assuming the user will enter valid coefficients a, b, and c, with a not being 0

● Part 2 - assume the user will input valid floating point numbers for the coordinates.

● Part 3 - The user will have to understand the game rules and follow the instructions

correctly.

● Part 4 - We assume the user will enter valid integer marks for all the forms of assessment.

Constraints:

● For part 1 - The program only calculates real roots and will not handle complex numbers.

● Part 2 - The program rounds results to the nearest hundredth.

● Part 3 - The program needs to seed the random number generator to make sure different

dice rolls.

● Part 4 - The program only accepts marks within the specified ranges for each of the

categories.

Solutions to the problem

Part 1 - Solving a quadratic equation


To solve this quadratic equation program, we started by asking the user for the coefficients a, b,

and c using printf and scanf to take in the float [Link] also implemented an if statement to

make sure that a is not zero since it would invalidate the quadratic equation, if they did it would

print a error message. Then , we calculated the discriminant using the provided equation to

determine the type of roots. Depending on the value of D, we used conditional statements to

calculate and also display the roots. If D > 0, we computed two distinct real roots, if D = 0 we

found one real root but if D < 0 then we showed the roots are imaginary.

Part 2 - Cartesian Coordinates

(The program required math.h library ) For this program, we asked the user to input the x and y

coordinates, rounding them to the nearest hundredth for precision using the round function. After

we implemented checks using conditional statements to determine if the point was at origin, on

an axis, or in one of the four quadrants. Doing this involved evaluating the rounded values and

providing the required output based on the position of the point.

Part 3 - Simulating a dice rolling game

In the dice roll simulation, we began by seeding the random number generator with srand() and

corrected the syntax for generating random numbers by changing the == to = for assignment. We

calculated the sum of two dice rolls and used condition statements to evaluate the outcome which

is winning, losing or to continue the game. After making the changes the program displayed the

right results that were needed.


Part 4 - Calculating letter grade from student marks

In order to calculate the final score and letter grade, we asked the user for all of the three forms

of assessment marks, and then corrected errors such as the messing address of operators which

were in the scanf and also using the correct syntax for the character assignment. We calculated

the weighted average and applied a bonus, utilizing arithmetic operations and conditional

statements to determine the final score and the specified letter grade. After debugging the

program displayed the results that we desired. I found that going line by line like I'm writing the

code from scratch makes debugging less time consuming and aids me in finding the right

solutions.

Conclusion and self assessment

In this lab, I successfully used various new C concepts for all the sections including solving

quadratic equations, determining the position of points in cartesian coordinates, debugging the

dice roll game, and calculating students grades. I felt each part helped add on to my

understanding of conditional statements, mathematical functions, and input/output operations.

As said previously at the start, I struggled with the math operations and how to utilize them

efficiently in code but after this lab I believe that I received enough practice for me to be

confident in knowing how to use it when given a specific problem. I learned the main importance

of handling different scenarios, such as checking the discriminant for quadratic equations and

rounding coordinates correctly. Debugging parts 3 and 4 allowed me to improve my problem

solving skills and made me come up with more efficient methods to save time while thoroughly
checking for errors in the program. Overall, this lab was beneficial in making me understand

how to structure and execute different algorithms effectively. I see some areas I can improve on

and with practicing these concepts through the lab and at home I feel I can be thorough in

debugging and programming.

Code:

Part 1:

#include <stdio.h>

#include <math.h>

int main(){

float a, b, c, discriminant, root1, root2;

printf("Enter the coefficients a, b and c: ");

scanf("%f,%f,%f", &a, &b, &c);

if(a==0){

printf("invalid input as the program is meant to solve quadratic equations \n");

return 1;

discriminant = (b*b)-(4*a*c);

if(discriminant>0){

root1=(-b + sqrt(discriminant))/2*a;

root2=(-b - sqrt(discriminant))/2*a;

printf("The roots are real and distinct \n");

printf("root 1: %.2f \n", root1);


printf("root 2: %.2f \n", root2);

}else if(discriminant==0){

root1=(-b / 2*a);

printf("The roots are real and equal \n");

printf("root: %.2f \n", root1);

}else{

printf("The roots are imaginary");

return 0;

Part 2:

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

int main() {
double x, y;

printf("Enter the x-coordinate in floating point: ");


scanf("%lf", &x);

printf("Enter the y-coordinate in floating point: ");


scanf("%lf", &y);

x = round(x * 100) / 100;


y = round(y * 100) / 100;

if (x == 0.00 && y == 0.00) {


printf("(%.2f, %.2f) is at the origin.\n", x, y);
}

else if (y == 0.00) {
printf("(%.2f, %.2f) is on the x axis.\n", x, y);
}

else if (x == 0.00) {
printf("(%.2f, %.2f) is on the y axis.\n", x, y);
}

else {
if (x > 0 && y > 0) {
printf("(%.2f, %.2f) is in quadrant I.\n", x, y);
} else if (x < 0 && y > 0) {
printf("(%.2f, %.2f) is in quadrant II.\n", x, y);
} else if (x < 0 && y < 0) {
printf("(%.2f, %.2f) is in quadrant III.\n", x, y);
} else if (x > 0 && y < 0) {
printf("(%.2f, %.2f) is in quadrant IV.\n", x, y);
}
}

return 0;
}

Part 3:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int dice1, dice2, sum;
char play_again;
srand(time(0)); // Should have time
dice1 = (rand() % 6)+1; // should have +1 to roll from 1 to 6 and should have 1 = for assignment
dice2 = (rand() % 6)+1; // same thing here
sum = dice1 + dice2;
printf("You rolled a %d and a %d.\n", dice1, dice2);
printf("The sum is %d.\n", sum);
if (sum == 7 || sum == 11) {
printf("You win!\n");
} else if (sum == 2 || sum == 3 || sum == 12) { //sum = 12 should be == 12 conditional operator
printf("You lose!\n");
} else {
printf("No win or loss, play again.\n", play_again); //variable play_again should be declared here
}
return 0;
}

Part 4:

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

int main() {
int quiz1, quiz2, assignment, exam;
double weighted_average, final_score, bonus;
char grade;

printf("Enter marks for Quiz 1 (out of 20): ");


scanf("%d", &quiz1);
printf("Enter marks for Quiz 2 (out of 20): ");
scanf("%d", &quiz2);
printf("Enter marks for the Assignment (out of 50): ");
scanf("%d", &assignment);
printf("Enter marks for the Exam (out of 100): ");
scanf("%d", &exam);

weighted_average =
((((quiz1 + quiz2) / 2.0) / 0.20) * 0.2) + ((assignment / 0.5) * 0.3) + (exam * 0.5);

bonus = ceil(weighted_average * 0.1); // Bonus calculation


final_score = weighted_average + bonus;

printf("Weighted Average: %.2lf\n", weighted_average);


printf("Bonus: %.2lf\n", bonus);
printf("Final Score: %.2lf\n", final_score);

if (final_score >= 90) {


grade = 'A';
} else if (final_score >= 80 && final_score < 90) {
grade = 'B';
} else if (final_score >= 70 && final_score < 80) {
grade = 'C';
} else if (final_score >= 60 && final_score < 70) {
grade = 'D';
} else {
grade = 'F';
}
printf("Your final grade is: %c\n", grade);
return 0;

Common questions

Powered by AI

The cosine rule helps in determining the relative position of a point by comparing angle measurements derived from coordinate vectors and their magnitudes. Implementing this involves computing dot products and magnitudes to apply the rule accurately when classifying a point’s location. One difficulty faced was selecting appropriate calculations that apply the cosine rule correctly, necessitating strategic planning to effectively use vector algebra in the code .

Rounding coordinate inputs to two decimal places ensures precision in determining a point's exact position, particularly when comparing proximity to axes or the origin. It helps to avoid inaccuracies that could arise from floating-point precision errors, allowing correct evaluations for positions like origin, axes, or quadrants using conditional checks on the rounded values .

The method for calculating a student's final letter grade involves collecting scores for quizzes, assignments, and exams. Each form of assessment has a weighted factor: quizzes combined contribute 20%, assignments 30%, and exams 50% to the final score. The weighted average is computed and a bonus is applied using a calculated percentage of this average. The final score determines the letter grade based on predefined ranges: A for scores 90 and above, B for 80-89, C for 70-79, D for 60-69, and F below 60 .

Key concepts involved in rounding numerical inputs include precision handling and utilizing appropriate standard library functions like `round`. Rounding affects computational accuracy by mitigating floating-point errors, providing a stable representation of numbers for mathematical operations. For this lab, rounding to two decimal places ensures that coordinate positions are evaluated consistently, reducing errors associated with floating-point arithmetic in evaluations .

To solve a quadratic equation using a C program, follow these steps: first, prompt the user to enter the coefficients a, b, and c using `printf` and `scanf`. Ensure that a is not zero, which is crucial since a zero value would invalidate the equation. If a is zero, display an error message. Next, calculate the discriminant using the formula `D = b^2 - 4ac`. Determine the nature of the roots based on the value of the discriminant: if D > 0, there are two distinct real roots; if D = 0, there is one real root; if D < 0, the roots are imaginary .

The lab exercise enhanced understanding of C programming by applying concepts such as conditional statements in practical scenarios like solving quadratic equations and determining Cartesian positions. Debugging activities sharpened problem-solving skills by requiring meticulous checks for logical errors and incorrect syntax across simulations and grade calculations. These exercises provided practical experience in handling conditional operations, managing input/output functions, and constructing robust C programs .

Seeding the random number generator using a function like `srand()` ensures variety in simulated outcomes in games, preventing predictable sequences that can occur if not seeded. Without proper seeding, repeated executions of the game could generate identical results, undermining the randomness essential for game simulations and user engagement. Proper seeding ensures legitimate randomness and fair play conditions .

When debugging the C program simulating a dice-rolling game, challenges included fixing assignment errors and logical conditions. The primary issues were using '==' instead of '=' for assignments and ensuring correct logic for decision-making on the game outcome. Solutions involved correcting the assignment operator for proper dice roll calculations and ensuring that conditions accurately checked for win, loss, or continuation of the game .

Critical constraints include the assumption that the user provides valid coefficients, with a non-zero 'a', as zero makes the equation linear not quadratic. The program explicitly calculates only real roots, ignoring complex roots. These constraints ensure reliable execution by focusing on real-scenario validations, but limit the program’s scope to handle only real-number solutions, which keeps the computation straightforward .

Conditional statements facilitate decision-making in algorithms by providing pathways based on evaluation results, making them indispensable for mathematical problem-solving in C programming, such as checking discriminants or evaluating Cartesian coordinates. Benefits include clear logical flow and simplified complexity handling. However, challenges may arise with complex conditions leading to unwieldy code and increased difficulty in debugging errors or logical mismatches, requiring careful structuring and comprehensive testing .

You might also like