June 25th, 2013, 10:06 AM

Using 'if' statements
I am trying to write a program that finds the largest and smallest of four integers entered by the user. For example:
Code:
Enter 4 integers: 4 17 9 32
Largest integer: 32
Smallest integer: 4
The challenge is to use the 'if' statement for maximum 4 times. Help me if you can. Thanks in advance :)
June 25th, 2013, 10:29 AM

Show us what you have done so far.
You've been on this ride before, so you already know the rules.
June 25th, 2013, 01:06 PM

Originally Posted by arman.khandaker
I am trying to write a program that finds the largest and smallest of four integers entered by the user. For example:
Code:
Enter 4 integers: 4 17 9 32
Largest integer: 32
Smallest integer: 4
The challenge is to use the 'if' statement for maximum 4 times. Help me if you can. Thanks in advance :)
More challenge if you use 'if' 0 time ;)
Code:
#include<stdio.h>
void main(){
int i=1,x,y,z[4];
for(printf("Enter 4 integers: "),scanf("%d %d %d %d", &z[0],&z[1],&z[2],&z[3]),
x=y=z[0];i<4;x=(z[i]>x)?z[i]:x,y=(z[i]<y)?z[i]:y,i++);
printf("Largest integer: %d\nSmallest integer: %d\n",x,y);
}
Comments on this post
June 25th, 2013, 01:32 PM

Really? Have you tried yet  this is a really simple algorithm.
Clue:
if a is bigger than my biggest result so far, then my biggest result so far is a.
That's one if and one value. You have 4 values and can use 4 ifs. It is so trivial that I have probably already said too much.
Note that you need to initialise the biggest so far to the smallest possible integer  and that is not zero BTW.
June 25th, 2013, 04:25 PM

the code could be like this! the trick is in green color, initialize it outside the loop :D
Code:
int main()
{
int a[4],i,max,min;
scanf("%d %d %d %d", &a[0],&a[1],&a[2],&a[3]);
max=min=a[0];
/* Edited out solution  please don't hand out complete answers */
printf("max:%d\nmin:%d\n", max, min);
return 0;
}
Last edited by Scorpions4ever; June 25th, 2013 at 04:38 PM.
June 27th, 2013, 06:49 PM

Okay thanks guys. I was actually looking for a way to do it without using arrays. :)
Comments on this post