Create a free account on Computer Sir Ki Class and unlock access to valuable learning resources.
Exam Paper Downloads: After registering and logging in, you can download exam question papers in PDF format to practice and prepare for your exams.
Student Support: Get assistance with your doubts, queries, and questions related to your studies. Our support is here to help you understand topics and resolve your learning difficulties.
Register today and make your exam preparation easier and more effective!
Problem Statement - Function to return largest of three numbers along with all same check
Write a function to return the largest of three integer numbers passed to it as value. Also pass a variable as reference which will be set to 1 if all the numbers passed are same. Show implementation of this function in the main routine with appropriate messages.
Alternate post is a link to another way of doing the program which results in same output but with a different programming approach.
:
Run Output
Enter three numbers :12 13 14
14 is largest
-OR-
Enter three numbers :15 15 15
All numbers are same
int largest(int a,int b,int c,int &same)
This function definition gets three integers as pass by value parameter and a parameter &same passed as reference. { if(a>b && a>c) return a; else if(b>a && b>c) return b; else if(c>a && c>b) return c;
This three conditions returns appropriate largest number. else { same=1; return a;}
This condition sets the variable same (passed as reference) to 1. This also returns the number in a which will anyway be same as b and/or c if the all same condition is met. }
int a,b,c; cout<<“Enter three numbers :”; cin>>a>>b>>c;
Suitable data input is collected from the user. int same=0; //This variable is set as default to 0, which can be made 1 by the function.
int big=largest(a,b,c,same);
This is function call. The largest value is returned in big variable. Also if all the numbers are same, the variable same which is passed by reference will be updated to 1.
if(same) cout<<“All numbers are same”<<endl; else cout<<big<<” is largest”<<endl;
Suitable messages based on condition of same is printed here.
Notes
The way this program has been written is that it allows the optional use of variable same. If you just want to return the number even if all numbers are same you can still do so by not checking for condition of variable same.
Common Errors
int big=largest(a,b,c,&same); This is incorrect. Do as the program has suggested.