Why is the output of the program 1?

Why is the output of the program 1?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Example program
#include <iostream>
using namespace std;
int srt()
{
    for(int i=1;i<=5;i++)
    {
        return i;
    }
    return 5;
}

int main()
{
    int x=srt();
    cout<<x;
    
}
Last edited on
When you return you're exiting the function and returning that value.

In your for loop, you return i your first time passing through effectively exiting the function and returning 1 to the main function for x.
Topic archived. No new replies allowed.