Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying calculate the average of 5 numbers, all of them being lower than 10.
Any help would be much appreciated since I'm still very much in the early stages of learning.
int num1, num2;
int sum, i;
float average;
printf ("Enter five numbers to calculate the average:");
for (i = 0; i < 5; i++){
scanf ("%d", num1);
if (num1 > 10){
printf ("You can't enter this number\n");
printf ("Enter five numbers to calculate the average:");
scanf ("%d", num1);
}
else{
num1=num2;
}
sum += num2;
}
average = sum / 5;
printf ("Average is: %f", average);
Your first job is to write scanf("%d", &num1);, note the pointer. Eventually you should check the return value of scanf too - it should be 1 if a number was read.
One way (not to everyone's taste) would be to rewrite the if body as
if (num1 > 10){
printf ("You can't enter this number\n");
printf ("Enter five numbers to calculate the average:");
--i;
} ...
which reverses out the incrementation of i.
Another way (which I would prefer) would be to only increase i in the else branch, and drop the i++ from the third for loop expression.
Your assignment num1 = num2; is buggy too, nothing that you can't solve with a debugger, and you'll also realise you'll need average = sum / 5.0f; to avoid a truncation.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last month.
Improve this question
I am new to Programming and currently learning C, so I don't know much about this concept but I was learning Conditional Instructions and at that time, my instructor [I am learning online from YouTube] explained me about logical operators.
He explained that logical operators are used with if...else to decrease the indentation and increase the readability.
After some time, I was solving a problem to find the greatest of four numbers and here, he contradicted the theory. He described nested if to solve this question instead of using logical operators.
Now; I am confused, what approach should I go with and why?
Also; when should I use arithmetic instructions and when should I use nested if...else?
Code written by me:
#include <stdio.h>
int main()
{
int number1, number2, number3, number4;
printf("\nEnter the vlaue of number1: ");
scanf("%d", &number1);
printf("\nEnter the value of number2: ");
scanf("%d", &number2);
printf("\nEnter the value of number3: ");
scanf("%d", &number3);
printf("\nEnter the value of number4: ");
scanf("%d", &number4);
if(number1 > number2 && number1 > number3 && number1 > number4)
{
printf("\n%d is the greatest of four numbers.\n", number1);
}
else if(number2 > number3 && number2 > number4)
{
printf("\n%d is the greatest of four numbers.\n", number2);
}
else if(number3 > number4)
{
printf("\n%d is the greatest of four numbers.\n", number3);
}
else
{
printf("\n%d is the greatest of four numbers.\n", number4);
}
return 0;
}
Code written by my instructor:
#include <stdio.h>
int main()
{
int number1, number2, number3, number4;
printf("\nEnter the vlaue of number1: ");
scanf("%d", &number1);
printf("\nEnter the value of number2: ");
scanf("%d", &number2);
printf("\nEnter the value of number3: ");
scanf("%d", &number3);
printf("\nEnter the value of number4: ");
scanf("%d", &number4);
if(number1 > number2)
{
if(number1 >number3)
{
if(number1 > number4)
{
printf("\n%d is the greatest of four numbers.\n", number1);
}
}
}
else if(number2 > number3)
{
if(number2 > number4)
{
printf("\n%d is the greatest of four numbers.\n", number2);
}
}
else if(number3 > number4)
{
printf("\n%d is the greatest of four numbers.\n", number3);
}
else
{
printf("\n%d is the greatest of four numbers.\n", number4);
}
return 0;
}
The instructor’s code is wrong. If you enter 2, 1, 3, and 4 for the four numbers, it prints nothing, when it should print that 4 is the greatest.
The logical operators, && and ||, are generally used to combine other conditions. Decreasing indentation and increasing readability is a separate goal. Do not fixate on either of these; simply learn to use the operators to perform desired computations and practice making your programs readable.
Increasing indentation doesn't mean decrease readability. If you have a very long if-condition, it will decrease indentation, but also decrease readability. You should use the only way that allows you to keep your code clean and as simple as possible. Efficiency of code is also necessary since you are talking about C. Logical operators helps to combine two or more if-conditions in one and sometimes it really improve readability, sometimes - not. Sometimes, nested-ifs are better choice, you should think about your situation and choose the best way.
As stated by other commenters, your instructor is wrong and code has logical errors.
If number1 = 5, number2 = 3, number3 = 6, number4 = 2
It would print 5 is the greatest of four numbers, whilst 6 is.
So this is not correctly coded.
If conditional statements is the topic, your teacher has the more correct answer, however elaborate this may look.
Because on a practical note, you could code:
/* be sure to #include <stdlib.h> */
printf("\n%d is the greatest of four numbers.\n",
max(max(max(number1,number2),number3),number4);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
The following is an attempt to print a number of fibonacci sequence numbers, determined by the user. Uses a user-define function, fibonacci(int a). It is printing the wrong output, not a recursive sequence, but a continually doubling sequence. How can the code be fixed so that it works correctly?
#include <stdio.h>
int fibonacci(int a);
void main()
{
int number, range;
printf("Enter the number of Fibonacci numbers: ");
scanf("%d", &range);
number = fibonacci(range);
printf("%d\n", number);
}
int fibonacci(int a)
{
int num1 = 1;
int num2 = 1;
int position;
if (a == 1)
{
printf("%d", num1);
}
if (a == 2)
{
printf("%d\n", num1);
printf("%d", num2);
}
if (a > 2)
{
for(position = 1; a >= position; position++)
{
printf("%d\n", num1);
num1 = num2;
num2 = num1 + num2;
}
}
}
This prints the following output for all numbers:
1
1
2
4
8
16
...
The desired output is the fibonnaci sequence (each number is the sum of the two previous ones):
1
1
2
3
5
8
13
...
The problem is that within the loop you first overwrite num1 by assigning num2 to it:
num1 = num2;
Then you make num2 be the sum of itself and num1, but you have just made num1 equal to num2, so this line is effectively just multiplying num2 by two (i.e., adding it to itself):
num2 = num1 + num2;
You need to preserve the old value and use that for the sum, e.g., by adding a third, temporary, variable.
(Apart from this, you also have various other problems, but all of them are such that they should produce compiler warnings. If they don't, enable all warnings and/or get a better compiler. Once you get warnings, don't ignore them but research the cause for each of them and fix all warnings before you even run your code.)
I'm writing a c program for my intro class and I'm stuck on the if/else statements. we have to output the highest,lowest grade entered as well as the avg for those. Marks entered must be between 0-100. this is my code so far, i can't seem to figure it out, thanks for any advice! :
#include <stdio.h>
int main (void)
{
int numberofMarks;
int i;
int x;
int y;
int numofPasses=1;
int numofFails=1;
float sumpassedMarks =0;
float sumfailedMarks=0;
float markEntered=0;
float highestMark=0;
float lowestMark=0;
float totalMark=0;
float avgofMarks=0;
float avgpassedMarks=0;
float avgfailedMarks=0;
printf (" ---=== IPC mark Analyser ===---\n");
printf ("Please enter the number of marks(between 3 and 40): ");
scanf ("%d", &numberofMarks);
//asks user for number of marks, only takes 3-40, otherwise outputs error msg
for (i=1 ; (numberofMarks < 3)||(numberofMarks > 40) ; i++) {
printf ("Invalid number, enter a number between 3 and 40 inclusive: ");
scanf ("%d", &numberofMarks);
}
//for loop recieves the mark
for (x=1 ;(x <= numberofMarks) ; x++) {
printf ("%d> ", x);
scanf ("%f", &markEntered);
//contd loop..loop makes sure mark entered is between 1-100
for (y=1; (markEntered <0)||(markEntered>100); y++)
{
printf ("Error, Enter values between 0 and 100 incluisve.\n");
printf ("%d> ", x);
scanf ("%f", &markEntered);
if (markEntered >= 50) {
numofPasses=numofPasses+1;
}
if else (markEntered <= 49) {
numofFails = numofFails+1;
}
if else (markEntered > highestMark) {
highestMark = markEntered;
}
else (markEntered < lowestMark) {
lowestMark = markEntered;
}
}
//adds the mark entered to all the marks entered for a overall sum
totalMark = totalMark + markEntered;
}
avgofMarks = (float)totalMark / numberofMarks;
avgpassedMarks = (float)sumpassedMarks / numberofMarks;
avgfailedMarks = (float)sumfailedMarks / numberofMarks;
printf ("Total of %d students passed with an average of %.1f.\n", numofPasses,avgpassedMarks);
printf ("Total of %d students failed with an average of %.1f.\n", numofFails, avgfailedMarks);
printf ("Highest mark in the group: %.1f\n", highestMark);
printf ("lowest mark in the group: %.1f\n", lowestMark);
printf ("The average of all marks in this group is %.1f.\n", avgofMarks);
printf ("Program Ended.\n");
return 0;
}
The work asks,
In the loop in which marks are being entered, after each entry examine the value of the mark entered:
If it is a pass, add one to the number of passes and add the value of the mark to the sum of passed marks.
If it is a fail, add one to the number of fails and add the value of the mark to the sum of failed marks.
If the value is higher than the highest mark, set highest mark to the value read.
If the value is lower than the lowest mark, set the lowest mark to
the value read. After all the marks are entered and examined, divide
the sums by the corresponding number of marks to get the average and
print the results.
This is my output vs the sample output.
Your code is a mess; let's try to get some things straight here:
If you're not gonna use i in the body of a for loop, no reason to initialize and increment it. Better to use a while.
When you post a question, clear all not-strictly-necessary code from the answer, so that it's easier to help
Instead of making 15 variables, consider using an array or, if you're not gonna use the values later in the program, print the result directly.
Ex.
int a = 10, b = 15; If you wanna print the sum, no reason to save it in a new int sum, just printf("%d", a + b);
Do not request the number of votes outside of a loop, and then loop to verify the value (your first for loop). Consider a DO..WHILE loop instead.
Ex.
do{
scanf("%d", &n);
} while(n <= 0);
//Scan integer and save into n, until you get a positive value
Avoid nesting for loops for no reason, use more if() .. else if() .. if necessary.
It's not the best of practise, but you can also use the continue and break keywords to continue or stop the loops respectively.
Do not use "else" randomly. If you have more conditions to check, leave the if without else. You wanna use else after an if condition if (when the first condition comes back true) you don't want to check the next condition (they will be skipped !)
I am writing a C program to repeat a series of question specified times. I ask user to enter the number of attempts they want and then I run the following while loop based on their number, but the problem is the loop keeps repeating. It does not stop at the specified number of attempt. Here is the code:
#include <stdio.h>
int main(void){
int num1,num2,high,low,average,subtotal,total_aver;
printf("Enter number of tries you want:");
scanf("%d", &num1);
while (num1 < num1 + 1) {
printf("Try number: ");
scanf("%d", &num2);
printf("Enter high ");
scanf("%d", &high);
printf("Enter low ");
scanf("%d", &low);
subtotal = high + low;
total_aver = subtotal / 2;
printf("Average temperature is: %d", total_aver);
}
}
If user enters 3 for number of tries then the program should ask those question in inside the loop three times, but it keeps repeating without ending.
while (num1 < num1 + 1) // condition is never false
Well this is infinite loop . It will continue and continue.
Write loop like this if you want to iterate number of times -
int i=0;
while(i<num1){
// your code
i++;
}
Or without any extra variable -
while(num1>0){
// your code
num1--;
}
This happens because the condition in the while is wrong.
Infact, assigning to num1 to any value, it will exit when num1 will be equal to num1+1. Is this impossibile, isn't it? You have to use another variable to take count of times you repeat the loop.
Fix this way:
int count=0;
while(count<num+1){
//your code
count=count+1;
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm trying to figure out a homework assignment in C. I'm supposed to have the user enter integers until they enter a negative number. At that point the program needs to stop inputting and proceed to output the sum, number of tries before a negative number is entered, and the mean.
I can't seem to find any errors in my code (although I'm sure there is), but when I try to compile I get multiple errors on my output printf statements that say both expected ';' before ')' token and expected statement before ')' token. I must be blind. Please enlighten me.
Here's all my code thus far:
int main(void)
{
int i=0,sum=0,tries=0;
int mean=sum/tries;
do
{
printf("Please enter a number %i. When finished, enter "
"a negative number. \n",i);
scanf("%i",&i);
sum+=i;
tries++;
}
while(i>=-1);
if((sum<=0) && (i<=-1))
{
printf("No valid numbers were entered. Try again. ");
}
else
{
printf("Sum is %i\n"),sum);
printf("%i tries \n"),tries);
printf("Mean is %i \n"),mean);
}
return 0;
}
You have too many parentheses
printf("Sum is %i\n"),sum);
printf("%i tries \n"),tries);
printf("Mean is %i \n"),mean);
Should be
printf("Sum is %i\n",sum);
printf("%i tries \n",tries);
printf("Mean is %i \n",mean);
Full code:
int main(void)
{
int i=0,sum=0,tries=0;
int mean=sum/tries;
do
{
printf("Please enter a number %i. When finished, enter "
"a negative number. \n",i);
scanf("%i",&i);
sum+=i;
tries++;
}
while(i>=-1);
if((sum<=0) && (i<=-1))
{
printf("No valid numbers were entered. Try again. ");
}
else
{
printf("Sum is %i\n",sum);
printf("%i tries \n",tries);
printf("Mean is %i \n",mean);
}
return 0;
}
You forgot the include line (#include <stdio.h>).
And miss type close parenthesis in the print lines, should be printf("Sum is %i\n", sum); and not printf("Sum is %i\n"),sum); should also give some error similar to the posted.
This would be the fixed code:
#include <stdio.h>
int main(void) {
int i = 0, sum = 0, tries = 0;
int mean = sum / tries;
do {
printf("Please enter a number %i. When finished, enter "
"a negative number. \n",
i);
scanf("%i", &i);
sum += i;
tries++;
} while (i >= -1);
if ((sum <= 0) && (i <= -1)) {
printf("No valid numbers were entered. Try again. ");
} else {
printf("Sum is %i\n", sum);
printf("%i tries \n", tries);
printf("Mean is %i \n", mean);
}
return 0;
}