'how to put an option like this " try again? Y/N"?
I have been trying to put an option that would ask the user to try again or not, but I was unsuccessful in doing that. How do I do it?
#include <stdio.h>
int largest(int[], int);
int main()
{
char repeat;
int arr[5];
int i;
while (repeat == "y" || "Y")
{
for (i = 0; i < 5; i++)
{
printf("\nInput a number at index %d: ", i);
scanf("%d", &arr[i]);
}
for (i = 0; i < 5; i++)
printf("Element[%d] = %d\n", i, arr[i]);
printf("Largest in given array is %d\n", largest(arr, 5));
}
}
int largest(int arr[], int n)
{
int i;
int max = arr[0];
for (i = 1; i < n; i++)
if (arr[i] > max)
max = arr[i];
return max;
}
Solution 1:[1]
You need to initialize repeat to 'y' so it will go through the while loop at least once:
char repeat = 'y';
Your while loop needs to change to:
while (repeat == 'y' || repeat == 'Y') {
Then as the last thing in your while loop, after the printf, you'll want something like this:
printf("\nTry again? (Y/N) ");
scanf(" %c%*[^\n]",&repeat);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
