Do it this way when an invalid value is entered, the user must repeat the new value in C

For my HW assignment, I need to create a program that draws an asterisk-based triangle, which depends on user input. I got my program to work until the user enters an integer that displays the correct triangle, but my problem is when an invalid value is entered, how can I make it so that the user re-tries to represent the value? I looked at the forums and I was not able to find a similar question.

#include <stdio.h>

int main() {
int lines, a, b;

//prompt user to input integer
printf("Input a value from 1 to 15: ");
scanf("%d", &lines);

//Check if inputed value is valid
if(lines >= 1 && lines <= 15) {
    /*create triangle based on inputed value */
    for(a = 1; a <= lines; a++) {
        for(b=1; b<= a; b++) {
            printf("*");
        }
        printf("\n");
    }
}
else {
    printf("not valid");/* repeat code in this else statement, maybe */
}
system("pause");
}
+1
source share
2 answers
#include <stdio.h>

int main() {
int lines, a, b;

//prompt user to input integer
do{
    printf("Input a value from 1 to 15: ");
    scanf("%d", &lines);

    //Check if inputed value is valid
    if(lines < 1 || lines > 15) {
        printf("Error: Please Enter a Valid number!!!\n");
        continue;
    }
    /*create triangle based on inputed value */
        for(a = 1; a <= lines; a++) {
            for(b=1; b<= a; b++) {
                printf("*");
            }
            printf("\n");
        }
}while(1);
system("pause");
}

, ( 1-15), else break.

do{
    printf("Input a value from 1 to 15: ");
    scanf("%d", &lines);

    //Check if inputed value is valid
    if(lines < 1 || lines > 15) {
        printf("Error: Please Enter a Valid number!!!\n");
        continue;
    }
    else{
    /*create triangle based on inputed value */
        for(a = 1; a <= lines; a++) {
            for(b=1; b<= a; b++) {
                printf("*");
            }
            printf("\n");
        }
        break;
   }
}while(1);
system("pause");
}
0

do .. while, .

int main() { 
   int lines, a, b;

    do {

        //prompt user to input integer
        printf("Input a value from 1 to 15: ");
        scanf("%d", &lines);

        //Check if inputed value is valid
        if(lines >= 1 && lines <= 15) {
            /*create triangle based on inputed value */
           for(a = 1; a <= lines; a++) {
                for(b=1; b<= a; b++) {
                   printf("*");
               }
               printf("\n");
           }

           break; //break while loop after valid input
        }
       else {
          printf("not valid");/* repeat code in this else statement, maybe */
       }
   }while(1);
   system("pause");
}
0

All Articles