Hi! I am pretty new to c++ and i have a question- Is it possible to replace this while loop with a return value that can influence an "if" statement in "main()" ?
Code with the while loop:
1 2 3 4 5 6 7 8 9 10 11 12
int setShips(){
int ships = 0;
while(ships<10){
int x = rand() % rows;
int y = rand() % cols;
if(matrix[x][y] != 1){
ships++;
matrix[x][y]=1;
}
}}
This is what i have made, but doesn't work:
int SetShips(int ships);
int main()
{
int ships=0;
if (ships < 10){
SetShips(ships);
int x =rand() % rows;
int y =rand() % cols;
if (matrix[x][y] != 1){
matrix[x][y]=1;
ships++;
}
return 0;
}
int SetShips(int ships){
if (ships < 10){
return 1+SetShips(ships+1);
}
return 1;
}
A return statement returns a value and terminates the function.
1 2 3 4 5
int random_function(int input)
{
//Do stuff
return 0;
}
The function stops there and will do nothing more, because once something is returned the function is done. However a while loop will execute a block of code while the condition is true. It never returns a value just repeats lines of code.
In your program the function setShips() should be return an integer, hence the int before the name, yet it never returns any value. If you don't want a function to return any value instead of putting a type to return simply type void.