functions

Heya,

I've just learning about functions and have tried writing my own function up below, to determine the maximum value of 3 values inputted into the system. I have tried to "call" the function before the "main" body and then defined the function below.

It's not quite working though.

I'm confused about the "return" also.. am I doing it right, by defining my final value as "Answer" and then calling it back in the final "return" statement?

Thanks kindly in advance!!



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>

int int_max_3(int, int, int);



int
main(int argc, char **argv) {
	printf("The answer is", int_max_3);
	
	return 0;
}


int
int_max_3(int a, int b, int c) {
	
	while(scanf("%d%d%d",&a,&b,&c)==3){
		int answer;
		
	if ((a>b) && (a>c)){
		
		answer == a;
		printf("%d is the largest number", answer);
		break;
	}
	else if ((b>a) && (b>c)){
		answer == b;
		printf("%d is the largest number", answer);
		break;
	}
	else {
		answer == c;
		printf("%d is the largest number", answer);
		break;
	}
	}
	return answer;
}
return can be used to bring back a value or any other thing. it can also be used to bring back whether the function worked properly(code 0) or not(code 1)
closed account (o3hC5Di1)
Hi there,

You're doing it quite right, but you need to pass some numbers to the function, or it won't have any data to work with. I notice you are requesting the numbers from the user in the in_max function, but it's name suggests it should only find the maximum - not ask the numbers.

Here's some corrections to your code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>  //iostream is preferred in c++ for using std::cout

int int_max_3(int, int, int);  //this is called a function prototype

int main(int argc, char **argv) {

        int i1, i2, i3; //declare integers
        std::cout << "Please enter 3 integers, separated by spaces: ";
        std::cin >> i1 >> i2 >> i3;  //read user input

        //pass the integers to the function and print the result
	std::cout << "The answer is "<< int_max_3(i1, i2, i3);
	
	return 0;
}


int int_max_3(int a, int b, int c) {
	int answer; //answer variable must be declared or you can't use it
	if ((a>b) && (a>c)){
		
		answer == a;  //you don't need break; here - only in switch statements or loops
	}
	else if ((b>a) && (b>c)){
		answer == b;
	}
	else {
		answer == c;
	}

	return answer;
}


Return values are a way of either getting feedback from a function (for instance if it's operation was succesful) or getting modified values back from the function (for instance int sum(2, 3) would return an integer 5. So in your case you do indeed need to return the answer.

Let us know if you have any further questions.

All the best,
NwN
Topic archived. No new replies allowed.