Author Topic: C Program to find maximum between three number using nested if  (Read 1506 times)

0 Members and 1 Guest are viewing this topic.

Offline khatusTopic starter

  • Regular Contributor
  • *
  • Posts: 146
  • Country: gl
C Program to find maximum between three number using nested if
« on: January 30, 2020, 06:02:28 pm »
Step by step descriptive logic to find maximum between three numbers.

1 Input three numbers from user. Store it in some variable say num1, num2 and num3.

2. Compare first two numbers i.e. num1 > num2. If the statement is true then num2 is surely not max value. Perform one more comparison between num1 with num3 i.e. if(num1 > num3), then num1 is max otherwise num3.

3. If the statement num1>num2 is false. Which indicates that num1 is not max. Hence, this time compare num2 with num3. If the statement num2>num3 is true then num2 is max otherwise num3.

Code: [Select]
/**
 * C program to find maximum between three numbers using nested if
 */

#include <stdio.h>

int main()
{
    int num1, num2, num3, max;

    /* Input three numbers from user */
    printf("Enter three numbers: ");
    scanf("%d%d%d", &num1, &num2, &num3);
   

    if(num1 > num2)
    {
        if(num1 > num3)
        {
            /* If num1 > num2 and num1 > num3 */
            max = num1;
        }
        else
        {
            /* If num1 > num2 but num1 > num3 is not true */
            max = num3;
        }
    }
    else
    {
        if(num2 > num3)
        {
            /* If num1 is not > num2 and num2 > num3 */
            max = num2;
        }
        else
        {
            /* If num1 is not > num2 and num2 > num3 */
            max = num3;
        }
    }
   
    /* Print maximum value */
    printf("Maximum among all three numbers = %d", max);

    return 0;
}

Hello guys in this program if num1 = 3 num2 =2 and num3 = 1.Then the program first checks 3>2 if that satisfies then it checks 3>1 if this is not satisfies then max = num3;that means num3 =1 ids the greatest number.which is not possible.I am confused which line will be executed first


 

Offline jesuscf

  • Frequent Contributor
  • **
  • Posts: 499
  • Country: ca
Re: C Program to find maximum between three number using nested if
« Reply #1 on: January 30, 2020, 06:30:47 pm »
max=num1;
if(num2>max) max=num2;
if(num3>max) max=num3;
Homer: Kids, there's three ways to do things; the right way, the wrong way and the Max Power way!
Bart: Isn't that the wrong way?
Homer: Yeah, but faster!
 

Online oPossum

  • Super Contributor
  • ***
  • Posts: 1417
  • Country: us
  • Very dangerous - may attack at any time
Re: C Program to find maximum between three number using nested if
« Reply #2 on: January 30, 2020, 07:06:26 pm »
Code: [Select]
printf("Maximum among all three numbers = %d", (num1 < num2) ? ((num2 < num3) ? num3 : num2) : ((num1 < num3) ? num3 : num1));
 

Offline aix

  • Regular Contributor
  • *
  • Posts: 147
  • Country: gb
Re: C Program to find maximum between three number using nested if
« Reply #3 on: January 30, 2020, 07:08:50 pm »
The mistake in your reasoning is here:

Quote
then it checks 3>1 if this is not satisfies then max = num3

3 is greater than 1 and so the max is num1, not num3.

Personally, I'd write it the way jesuscf did.  Much easier to grasp at a glance and to reason about.

Lastly, your problem statement says "numbers".  Your code interprets that to mean "integers".  If one has to write similar code for floating-point numbers, there are additional subtleties to consider (such as NaNs and how they compare).
« Last Edit: January 30, 2020, 07:12:49 pm by aix »
 

Offline ve7xen

  • Super Contributor
  • ***
  • Posts: 1193
  • Country: ca
    • VE7XEN Blog
Re: C Program to find maximum between three number using nested if
« Reply #4 on: January 30, 2020, 09:35:56 pm »
Personally I would prefer to compose this from the standard two-input max function `int max(int a, int b)`.

So:

Code: [Select]
int max(int a, int b) {
  return (a > b) ? a : b;
}

int main(void) {
  ...
  int max3 = max(num1, max(num2, num3));
  ...
}

Or use C++ and the std::min and std::max library functions.
73 de VE7XEN
He/Him
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 4040
  • Country: nz
Re: C Program to find maximum between three number using nested if
« Reply #5 on: January 30, 2020, 09:50:22 pm »
I think there is confusion here between the names of the variables num1, num2, num3 and the values they (currently) hold.

Change "num1" everywhere in the program to "toyota".
Change "num2" everywhere in the program to "subaru".
Change "num3" everywhere in the program to "honda".

And it will work identically.

Beginners should be taught to program in machine code (not even assembly language) until they understand the concepts, not in magical-looking things like C or Python.

And I don't mean x86.
 
The following users thanked this post: bsudbrink

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 4040
  • Country: nz
Re: C Program to find maximum between three number using nested if
« Reply #6 on: January 30, 2020, 09:54:11 pm »
Personally I would prefer to compose this from the standard two-input max function `int max(int a, int b)`.

