So I was trying to answer a question on Project Euler (The question was: Find the 10,001 prime number), and ran into a problem that I don't know why it is happening. When I run the following C++ code,
#include <iostream>
using namespace std;
int main()
{
int arr[10001]={2}, term=1, i, num=3;
while(term!=10001)
{
for(i=0; i<term; i++)
{
if(num%arr[i]==0){
break;
}
}
if(i==term){
arr[term]=num;
cout<< arr[term]<< " is prime"<< endl;
term++;
}
num++;
}
cout<< arr[term]<< endl;
}
I always get cout<< arr[term]<< endl; printing out whatever n++;(next number in this case but if I were to change that to n=856then it would print out that number). I dont understand why that array term would change since I thought it would only change when arr[term]=num;is executed
Your code has undefined behaviour because you are accessing the array outside of its bounds.
When the loop breaks, the value of term is 10001, which is the 10002nd element of the array arr whereas your array memory allocated only for 10001 elements.
To print the last element of the array, do:
cout<< arr[term - 1]<< endl;
In every iteration, you execute
arr[term]=num;
cout<< arr[term]<< " is prime"<< endl;
term++;
So when the while ends, term is one more that the one you used for the last assignment.
You have to output the arr[term-1] instead of arr[term] because term is incremented at the end of the assignment to the arr[], hence the term variable is 1 more 10001.
Edited code:
#include <iostream>
using namespace std;
int main()
{
int arr[10002]={2}, term=1, i, num=3;
while(term!=10001)
{
for(i=0; i<term; i++)
{
if(num%arr[i]==0){
break;
}
}
if(i==term){
arr[term]=num;
cout<< arr[term]<< " is prime"<< endl;
term++;
}
num++;
}
cout<< arr[term-1]<< endl;
//Your 'term' variable actually is term + 1, hence, you have
//to print the element at 'term - 1'.
}
Related
I was practicing with vector, I wanted to push an element using push_back(); using a for loop, but the program doesn't even enter the for loop, help!!!
#include <iostream>
#include <vector>
using namespace std;
int main()
{
cout << "check ";
int val;
vector<char> vec;
cout << "check " << endl << "Its in the game";
//those two "check" were to confirm if the program is even running and is it a
problem while declaring the vector
for(int i = 0; i < vec.size(); i++){
cout << "enter element for vector" << endl;
cin >> val;
vec.push_back(val);
}
}
Your vector is empty. The for loop starts at zero, which is not less than zero, so the for loop never runs.
Your vector is literally empty, which means vec.size() is 0.So It will never enter the loop. If you know what your vector size is gonna be, you should define it as
std::vector<int> vec(vec_size);
for(int i=0;i<vec_size;++i)
{
//whatever.....
}
Or you could have used a while loop.
while(std::cin>>val)
{
//do your thing....
}
this is my code:
#include <iostream>
using namespace std;
int main()
{
char character;
int x;
cout << "Input a character: " ;
cin >> character;
x = int(character);
cout << "Its integer value is: " << x << endl;
int arr[7], i=0,j;
while(x>0)
{
arr[i]=x%2;
i++;
x=x/2;
}
cout << "Its Binary format is: ";
for (j=i; j>=0;j--)
{
cout<<arr[j];
}
return 0;
}
I have only 8 array spaces allocated for this code but the displayed result is more than 8 and is totally unrelated to the algorithm. I'm suspecting this to be an overflow issue.
How do i remedy this issue?
Thank you!
while(x>0)
{
arr[i]=x%2;
i++;
x=x/2;
}
let's take case when this loop is executed once.
i is 1 after loop is finished. However, array element at index 1 is not initialized.
You trigger undefined behaviour by trying to print it here:
for (j=i; j>=0;j--) // assuming for should be here
{
cout<<arr[j]; // access array element with index 1 (our example)
}
The fix is to change your loop to
for (j=i-1; j>=0;j--)
Also beware what if user enters number which is larger (or equal) than 7th power of 2. You won't have places in your array to store all digits. And will trigger again undefined behaviour, by trying to write past the end of the array.
Like for example:
#include <iostream>
using namespace std;
int main()
{
for (int n=10; n>0; n--){
cout<< n <<", ";}
}
This will output the numbers 10,9,8,7,6,5,4,3,2,1
So is there a new way so I just get the last instance of the loop, the 1?
I new at this and google isn't giving me any answers.
There is no direct way to detect whether the current iteration of a for loop is the last one. But if the behavior of the loop is predictable, you can usually write code that can detect when you're on the last iteration.
In this case, you could do something like:
if (n == 1) {
cout << n << "\n";
}
in the body of the loop. (Of course it would be simpler in this case to replace the entire loop with cout << "1\n";, but I presume this is an example of something more complex.)
In more complicated cases, you can save whatever information you need in the body of the loop:
int value_to_print:
for ( ... ) {
value_to_print = i;
}
std::cout << value_to_print << "\n";
On each iteration, value_to_print is replaced by the current value of i. The final value is the value of i on the last iteration.
You could create a variable (outside the loop) to hold the "current" value of n; whatever happens to the loop (exit condition reached, break, an exception is thrown...) the value will stay there:
int last_n;
for (int n=10; n>0; n--) {
last_n = n;
cout<< n <<", ";
if (something) {
break; // works in this case
} else if (something else) {
throw some_random_error; // works in this case too
}
}
cout << "The last value of 'n' was " << last_n << endl;
You can use a simple if statement for that.
int main()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
if( n == 1 ) {
return n;
}
}
}
The simplest way to accomplish this is: -
#include <iostream>
using namespace std;
int main()
{
int x;
for (int n = 10; n > 0; n--){
x = n;
}
cout << x;
return 0;
}
I'm new to programming too and was trying to figure out something which will allow me to get the last instance of my loop as output.
I tried something and got the output, see if it can help you (if there's a mistake please let me know).
Here user input string is being replaced by "*" and instead of giving output of every instance i have made so only last instance is given as output.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int string_length;//string length
cout<<"Enter your Email-ID: ";
cin>>str;
string_length = str.length(); //to give the length of input string and use it for the loop
cout<<"lentgh of the string: "<<string_length <<endl;
for(int x = 0; x <= string_length; x++){
str[x] = '*';
while(x==string_length) //string_length is the last instance of the loop
{
cout<<"Here's your Encrypted Email-ID: " <<str<<endl;
break;
}
}
return 0;
}
I'm struggling to apply a "While" loop to the following problem: Design the logic for a program that allows a user to enter a number. Display the sum of every number from one through the entered number.
Start
int userNumber;
Declarations
int number = 1
while number <= userNumber
++number
endwhile
output number
Stop
I know my code isn't correct as it is just adding one to the initial value until the user's number is reached, thus making the output the user's number. How would I go about adding each subsequent value without writing them out e.g. user's number is 10, so the program would add 1+2+3+4+5+6+7+8+9+10 and output the total of 55?
Thank you!
Here's a tip. You'll want to start at the users number and count down to 0. Like this:
int finalNum = 0;
int userNum;
//This is where you need to get the user's number....
while(userNum > 0)
{
finalNum += userNum;
userNum--;
}
//Do whatever you need to finalNum....
EDIT: It appears you've posted pseudocode; usually a big no-no here unless stated otherwise. It's better to post the actual code as it's easier to tell what exactly is going on.
The function you need could look like this for c++:
#include <iostream>
using namespace std;
void calc(unsigned x)
{
unsigned t = 0; // Assume the result to be 0 (zero)
for (i = 1; i <= x; i++) // Continue until i is greater than x
{
t += i; // Accumulate, i.e. t = t +i
}
cout << "sum=" << t << endl; // Print the result
}
int main()
{
calc(10);
return 0;
}
An alternative is:
#include <iostream>
using namespace std;
void calc(unsigned x)
{
cout << "sum=" << (x*(x+1)/2) << endl; // Print the result
}
int main()
{
calc(10);
return 0;
}
This works because the sum of all integers from 1 to n is n*(n+1)/2
Hello I am having trouble with a c++ program. Basically its a loop that iterates the amount of times the user wants it to. Now when it reaches a number divisible by 4 it keeps track of that number and finally then outputs how many times the number entered was divisible by 4.
#include<iostream>
using namespace std;
int num;
int count;
int test = 0;
int main()
{
cin>> num;
for (int count = 0; count < num; count++)
if (count % 4 == 0)
(test++);
else
cout<<"";
return 0;
}
Well - if you use return in main, your program will just exit, because that's what return does - ends the function and returns some value. If you want to actually print the value of test, do it before you return:
cout << test;
getch(); // use this so the console won't close automatically
return 0;
Also, the whole program could be written much better:
int main()
{
cin>> num;
cout << num/4;
getch(); // use this so the console won't close automatically
return 0;
}
Do you need to use a loop? If you just need "How many times is a given number divisible by 4" and are not required to loop
#include<iostream>
using namespace std;
int main()
{
int num;
cin>> num;
cout<< num<<" is divisible by 4 "<< (num>>2) <<" time"<<(num>>2>1?"s":"") <<endl;
return 0;
}
num>>2 is bit shifting to teh right twice, which is the same as doing an integer divide by 4. It could be replaced by num/4 if you wanted. Integer division always truncates, so for all positive numbers, it's like rounding down: the same behavior your loop gives you.