Write a program to find the greatest of four numbers [closed] - c

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

Related

Why is my program to check for prime numbers showing numbers with last digit 5 as prime numbers? [closed]

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 2 months ago.
Improve this question
I wrote a simple and short program to check for prime numbers in C. It is showing normal results for all numbers except for those numbers which have last digit as 5 by printing them as prime numbers, even those numbers which are clearly not prime, like 15, 25, 45 etc.
My question is that why is it doing so and how can I fix it?
Here is my code -:
#include<stdio.h>
int main()
{
int num, count=0;
printf("\nEnter a number : ");
scanf("%d",&num);
for(int i=2; i<=num/2; i++)
{
if(num%i==0)
count=1;
break;
}
if(count==1)
printf("\nNot a prime number.");
else
printf("\nPrime Number.");
}
Any help would be great.
Thank You.
Your program executes the for cycle only once, since the removal of the curly brackets causes only the line count=1 to be executed when the if condition becomes true. Thus, the break command is ALWAYS executed. You could fix it by writing the line as:
if (num%i==0) {
count=1;
break;
}
Hope this helps!
#include<stdio.h>
int main()
{
int num, count=0;
printf("\nEnter a number : ");
scanf("%d",&num);
for(int i=2; i<=num/2; i++)
{
if(num%i==0){ // you have to add {} for multi-line code
count=1;
break;
}
}
if(count==1)
printf("\nNot a prime number.");
else
printf("\nPrime Number.");
}

Subtracting in C adds and turns negative

I'm trying to make a simple calculator that asks how many numbers are needed (right now just for adding and subtracting) then collects those numbers for the user and does the corresponding math depending on what the user wants.
Here's my code:
if (option == 1) {
printf("ADDITION\n");
printf("How many numbers do you need? ");
scanf("%d", &n);
printf("Enter %d numbers:\n", n);
for(i=1; i<=n; i++){
scanf("%lf", &addNum);
sol = sol + addNum;
}
printf("Solution: %.2lf\n", sol);
}
if (option == 2) {
printf("SUBTRACTION\n");
printf("How many numbers do you need? ");
scanf("%d", &n);
printf("Enter %d numbers:\n", n);
for(i=1; i<=n; i++){
scanf("%lf", &subNum);
sol = sol - subNum;
}
printf("Solution: %.2lf\n", sol);
}
The addition works perfectly fine. The subtraction does not. I figured if adding is working, then replacing the + with an - would suffice but I guess not. The problem I'm having is, for example:
ADDITION
How many numbers do you need? 2
Enter 2 numbers:
10
5
Solution: 15.00
SUBTRACTION
How many numbers do you need? 2
Enter 2 numbers:
10
5
Solution: -15.00
Can someone help me understand how rather than subtracting, it's adding the numbers and going negative?
For subtraction (option 2) you have not assigned sol to be the value you wish to subtract from. In your code, you start subtracting from 0 straight away and therefore are left with a negative value.
A fix could be to say that for first number you want to subtract from, set it to be the value of sol.
for(i=1; i<=n; i++)
{
scanf("%lf", &subNum);
if(i == 1)
{
sol = subNum;
}
else
{
sol = sol - subNum;
}
}

Counting the amount of digits in a while loop does not work [closed]

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 2 years ago.
Improve this question
I use the following code to count the amount of digits in a while loop, so "0" should be 1, "10" should be 2 etc. - however the code does not seem to work. Can you please help me?
#include<stdio.h>
#include<stdlib.h>
int main()
{
int x;
int division;
int counter=0;
printf("Enter a number : ");
scanf("%d",&x);
do
{
division=x/10;
counter++;
}
while(division!=0);
printf("This number contains : %d digits",counter);
return 0;
}
please change division=x/10; to x /= 10 and corresponding while condition. x is not changed your code, thus you get stucked in you while loop forever
This line:
division = x / 10;
Will be performed forever since the condition given in the while logic never becomes false.
If you do:
do {
x = x / 10;
counter++;
} while (x != 0);
It'll work.
Enhanced version of your code:
#include <stdio.h>
int main() {
int x;
int counter = 0;
printf("Enter a number : ");
// looping until a correct format is provided
while (scanf("%d", &x) == 0) {
printf("Incorrect values, enter again: ");
fseek(stdin, 0, SEEK_END);
}
do {
x = x / 10;
counter++;
} while (x != 0);
printf("This number contains : %d digits.", counter);
return 0;
}
The intention behind the "enhanced version" is to verify if the input is correctly given as formatted in coding (i.e. accepting an integer and nothing else) which isn't in your program.
Also, you don't need to include stdlib.h for your own code. That works without it too.
You'll then get the following sample output:
Enter a number : asdlfjal;sdk
Incorrect values, enter again: asdf sdf
Incorrect values, enter again: 33334
This number contains : 5 digits.
You are not changing the division value. This should work
#include<stdio.h>
#include<stdlib.h>
int main()
{
int x;
int division;
int counter=0;
printf("Enter a number : ");
scanf("%d",&x);
do
{
x=x/10;
counter++;
}
while(x!=0);
printf("This number contains : %d digits",counter);
return 0;
}

How to enter if statement inside a for loop? [closed]

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.

Expected ; before ) token error in C [closed]

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

Resources