So:

Code: [Select]
int max(int a, int b) {
  return (a > b) ? a : b;
}

int main(void) {
  ...
  int max3 = max(num1, max(num2, num3));
  ...
}

Or use C++ and the std::min and std::max library functions.

This is going in 180 degrees the wrong direction for a beginner. They need concrete not abstract. They need it to be completely obvious what you can say (and what it means) and what you *can't* say.

You give a toddler Lego to build things from, not a NC milling machine.
 

Offline helius

  • Super Contributor
  • ***
  • Posts: 3643
  • Country: us
Re: C Program to find maximum between three number using nested if
« Reply #7 on: January 30, 2020, 10:21:59 pm »
Function composition is a good tool for people who understand algebra. Yes, it's an "abstraction", but it's a simple and consistent one. Building functions out of repeated calls to simpler functions is the bedrock of maintainable code.

There's a saying (attributed to Tony Hoare, I think) that you can either make a program so simple that it obviously has no defects, or make it so complicated that it has no obvious defects. Beginning with machine language seems like a recipe for the latter result.
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19519
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: C Program to find maximum between three number using nested if
« Reply #8 on: January 30, 2020, 10:51:19 pm »
There's a saying (attributed to Tony Hoare, I think) that you can either make a program so simple that it obviously has no defects, or make it so complicated that it has no obvious defects. Beginning with machine language seems like a recipe for the latter result.

Correct (and I met him once and thanked him for his semonal Algol-60 compiler :) )

Machine language can be elegant or obfuscated, just like C.
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 
The following users thanked this post: bsudbrink

Offline Brumby

  • Supporter
  • ****
  • Posts: 12298
  • Country: au
Re: C Program to find maximum between three number using nested if
« Reply #9 on: January 30, 2020, 10:51:48 pm »
This is going in 180 degrees the wrong direction for a beginner. They need concrete not abstract. They need it to be completely obvious what you can say (and what it means) and what you *can't* say.

You give a toddler Lego to build things from, not a NC milling machine.
I have to agree.  For someone who is challenged by this extremely straightforward exercise, keeping things simple and obvious is necessary for them to learn how to program with logic and understanding.   Being presented with the library of functions or other tips and tricks before they can get their "If" statements sorted is pointless.

Having said that, nested structures can be extremely powerful.  However, I would suggest that incorrectly written nested structures would be the number one programming problem coders make, especially early on in their development.

Nevertheless, keeping things simple will reduce coding errors and will allow for logic to be obvious when the code is visited further down the track - whether by the original author or someone else.  On that point, comments are invaluable.  Developing the discipline to add clear and descriptive comments will produce MUCH more maintainable code.  DO IT.


This is how I would suggest a beginner do it:
max=num1;
if(num2>max) max=num2;
if(num3>max) max=num3;
... and I wouldn't have a problem with a 30 year veteran programmer doing it this way either.
 

Offline grumpydoc

  • Super Contributor
  • ***
  • Posts: 2905
  • Country: gb
Re: C Program to find maximum between three number using nested if
« Reply #10 on: January 30, 2020, 10:54:45 pm »
max=num1;
if(num2>max) max=num2;
if(num3>max) max=num3;

Arguably the best solution because it is clear and readily understandable and also lends itself to the next (and more realistic) problem - find the maximum out of an arbitrary number of items - the most obvious solution being to set max to the first element of an array then run along the array elements updating max if the current element is larger.

But, yeah, like most C programmers I'd define a MAX macro (or use a handy one if I pulled it in with library headers), or inline function and say something like
Code: [Select]
m = max(a, max(b,c))

Code: [Select]
int max(int a, int b) {
  return (a > b) ? a : b;
}

If you want, but:
Code: [Select]
int max(int x, int y)
{
    return x ^ ((x ^ y) & -(x < y)); 
}
Is more fun.

Proof this works left as an exercise for the reader.
 

Offline helius

  • Super Contributor
  • ***
  • Posts: 3643
  • Country: us
