facebook like button

26 March, 2011

program 10: Largest of three integers

The need:
     To find out largest of three numbers given by user. To learn the conditional assignment (the ? : operator) and to learn how to scan more than one variable in a single scan statement. 
The code:
-------------------------------------------

#include<stdio.h>
int main()
{
int i,j,k,l;
printf("Enter three integers\n");
scanf("%d %d %d",&i,&j,&k);
l=(i>j)?i:j;
l=(k>l)?k:l;
printf("The largest integer of the above given is %d\n\n",l);
return 0;
}
-------------------------------------------

   First of all copy the code and run the program. When this program asks for three integers, enter three integers one by one and the program will print the largest number for you. At this point you already know that the first line inside main() is the declaration of 4 integer variables. The second line will print a message on console. The third will scan three integers form keyboard(also called STDIN which stands for standard input) and assign their values to i,j,k respectively.
   There is a fourth variable 'l' that will be holding the value of largest integer at end of the program. The fourth line of main() is a 'conditional assignment' statement. It may be a new term for you but as the name says its an assignment based on some condition. Look at the format of this statement. Just after the '=' sign a parenthesis starts and there is also a closing parenthesis in the same line. This pair of parenthesis encloses our condition for assignment. After closing parenthesis there is '?' and then a value(variable i) then a ':' then a value(variable j). One of these value is to be assigned to 'l'.
   If the condition enclosed in the parenthesis is true then the former value is assigned to 'l' else the latter value is assigned. This follows that if i>j is true then value of i is assigned to 'l' else value of 'j' is assigned to 'l'.  This means after line 4 of main() 'l' will be having larger of 'i' and 'j'. By the same logic after line 5 of main() 'l' will be having larger of 'l' and 'k'. This follows that by the end of line 5 'l' will be having the largest value of i,j and k.

Note:
  1. Instead of giving the value directly we can write any expression that lead to a value or a function that returns a value.
  2. This will be true in all other assignments. In most of the cases variables can be replaced by expressions and functions.
  3. We can not replace a variable that is on the left side of '=' with an expression or a function.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply