Prince
Prince

Reputation: 47

Is there any method to print the value that user input with array?

It prints the wrong number/random number. What I want is to print numbers higher than 75.

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

    for (i = 1; i <= 5; i++) {
        printf("Input Num %d : ", i);
        scanf("%d", &num);
    }
    if (num >= 75) {
        printf("%d\n", array[i]);
    }
    return 0;
}

Upvotes: 1

Views: 78

Answers (2)

Duck Dodgers
Duck Dodgers

Reputation: 3461

You have a couple of errors:

  1. You iterate over the wrong set. Arrays in C start from 0, NOT 1.
  2. You never set any value for array. What should it contain then? Random stuff of course. You could avoid it by initializing your array to zero. That way you know you are not writing to your array if you get zeros in your output.

Code:

#include <stdio.h>

int main() {
  int array[5] = {};
  int num = 0,i;

  for ( i = 0; i <5; i++) {
    printf("Input Num %d : ",i );
    scanf("%d",&num );
    array[i] = num;
  }
  for ( i = 0; i <5; i++) {
      if (array[i] >= 75) {
          printf("%d\n",array[i]);
      }
  }
  return 0;
}

Upvotes: 0

Loc Tran
Loc Tran

Reputation: 1180

Please use if within "for" loop. and please change "array" to "arr" or another name. The array will be a keyword in c++ sometime. should not use "array" to name a variable. here is my solution:

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

    for (i = 1; i <= 5; i++) {
        printf("Input Num %d : ", i);
        num = 0;
        scanf("%d", &num);
        arr[i-1] = num;

    }

    for (i = 1; i <= 5; i++) {
        if (arr[i - 1] >= 75) {
            printf("%d\n", arr[i - 1]);
        }
    }

    return 0;
}

Upvotes: 1

Related Questions