arrays and index [closed] - c++

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
How can I enter numbers into an array such that duplicate entries are ignored?
For example, if I put 6 and then 3 into the array, attempting to then insert 6 into the the array should cause 6 to be rejected (since it is already in the array).
#include <iostream>
using namespace std;
int main()
{
int x,y;
int number;
int arr[5];
for (x=0; x<5; )
{
cout<<"enter a number:"<<endl;
cin>>number;
bool replace = True;
for (y=0; y<x; y++)
{
if (number != arr[y])
{
cout << "try next time" << endl;
replace = False;
break;
}
}
if (replace)
{
arr[x] = number;
x++;
}
}
return 0;
}

std::set<int> would do what you want. This is not indexable, though.
You could use Boost.MultiIndex to give you random access and enforce uniqueness on the same underlying list of values.
btw - asking directly for code is not recommended practice.

you have too many x++'s and you don't preset arr (maybe more style than error)
how do you know it's not working?
(put some debug code inside of if (number == arr[y]) and if (replace)

What you really want is a set. Sets cannot contain duplicate elements.
Here is a reference to the set in C++.
Just use the set as a container for your numbers. When you try to add a duplicate, it will be automatically rejected.

You don't want an array but a datastructure called Hashtable for that;
Alternatively, you might want to look up a datastructure called associative array.

You shouldn't use arrays for this. You should use, for example, std::set. Or, if you need to have an array as your data structure, you could encapsulate the array (e.g. realized through std::vector) in a class and define specific functions to access the array elements. Additionally, you could hold a std::set to provide a fast check for existing elements.

Should be :
int arr[5] = {0,0,0,0,0};
Remove the x++ from the following line:
for (x=0;x<5;x++)
Then:
bool replace=true;
for (y=0;y<x;y++)
{
if (number == arr[y])
{
replace=false;
break;
}
}
if (replace)
{
arr[x]=number;
x++;
}
Finally, remove the :
else if(number == arr[x])
{
arr[x]=number;
cout << "try next time"<<endl;
}
You can insert :
cout << "try next time"<<endl;
before the
replace=false;

Take out the x++ in the for loop, That way you will only increment that count when you enter a new number.
Also, if you want to only run the loop five times, your outer for loop should be only to x<5.
All in all your outer loop should read:
for (x=0;x<5;)

Take a closer look at where you increment x.

It looks like you want to read in a sequence of numbers eliminating any duplicates.
It also appears that the maximum number of unique numbers is 5.
int n = 0; /* The number of unique numbers read in so far */
for {;;}
cout << "enter nmber" << endl;
cin >> number;
for (x=0; x < n; ++x) {
if (number == arr[x]) goto L1; /* I love messing with peoples head by using this goto */
}
arr[n] = number;
++n;
if (n == 5) break;
L1:
continue;
}

Related

How to find the sum of numbers that have digits higher than 5 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
so I want to write a function that returns the sum of all numbers in an array who's digits are higher then 5 so for example if the array is [12, 66, 23, 67] the answer would be 66+67
This code summs all the numbers in the array and I can'\t figure out why
using namespace std;
int func(int n[], int size){
int digit, S=0, a;
for(int i=0; i<size; i++){
a= n[i];
while( n[i]!=0){
digit= n[i]%10;
if(digit>=5){
n[i]= n[i]/10;
}
else break;
}
S=S+a;
}
return S;
}
int main()
{
int n[3], i;
for(int i=0; i<3; i++){
cin>>n[i];
}
cout<<func(n, 3)<<endl;
return 0;
}```
S=S+a This piece of code is out of your while loop and inside for loop, this will add all the elements in the array
The main problem is that you are not checking when you should add a to S.
These lines are causing the problem:
int func(int n[], int size){
int digit, S=0, a;
for(int i=0; i<size; i++){
a= n[i];
while( n[i]!=0){
digit= n[i]%10;
if(digit>=5){ // Wrong. Do "digit > 5"
n[i]= n[i]/10;
}
else break; <--- exiting this while loop
}
S=S+a; <--- ...but still adding?
}
return S;
}
You are breaking the loop, but still adding to the sum.
You should use a flag. Your inner loop would look something like this:
// We need to check if each digit is valid
bool each_digit_greater_than_5 = true;
// As long as we have digits left and all previous digits were valid
while(n[i] != 0 && each_digit_greater_than_5)
{
// Extract a digit
digit = n[i] % 10;
// If valid, get next digit to extract
if(digit > 5)
{
n[i] /= 10;
}
// Else, exit the loop
else
{
each_digit_greater_than_5 = false;
}
}
And then, simply check if each_digit_greater_than_5:
// If number was valid
if(each_digit_greater_than_5)
{
// Add to sum
S = S + a;
}
Extra Notes:
How you write the code is often more important than what you write.
Here are (some) food for thoughts.
Use better formatting: The whole block of code should be uniformly indented. This:
...
for(int i=0; i<size; i++){
a= n[i];
while( n[i]!=0){
digit= n[i]%10;
...
is both confusing and unclear. Use same indentation for each separate block:
...
for(int i=0; i<size; i++){ // The base block
a= n[i]; // new block start, add indent
while( n[i]!=0){ // same block, same indent
digit= n[i]%10; // new block, add indent
...
Use better naming: Don't use S, a and n unless they are very clear.
digit is a good choice, so credits for that!
Here, it is better to use:
sum_of_special_numbers
and
array
and
current_number
instead of S, n and a.
Comment!: Another very important part of programming (Note: not coding).
Are you coding?
Don't care if anyone understands it or not, just doing it cause they said so.
Or programming?
Making a clear, maintainable and debuggable code.
You decide!
Since this question is tagged with C++, I want to give an additional answer that uses C++ and especially modern C++ algorithms. I added also comments to the code and used meaningful variable names. I recommend that you try to do the same in the future.
What is the example code doing?
First, it informs the user about the software and asks, how many values should be checked and added. The values will be stored in a std::vector. With std::copy_n and the std::istream_iterator we read the values given by the user. The std::istream_iterator simply calls the extractor operator >> in the copy loop.
Then we call the subfunction to calculate the sum and show it to the user.
The subfunction consists of one Lampda definition and one std::accumulate statement. That's all.
The lambda converts the int to a std::string and then checks if any of the characters in the number is lower than '5'. Then it returns an inverted result.
So, you see, with C++, the implementation get's very simple:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <numeric>
int sumOfNumbersWithDigitsGreaterThan5(const std::vector<int>& v) {
// Create a lambda that checks, if all digits are greater than 5
auto check5 = [](const int i) -> bool { std::string s{ std::to_string(i) };
return !std::any_of(s.begin(), s.end(), [](const char c) { return c <= '5'; }); };
// Calculate the sume of all given values in the vector with all digits greater than 5
return std::accumulate(v.begin(), v.end(), 0,
[&](const int init, const int i) { return init + (check5(i) ? i : 0); });
}
int main() {
// Inform the user, what to do
std::cout << "Sum of all numbers having all digits greater than 5\n\nHow many numbers to you want to sum?: ";
// Get the number of values that we want to sum up. Check plausibility
if (int numberOfValuesToCheck{}; (std::cin >> numberOfValuesToCheck) && (numberOfValuesToCheck > 0)) {
// Create a std::vector for our values having the requested number of elements
std::vector<int> values(numberOfValuesToCheck);
// Read the requested number of elements from std::cin to the values vector
std::copy_n(std::istream_iterator<int>(std::cin), numberOfValuesToCheck, values.begin());
// Show result
std::cout << "\n\nThe sum for all numbers with all digits greater 5 is: " <<
sumOfNumbersWithDigitsGreaterThan5(values) << "\n";
}
else {
std::cerr << "\n\n*** Error: Wrong input\n";
}
return 0;
}
Of course there are many many other possible solutions . . .

How to alert a user if the number they entered into a 1 dimensional array has already been entered?

Ok so I'm trying to write a program that will accept 5 distinct numbers from the user and would input into a 6 element one dimensional array and then be tested to make sure that its between 1 and 69 and that the number (just entered) isn't already in the array.
I've already tested for the range issue but I cant figure out how to test the duplicate array issue because the tester executes regardless of what the numbers are or just not at all.
Also just in case anyone is wondering any kind of "pball" variable is related to the powerball lottery, this is just one function of several In a powerball simulator. As much as I want to I cant use library functions (like sort) due to requirements by my professor.
#include <iostream>
using namespace std;
const int PBALLAMOUNT = 6;
const int PBMAX = 69;
const int PBMIN = 1;
int pBallNums[PBALLAMOUNT];
void pBallInput(int pBallNums[PBALLAMOUNT]) {
cout << "Enter the numbers you want to use." << endl;
for (int k = 0; k < PBALLAMOUNT - 1; k++) {
cin >> pBallNums[k];
while (pBallNums[k] < PBMIN || pBallNums[k]>PBMAX) {
cout << "Invalid input! Please enter different numbers between 1 and 69" << endl;
cin >> pBallNums[k];
}
for (int qt = 0; qt < PBALLAMOUNT; qt++)
while (pBallNums[qt] == pBallNums[qt + 1]) {
cout << " you need 5 unique numbers. Please enter a new number ";
cin >> pBallNums[qt];
}
}
}
when I execute the current code, the repeat test displays regardless. it should only display if the number your trying to enter has already been put put into the array.
Thanks in advance!
for (int qt = 0; qt < PBALLAMOUNT; qt++)
while (pBallNums[qt] == pBallNums[qt + 1]) {
// stuff not changing qt
}
You have an endless while loop within that for loop. The outer for loop isn't iterating, it's just the inner while loop.
(if the order of input doesn't matter, then use a std::set or even better std::unordered_set)
Apart from that, I think you should try to organize your code better. Use small functions for small tasks!
while (/* not all numbers set */)
{
// input number here
if (/* input failed */)
{
// handle IO failure; best to exit probably
}
else if (/* input not in correct range */)
{
// print error, retry
}
else if (/* input number already present in array */)
{
// print error, retry
}
else
{
// save input to current array index
// advance current array index if you need more numbers
}
}
// Implement this for the check above
// size == numbers read so far
bool input_already_present(int * array, size_t size, int number);

Finding the Largest and Smallest Integers In A Set- Basic [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm kind of on the right track, however my output is not quite right. The program asks for the number of integers you have and then it asks for those numbers. For an example is says please enter the number of integers, you can put 3. And then you enter 3 numbers. I can't use arrays because I am a beginner student and we have not learned those yet. Using count is the only way that allows me to input integers. What do I need to add to my program? Again I am a general computer science student so I can't use anything advanced. I used include iostream, namespace int main and all that you just cant see it
int data;
int num;
int count=0;
int max=0;
do
{
cout<<"Enter the number of intergers"<<endl;
cin>>num;
while (count<num)
{
cout<<"Please enter a number"<<endl;
cin>>data;
count++;
if (data<min)
{
min=data;
}
if (data>max)
{
max=data;
}
}
cout<<"Smallest integer:"<<min<<endl;
cout<<"Largest integer:"<<max<<endl;
cout<<"Would you like to continue?"<<endl;
cin>>ans;
} while ((ans=='y')||(ans=='Y'));
return 0;
}
Try out something like this:
int data;
int num;
int max=0, min = 1000000;
cout<<"Enter the number of intergers"<<endl;
cin>>num;
for (int count = 0; count < num; ++count)
{
cout<<"Please enter number #" << count <<endl;
cin>>data;
if (data<min)
{
min = data;
}
if (data>max)
{
max = data;
}
}
cout<<"The smallest number:"<<min<<endl;
cout<<"The largest number:"<<max<<endl;
You can use two temporal variables to store the smallest-so-far and biggest-so-far numbers. On each loop iteration, you check if need to update them.
I don't want to put any code... it is your assignment ;-)
The answer above is the way to do this correct but to be more explicit you may have to update the smallest or the biggest number. For example; give the computer 5 then 4.. Your program prints 4 as a biggest number. However if you update "max" by using any other temporary int, it will give the right number .
First of all, your condition is wrong, it should be while( count < num), since count starts at 0. Now, if you want the quick n' dirty way, simply initialize two variables, min and max to the minimum and maximum values an int can hold. Check the input via comparisons for each variable and update as needed.

accessing an array [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
i am declaring a global array,and then assigning the values inside a if statement. But when i am using the array in another if statement the array has different values other than i assigned previously.
For example:
int arr[5];
xyz(bool p,bool q)
{
if(p)
{
for(int i=0;i<5;i++)
{
arr[i]=rand()%100;
}
}
if(q)
{
for(i=0;i<5;i++)
printf("%d",arr[i]);
}
}
can anyone help??
Well, if p != q then any changes you make to arr in the first conditional will not be printed when you enter the second conditional. If arr was never initialized, it will almost certaninly not have the values you expect.
Edit: Based on your comment below, Try using a std::vector<int> instead of a C style integer array, as in:
#include <vector>
std::vector<int> arr(5); // was int arr[5]
Also a couple suggestions:
Where practical (which is almost, but not quite always) you should be using the standard containers in C++. They tend to be better behaved than C style arrays.
Use of global variable can sometimes lead to more problems than they solve. Recommend you make arr a local variable and pass it as a parameter where needed. This helps people looking at your code know what it needs and what it accesses without having to actually dig through the code to see it all. It's possible (perhaps even likely) that something else is changing arr without you knowing it. If you always pass arguments and refrain from using globals, this will help you discover where it's being changed.
So, combining these I would recommend doing something like:
#include <vector>
#include <iostream>
xyz(std::vector<int>& arr, bool p, bool q)
{
std::vector<int>::iterator ai;
if(p)
{
for(ai = arr.begin(); ai != arr.end(); ++ai)
{
*ai = rand() % 100;
}
}
if(q)
{
for(ai = arr.begin(); ai != arr.end(); ++ai)
{
std::cout << *ai << std::endl;
}
}
}
int main()
{
std::vector<int> arr(5);
xyz(arr, true, false);
xyz(arr, false, true);
return 0;
}
Try adjusting your first code block to something more like this:
if (p) {
int temp;
for (int i=0; i<5; i++) {
temp = rand() % 100;
printf("%i: %d\n", i, temp);
arr[i] = temp;
}
}
Now, you will get a listing of the random values before they are written into the array. Compare this list to what you get when you read them from the array later.
Update: I ran the above modification to your code on Codepad, and I am seeing the exact same values both times.
I don't even see why you're adding those 'bool' variables since you're not creating to never run it!
So just use this code [ which is the same as beta's version];
int temp;
for (int i=0; i<5; i++) {
temp = rand() % 100;
cout << i << temp << endl;
arr[i] = temp;
}

Prime numbers program

I'm currently trying out some questions just to practice my programming skills. ( Not taking it in school or anything yet, self taught ) I came across this problem which required me to read in a number from a given txt file. This number would be N. Now I'm suppose to find the Nth prime number for N <= 10 000. After I find it, I'm suppose to print it out to another txt file. Now for most parts of the question I'm able to understand and devise a method to get N. The problem is that I'm using an array to save previously found prime numbers so as to use them to check against future numbers. Even when my array was size 100, as long as the input integer was roughly < 15, the program crashes.
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main() {
ifstream trial;
trial.open("C:\\Users\\User\\Documents\\trial.txt");
int prime;
trial >> prime;
ofstream write;
write.open("C:\\Users\\User\\Documents\\answer.txt");
int num[100], b, c, e;
bool check;
b = 0;
switch (prime) {
case 1:
{
write << 2 << endl;
break;
}
case 2:
{
write << 3 << endl;
break;
}
case 3:
{
write << 5 << endl;
break;
}
case 4:
{
write << 7 << endl;
break;
}
default:
{
for (int a = 10; a <= 1000000; a++) {
check = false;
if (((a % 2) != 0) && ((a % 3) != 0) && ((a % 5) != 0) && ((a % 7) != 0)) // first filter
{
for (int d = 0; d <= b; d++) {
c = num[d];
if ((a % c) == 0) {
check = true; // second filter based on previous recorded primes in array
break;
}
}
if (!check) {
e = a;
if (b <= 100) {
num[b] = a;
}
b = b + 1;
}
}
if ((b) == (prime - 4)) {
write << e << endl;
break;
}
}
}
}
trial.close();
write.close();
return 0;
}
I did this entirely base on my dummies guide and myself so do forgive some code inefficiency and general newbie-ness of my algorithm.
Also for up to 15 it displays the prime numbers correctly.
Could anyone tell me how I should go about improving this current code? I'm thinking of using a txt file in place of the array. Is that possible? Any help is appreciated.
Since your question is about programming rather than math, I will try to keep my answer that way too.
The first glance of your code makes me wonder what on earth you are doing here... If you read the answers, you will realize that some of them didn't bother to understand your code, and some just dump your code to a debugger and see what's going on. Is it that we are that impatient? Or is it simply that your code is too difficult to understand for a relatively easy problem?
To improve your code, try ask yourself some questions:
What are a, b, c, etc? Wouldn't it better to give more meaningful names?
What exactly is your algorithm? Can you write down a clearly written paragraph in English about what you are doing (in an exact way)? Can you modify the paragraph into a series of steps that you can mentally carry out on any input and can be sure that it is correct?
Are all steps necessary? Can we combine or even eliminate some of them?
What are the steps that are easy to express in English but require, say, more than 10 lines in C/C++?
Does your list of steps have any structures? Loops? Big (probably repeated) chunks that can be put as a single step with sub-steps?
After you have going through the questions, you will probably have a clearly laid out pseudo-code that solves the problem, which is easy to explain and understand. After that you can implement your pseudo-code in C/C++, or, in fact, any general purpose language.
There are a two approaches to testing for primality you might want to consider:
The problem domain is small enough that just looping over the numbers until you find the Nth prime would probably be an acceptable solution and take less than a few milliseconds to complete. There are a number of simple optimizations you can make to this approach for example you only need to test to see if it's divisible by 2 once and then you only have to check against the odd numbers and you only have to check numbers less than or equal to the aquare root of the number being tested.
The Sieve of Eratosthenes is very effective and easy to implement and incredibly light on the math end of things.
As for why you code is crashing I suspect changing the line that reads
for( int d=0; d<=b; d++)
to
for( int d=0; d<b; d++)
will fix the problem because you are trying to read from a potentially uninitialized element of the array which probably contains garbage.
I haven't looked at your code, but your array must be large enough to contain all the values you will store in it. 100 certainly isn't going to be enough for most input for this problem.
E.g. this code..
int someArray[100];
someArray[150] = 10;
Writes to a location large than the array (150 > 100). This is known as a memory overwrite. Depending on what happened to be at that memory location your program may crash immediately, later, or never at all.
A good practice when using arrays is to assert in someway that the element you are writing to is within the bounds of the array. Or use an array-type class that performs this checking.
For your problem the easiest approach would be to use the STL vector class. While you must add elements (vector::push_back()) you can later access elements using the array operator []. Vector will also give you the best iterative performance.
Here's some sample code of adding the numbers 0-100 to a vector and then printing them. Note in the second loop we use the count of items stored in the vector.
#include <vector> // std::vector
...
const int MAX_ITEMS = 100;
std::vector<int> intVector;
intVector.reserve(MAX_ITEMS); // allocates all memory up-front
// add items
for (int i = 0; i < MAX_ITEMS; i++)
{
intVector.push_back(i); // this is how you add a value to a vector;
}
// print them
for (int i = 0; i < intVector.size(); i++)
{
int elem = intVector[i]; // this access the item at index 'i'
printf("element %d is %d\n", i, elem);
}
I'm trying to improve my functional programming at the moment so I just coded up the sieve quickly. I figure I'll post it here. If you're still learning, you might find it interesting, too.
#include <iostream>
#include <list>
#include <math.h>
#include <functional>
#include <algorithm>
using namespace std;
class is_multiple : public binary_function<int, int, bool>
{
public:
bool operator()(int value, int test) const
{
if(value == test) // do not remove the first value
return false;
else
return (value % test) == 0;
}
};
int main()
{
list<int> numbersToTest;
int input = 500;
// add all numbers to list
for(int x = 1; x < input; x++)
numbersToTest.push_back(x);
// starting at 2 go through the list and remove all multiples until you reach the squareroot
// of the last element in the list
for(list<int>::iterator itr = ++numbersToTest.begin(); *itr < sqrt((float) input); itr++)
{
int tmp = *itr;
numbersToTest.remove_if(bind2nd(is_multiple(), *itr));
itr = find(numbersToTest.begin(), numbersToTest.end(), tmp); //remove_if invalidates iterator
// so find it again. kind of ugly
}
// output primes
for(list<int>::iterator itr = numbersToTest.begin(); itr != --numbersToTest.end(); itr++)
cout << *itr << "\t";
system("PAUSE");
return 0;
}
Any advice on how to improve this would be welcome by the way.
Here is my code. When working on a big number, it's very slow!
It can calculate all prime numbers with in the number you input!
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
int m;
int n=0;
char ch;
fstream fp;
cout<<"What prime numbers do you want get within? ";
if((cin>>m)==0)
{
cout<<"Bad input! Please try again!\n";
return 1;
}
if(m<2)
{
cout<<"There are no prime numbers within "<<m<<endl;
return 0;
}
else if(m==2)
{
fp.open("prime.txt",ios::in|ios::out|ios::trunc);//create a file can be writen and read. If the file exist, it will be overwriten.
fp<<"There are only 1 prime number within 2.\n";
fp<<"2\n";
fp.close();
cout<<"Congratulations! It has worked out!\n";
return 0;
}
else
{
int j;
int sq;
fp.open("prime.txt",ios::in|ios::out|ios::trunc);
fp<<"2\t\t";
n++;
for(int i=3;i<=m;i+=2)
{
sq=static_cast<int>(sqrt(i))+1;
fp.seekg(0,ios::beg);
fp>>j;
for(;j<sq;)
{
if(i%j==0)
{
break;
}
else
{
if((fp>>j)==NULL)
{
j=3;
}
}
}
if(j>=sq)
{
fp.seekg(0,ios::end);
fp<<i<<"\t\t";
n++;
if(n%4==0)
fp<<'\n';
}
}
fp.seekg(0,ios::end);
fp<<"\nThere are "<<n<<" prime number within "<<m<<".\n";
fp.close();
cout<<"Congratulations! It has worked out!\n";
return 0;
}
}
For one, you'd have less code (which is always a good thing!) if you didn't have special cases for 3, 5 and 7.
Also, you can avoid the special case for 2 if you just set num[b] = 2 and only test for divisibility by things in your array.
It looks like as you go around the main for() loop, the value of b increases.
Then, this results in a crash because you access memory off the end of your array:
for (int d = 0; d <= b; d++) {
c = num[d];
I think you need to get the algorithm clearer in your head and then approach the code again.
Running your code through a debugger, I've found that it crashes with a floating point exception at "if ((a % c) == 0)". The reason for this is that you haven't initialized anything in num, so you're doing "a % 0".
From what I know, in C/C++ int is a 16bit type so you cannot fit 1 million in it (limit is 2^16=32k). Try and declare "a" as long
I think the C standard says that int is at least as large as short and at most as large as long.
In practice int is 4 bytes, so it can hold numbers between -2^31 and 2^31-1.
Since this is for pedagogical purposes, I would suggest implementing the Sieve of Eratosthenes.
This should also be of interest to you: http://en.wikipedia.org/wiki/Primality_test
for(int currentInt=2; currentInt<=1000000; currentInt++)
{check = false; // Basically the idea for this for loop is to run checks against integers. This is the main for loop in this program. I re initialize check to false ( check is a bool declared above this. )
for( int arrayPrime=0; arrayPrime<currentPrime; arrayPrime++) // This for loop is used for checking the currentInt against previously found primes which are stored in the num array.
{ c=num[arrayPrime];
if ((currentInt%c)==0) { check = true;// second filter based on previous recorded primes in array
break;} // this is the check. I check the number against every stored value in the num array. If it's divisible by any of them, then bool check is set to true.
if ( currentInt == 2)
{ check = false; } // since i preset num[0] = 2 i make an exception for the number 2.
if (!check)
{
e=a;
if(currentPrime <= 100){
num[currentPrime]= currentInt;} // This if uses check to see if the currentInt is a prime.
currentPrime = currentPrime+1;} // increases the value of currentPrime ( previously b ) by one if !check.
if(currentPrime==prime)
{
write<<e<<endl;
break;} // if currentPrime == prime then write the currentInt into a txt file and break loop, ending the program.
Thanks for the advice polythinker =)
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
{
ifstream trial;
trial.open("C:\\Users\\User\\Documents\\trial.txt");
int prime, e;
trial>>prime;
ofstream write;
write.open("C:\\Users\\User\\Documents\\answer.txt");
int num[10000], currentPrime, c, primePrint;
bool check;
currentPrime=0;
num[currentPrime] = 2;
currentPrime=1;
for(int currentInt=2; currentInt<=1000000; currentInt++)
{check = false;
for( int arrayPrime=0; arrayPrime<currentPrime; arrayPrime++)
{ c=num[arrayPrime];
if ((currentInt%c)==0) { check = true;// second filter based on previous recorded primes in array
break;}
}
if (!check)
{ e=currentInt;
if( currentInt!= 2 ) {
num[currentPrime]= currentInt;}
currentPrime = currentPrime+1;}
if(currentPrime==prime)
{
write<<e<<endl;
break;}
}
trial.close();
write.close();
return 0;
}
This is the finalized version base on my original code. It works perfectly and if you want to increase the range of prime numbers simply increase the array number. Thanks for the help =)
Since you will need larger prime number values for later questions, I suggest you follow dreeves advice, and do a sieve. It is a very useful arrow to have in your quiver.