Rewrite 2-digit maximum input numbers for output

Asked

Viewed 53 times

-2

I need to rewrite two-digit numbers at most input to the output, stopping processing the input after reading the number 42.

Input:

1
2
88
42
99

Output:

1
2
88

My code is like this, I can’t understand what’s wrong:

#include <stdio.h>
#include <stdlib.h>

int main(){
    int a=100;
    int *n=(int*)malloc(100*sizeof(int));

    for(int i=0;i<100;i++){
        scanf("%d", &n[i]);
        if(n[i]==42){
            a=i++;
            break;
        } 
    }

    for(int i=0;i<a;i++){
        printf("%d\n", n[i]);
    }

    return 0;
}
  • 1

    what error? what output when you run?

  • I don’t see anything wrong either, the only thing I noticed is that it allows printing numbers with more than 2 digits, example 999

1 answer

0


stopping to read after reading the number 42, then its repetition should not have a limit for(int i=0;i<100;i++){ but an infinite bond, should be something like : for(int i=0;i>-1;i++){

and your code would stay that way

#include <stdio.h>
#include <stdlib.h>

int main(){
    int a=0;
    int *n=(int*)malloc(100*sizeof(int));

    for(int i=0;i>-1;i++){
        scanf("%d", &n[i]);
        if(n[i]==42){
            a=i++;
            break;
        } 
    }

    for(int i=0;i<a;i++){
        printf("%d\n", n[i]);
    }

    return 0;
}

if that is the mistake.

  • now it worked!!! thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.