Re: C Program to find maximum between three number using nested if
« Reply #11 on: January 30, 2020, 11:03:22 pm »
(and I met him once and thanked him for his semonal Algol-60 compiler :) )
I only discovered a few years ago that he also invented Quicksort. Going back to the paper (in a predecessor to ACM Letters, that didn't even exist at the time) it's amazing how opaque it looks with the terminology from that era. Can you imagine describing Quicksort without mentioning a stack or a procedure call? So much of the work of computer science is coming up with concepts (abstractions) that are both intuitive and rigorous.

Quote from: tggzzz
Machine language can be elegant or obfuscated, just like C.
I'll admit that I believe this too, but only if we mean something like the order code of a stack machine, where the source and destination are implicit. Instructions on register machines are full of irrelevant detail that imposes a heavy cognitive load, and bizarro 8086 is even harder.
 

Offline IDEngineer

  • Super Contributor
  • ***
  • Posts: 1926
  • Country: us
Re: C Program to find maximum between three number using nested if
« Reply #12 on: January 30, 2020, 11:34:29 pm »
This is definitely the most readable:

max=num1;
if(num2>max) max=num2;
if(num3>max) max=num3;

...but I must admit I got all tingly when I saw oPossum's offering:

Quote
printf("Maximum among all three numbers = %d", (num1 < num2) ? ((num2 < num3) ? num3 : num2) : ((num1 < num3) ? num3 : num1));

It might not be as immediately obvious, but it's darned elegant. My OCD loves it. Think about its extensibility....
 

Offline ve7xen

  • Super Contributor
  • ***
  • Posts: 1193
  • Country: ca
    • VE7XEN Blog
Re: C Program to find maximum between three number using nested if
« Reply #13 on: January 31, 2020, 12:21:55 am »
Personally I would prefer to compose this from the standard two-input max function `int max(int a, int b)`.

So:

Code: [Select]
int max(int a, int b) {
  return (a > b) ? a : b;
}

int main(void) {
  ...
  int max3 = max(num1, max(num2, num3));
  ...
}

Or use C++ and the std::min and std::max library functions.

This is going in 180 degrees the wrong direction for a beginner. They need concrete not abstract. They need it to be completely obvious what you can say (and what it means) and what you *can't* say.

You give a toddler Lego to build things from, not a NC milling machine.

I don't think it is ever too early to demonstrate idiomatic solutions, if they are simple to understand. It wouldn't be the first solution I'd offer to someone with this question, but the trivial examples were covered and I think it is worth showing other, more 'correct' ways of doing things. It is unfortunate that C doesn't define a max() in the library, but even handwaving away the function definition, understanding how to compose functions is simple, idiomatic, and essential to using the language. When I was going through a computer science education, I was constantly frustrated with how many times I was told 'you know what we said last week? that no longer applies, now we're going to do it this better way', and likewise it was always the hints of sweeter abstractions to come that kept me interested in the early classes.

Perhaps this is why I'm not a teacher.

Quote
Is more fun.
Cute  :-DD . Interestingly many compilers seem to generate equivalent assembly for these two options. I never would've thought the compiler would consider to simplify several bitwise operations into a cmp.
73 de VE7XEN
He/Him
 

Offline unitedatoms

  • Frequent Contributor
  • **
  • !
  • Posts: 324
  • Country: us
Re: C Program to find maximum between three number using nested if
« Reply #14 on: January 31, 2020, 01:20:14 am »
Code: [Select]
x=(a>b)?((a>c)?a:c):((b>c)?b:c);
« Last Edit: January 31, 2020, 01:21:57 am by unitedatoms »
Interested in all design related projects no matter how simple, or complicated, slow going or fast, failures or successes
 

Offline ve7xen

  • Super Contributor
  • ***
  • Posts: 1193
  • Country: ca
    • VE7XEN Blog
Re: C Program to find maximum between three number using nested if
« Reply #15 on: January 31, 2020, 02:08:20 am »
Of all the obfuscated examples proposed

Code: [Select]
int max = num1;
if (num2 > max) max = num2;
if (num3 > max) max = num3;

And

Code: [Select]
// Or the normal comparison based binary max(int, int)
max = std::max(num1, std::max(num2, num3));

generate identical and the shortest assembly in pretty much every optimizing compiler. clang's trunk is the cleverest and turns all the proposed examples into effectively identical assembly. There appears to be zero value, and in some cases negative value, in the obfuscation / optimization / fun  :-DD.

https://gcc.godbolt.org/z/qtSChD
« Last Edit: January 31, 2020, 02:11:21 am by ve7xen »
73 de VE7XEN
He/Him
 

Offline Brumby

  • Supporter
  • ****
  • Posts: 12298
  • Country: au
Re: C Program to find maximum between three number using nested if
« Reply #16 on: January 31, 2020, 02:17:24 am »
I'm all for elegance, optimisation and efficiency ... but let's help the OP stand on their own before we throw them into the decathalon.


To the OP... If a lot of this confuses you at the moment - don't worry.  Geeks often get caught up in their own world - software or hardware!
« Last Edit: January 31, 2020, 02:18:55 am by Brumby »
 

Offline gbaddeley

  • Regular Contributor
  • *
  • Posts: 205
  • Country: au
Re: C Program to find maximum between three number using nested if
« Reply #17 on: January 31, 2020, 02:31:42 am »
max=num1;
if(num2>max) max=num2;
if(num3>max) max=num3;

General solution for a zero based array a of n integers:

int i,m;
.....
m=MIN_INT;
for( i=0 ; i<n ; i++ ) if( a[ i ]>m ) m=a[ i ];
« Last Edit: January 31, 2020, 02:36:30 am by gbaddeley »
Glenn
 

Offline admiralk

  • Regular Contributor
  • *
  • Posts: 178
  • Country: us
Re: C Program to find maximum between three number using nested if
« Reply #18 on: January 31, 2020, 03:07:31 am »
This sounds like a school assignment and if nested if statements are a requirement almost every suggestion has been incorrect. One of the things school problems are supposed to teach is how to solve the problem. in other words understand the requirements. In this case, I think khatus is over thinking the problem. The answer is clearly stated twice in the question.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf