-4

Here if the condition occurs the value of i store in the array prime. But the index of the array is not increasing, all the values are storing at [0] index and destroy the previous value.

Tried all the other methods but didn't find anything. I tried prime[x++] and prime[x+1], but they both didn't work for me. If someone gives me a solution then I'll be very thankful to you.

#include<iostream>
using namespace std;

int main()
{
    int num = 20, prime[20], x;

    for (int i = 1; i <= num; i++) {
        if (i % 2 != 0) {
            prime[x] = i;
        }
    }

    for (int k = 1; k <= num; k++) {
        cout << prime[x] << "\t";
    }
}
JeJo
  • 30,635
  • 6
  • 49
  • 88

2 Answers2

1

You have the variable x un-initialized and you are using it, in the line

prime[x] = i;

assuming that it has been initialized. This invokes undefind behavior in your program and the result could not be predicted. Initialize it with the appropriate number to make the program to have a defined behavior.

Regarding prime numbers, see this SO post: Printing prime numbers from 1 through 100.

JeJo
  • 30,635
  • 6
  • 49
  • 88
0

defining x as uninitialized is a undefined behaviour.

Initialize x as 0 (int x = 0;)
Try with bellow :

int x = 0;

for(int i=1; i<=num; i++){
    if(i%2!=0){
        prime[x] = i;
        x++;
     }
  }

Now you have the number of prime array elements :

Now print prime array :

for(int k=0; k<x; k++){
    cout << prime[k] << "\t";
  }

The output (it seems your code detect odd numbers) :

1   3   5   7   9   11  13  15  17  19   

Test the code online

  • Thank you Mohammad Sir, really really thank you, sir. I am trying to solve this problem from last week but I can't get any solution. Thank you once again. And can you explain me this also that why you use prime[k] rather than prime[x] . When I try prime[x] it prints only zeroes but when I use prime[k] it works perfectly. Can you please explain. – Prabhjot Singh Nov 04 '18 at 11:16
  • 2
    @PrabhjotSingh Sounds like you need to [read more](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) before you try and guess something. – JeJo Nov 04 '18 at 11:24
  • @PrabhjotSingh you count the odd numbers with `x` and save them in `prime[]` array. So you have the number of odds in array, Now you should print this array... then `for` loop iterate in `prime[]`.... by the way, if you define a variable without initialization, it give a random number, not `zero` so initialize them before using... SO , I offer you read a c++ book for beginners... – BattleTested_закалённый в бою Nov 04 '18 at 15:01