how to write prime number in vector

#include <iostream>
#include<conio.h>
#include <vector>
using namespace std;
int main () {
int n;
cin>>n;
int prime=1;;
vector<int>primes(n);
for(int i=2;i<n;i++) {
prime=1;

for(int j=2;j<i;j++)
{
if(i%j==0) {
prime=0;
break;
}
if(prime==1) {
cout<<i<<endl;
}
getch ();
return 0;
}
}
}
ıt is not working corectly where is my mistake how can ı write prime number put into vector
You need to call primes.push_back to add your prime number to the vector.
http://www.cplusplus.com/reference/vector/vector/push_back/

Also you code would become easier if you use a function to check if a number is prime.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>
#include <cmath>

int main()
{
    std::size_t n ; // http://en.cppreference.com/w/cpp/types/size_t
    std::cin >> n ;

    std::vector<int> sieve( n, 1 ) ; // initialise to all 1

    // https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
    int ub = std::sqrt(n) + 1.5 ;
    for( int i = 2 ; i < ub ; ++i ) if( sieve[i] == 1 )
    {
        for( std::size_t j = i*i ; j<n ; j += i ) sieve[j] = 0 ;
    }

    for( std::size_t i = 2 ; i < n ; ++i ) if( sieve[i] == 1 ) std::cout << i << '\n' ;
}
how can i write value into vector


Depends.

You do create a vector that has n elements. So does the example by JLBorges.

The latter program assigns new values to existing elements. (Line 16.)
http://www.cplusplus.com/reference/vector/vector/operator[]/
http://www.cplusplus.com/reference/vector/vector/at/

Thomas1965 did suggest adding new elements to vector.
http://www.cplusplus.com/reference/vector/vector/push_back/
http://www.cplusplus.com/reference/vector/vector/emplace_back/


PS. Please post code with code tags. See http://www.cplusplus.com/articles/jEywvCM9/
Registered users can post here. Sign in or register to post.