C Program to find maximum between three number using nested if - Page 1
Forum section: electronics / beginners

author: khatus
author_rank: Regular Contributor
timestamp: January 30, 2020, 06:02:28 pm
content: 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:/*** 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

author: jesuscf
author_rank: Frequent Contributor
timestamp: January 30, 2020, 06:30:47 pm
content: max=num1;if(num2>max) max=num2;if(num3>max) max=num3;

author: oPossum
author_rank: Super Contributor
timestamp: January 30, 2020, 07:06:26 pm
content: Code:printf("Maximum among all three numbers = %d", (num1 < num2) ? ((num2 < num3) ? num3 : num2) : ((num1 < num3) ? num3 : num1));

author: aix
author_rank: Regular Contributor
timestamp: January 30, 2020, 07:08:50 pm
content: The mistake in your reasoning is here:Quote3 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).

author: ve7xen
author_rank: Super Contributor
timestamp: January 30, 2020, 09:35:56 pm
content: Personally I would prefer to compose this from the standard two-input max function `int max(int a, int b)`.So:Code: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.

author: brucehoult
author_rank: Super Contributor
timestamp: January 30, 2020, 09:50:22 pm
content: 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.

author: brucehoult
author_rank: Super Contributor
timestamp: January 30, 2020, 09:54:11 pm
content: Quote from: ve7xen on January 30, 2020, 09:35:56 pmThis 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.

author: helius
author_rank: Super Contributor
timestamp: January 30, 2020, 10:21:59 pm
content: 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.

author: tggzzz
author_rank: Super Contributor
timestamp: January 30, 2020, 10:51:19 pm
content: Quote from: helius on January 30, 2020, 10:21:59 pmCorrect (and I met him once and thanked him for his semonal Algol-60 compiler)Machine language can be elegant or obfuscated, just like C.

author: Brumby
author_rank: Unknown
timestamp: January 30, 2020, 10:51:48 pm
content: Quote from: brucehoult on January 30, 2020, 09:54:11 pmI 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:Quote from: jesuscf on January 30, 2020, 06:30:47 pm... and I wouldn't have a problem with a 30 year veteran programmer doing it this way either.

author: grumpydoc
author_rank: Super Contributor
timestamp: January 30, 2020, 10:54:45 pm
content: Quote from: jesuscf on January 30, 2020, 06:30:47 pmArguably 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 likeCode:m = max(a, max(b,c))Code:int max(int a, int b) {return (a > b) ? a : b;}If you want, but:Code: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.

author: helius
author_rank: Super Contributor
timestamp: January 30, 2020, 11:03:22 pm
content: Quote from: tggzzz on January 30, 2020, 10:51:19 pmI 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: tggzzzI'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.

author: IDEngineer
author_rank: Super Contributor
timestamp: January 30, 2020, 11:34:29 pm
content: This is definitely the most readable:Quote from: jesuscf on January 30, 2020, 06:30:47 pm...but I must admit I got all tingly when I saw oPossum's offering:QuoteIt might not be as immediately obvious, but it's darned elegant. My OCD loves it. Think about its extensibility....

author: ve7xen
author_rank: Super Contributor
timestamp: January 31, 2020, 12:21:55 am
content: Quote from: brucehoult on January 30, 2020, 09:54:11 pmI 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.QuoteCute. 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.

author: unitedatoms
author_rank: Frequent Contributor
timestamp: January 31, 2020, 01:20:14 am
content: Code:x=(a>b)?((a>c)?a:c):((b>c)?b:c);

author: ve7xen
author_rank: Super Contributor
timestamp: January 31, 2020, 02:08:20 am
content: Of all the obfuscated examples proposedCode:int max = num1;if (num2 > max) max = num2;if (num3 > max) max = num3;AndCode:// 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.https://gcc.godbolt.org/z/qtSChD

author: Brumby
author_rank: Unknown
timestamp: January 31, 2020, 02:17:24 am
content: 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!

author: gbaddeley
author_rank: Regular Contributor
timestamp: January 31, 2020, 02:31:42 am
content: Quote from: jesuscf on January 30, 2020, 06:30:47 pmGeneral 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 ];

author: admiralk
author_rank: Regular Contributor
timestamp: January 31, 2020, 03:07:31 am
content: 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.