how to solve this problem??

ive written a code for the following problem but it doesnt work properly according to the question. can anyone help??
PROBLEM:://WCP to enter to enter 5 integers in a single array.
If the number is greater than 11
it doesnt store it and prints "Please reenter the number"
it displays the same message
EVERY TIME a number>11 is entered//
[code]
#include


void main()
{
int num[5],i;

printf("
pls enter 5 numbers::");

for(i=0; i<5; i++)

{ scanf("%d", &num[i]);

if(num[i]>11)
{
printf("
Pls reenter the number");
}
scanf("%d", &num[i-1]);

}

for(i=0; i<5; i++)
printf("
The numbers are::
%d", num[i]);

}
[/code]

Comments

  • The main trouble with your code is that the second scanf should be within the test function and the index should be i:

    [code]
    if(num[i]>11)
    {
    printf("
    Pls reenter the number");
    scanf("%d", &num[i]);
    }

    }

    [/code]

    You can find other suggestions in a separate post I made asking for information on the scanf() function:

    http://www.programmersheaven.com/mb/beginnercpp/402619/402619/a-scanf-question-for-the-gurus/?S=B20000#402619

    Take Care,
    Ed
  • #include
    #include

    int main()
    {
    int num[5],i;
    printf("
    Pls enter 5 numbers : ");
    for(i=0; i<5; i++){
    scanf("%d", &num[i]);
    if (num[i]>11) {
    printf("
    Pls reenter number %d: ", i+1);
    i--;
    continue;
    }
    }
    printf("
    The numbers are:");
    for(i=0; i<5; i++)
    printf("
    %d %d", i+1, num[i]);
    printf("

    ");
    system("PAUSE");
    return 0;
    }

  • Just for grins, how about something like

    [code]
    #include
    #include
    #include

    int main(void) {

    int num[5] = { 0 }, i = 0;
    char nbuf[32] = { 0 };

    while(i < 5) {

    do {

    printf("%s number %d
    ", num[i] > 11 ? "please reenter" : "enter", i + 1);
    fgets(nbuf, sizeof nbuf, stdin);

    } while((sscanf(nbuf, "%d", &num[i]) != 1) || num[i] > 11);

    i++;
    }

    printf("

    The numbers are: ");

    for(i=0; i<5; i++)
    printf("%d ", num[i]);

    return (0);
    }[/code]

    HTH

  • Thanks a lot!!!
    I got three replies, but yours was the only one understood clearly and it is working perfectly.
    Thanks again.
  • Thanks a lot!!!
    I got three replies, but yours was the only one understood clearly and it is working perfectly.
    Thanks again.
  • If you want you can leave out the line

    [code]continue;[/code]

    since there is no code between the end of the if block and the closing of the for block.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories