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 11 years ago.
I have compiled the following program and i know what it does, it takes ten numbers multiplies it my itself and then at the end add their total together.
#include <iostream>
using namespace std;
main()
{
int a[10];//1
int sumOfSquares = 0 ;//2
int i =0; //3`enter code here`
cout << "Please enter the ten numbers one by one " << endl;//4
for (i = 0 ; i < 10 ; i++)//5 dont get what this does,
// obviously its a for loop,
// but why does it increment i by one
{
cin >> a [i];//6 this means store the 10 numbers
// in array a and refer to it by the variable i
}
for (i = 0 ; i < 10 ; i++) //7 again i dont get why this is here
{
sumOfSquares = sumOfSquares + a[i]*a[i];//8
}
cout << "The sum of squares is "<< sumOfSquares << endl; //9
}
why does it increment i by one
Array indexes run from 0 to N-1, where N is the number of elements in the array.
i++ increments the value of i by 1 (equivalent to i = i + 1;). Incrementing i in the for loop is a construct for accessing each element of the array a (in order):
for (int i = 0; i < 10; i++)
{
a[i] = 2; /* just example */
}
is equivalent to:
a[0] = 2;
a[1] = 2;
...
a[9] = 2;
As others have commented, get a C++ book (see this SO question for a list of C++ books).
#include <iostream>
using namespace std;
main()
{
//declare space in memory for 10 numbers to be stored sequentially
//this is like having ten variables, a1, a2, a3, a4 but rather than having
//hardcoded names, you can say a[4] or rather i=4, a[i], to get variable a4.
int a[10];
int sumOfSquares = 0 ; //space for a number to be stored called sumOfSquares
int i =0; //space for a number to be stored called i
cout << "Please enter the ten numbers one by one " << endl; //print msg to screen
for (i = 0 ; i < 10 ; i++) //make i = 0; while i < 10 run this code! increase i by 1 each time
{
//a stores 10 numbers. put the number the user entered in space
//a[0] the first time, a[1] the second time, a[2] the third time etc etc.
cin >> a [i];
}
//run this code 10 times, with i=0 the first time, i=1 the second time,
// i=3 the third time etc etc.
for (i = 0 ; i < 10 ; i++)
{
//get the number at a[0] multiple it by the number at a[0]
//add it to value already in sumOfSquares so this number goes up and up and up.
//the second time through the loop get a[1] and multiply it by a[1].
sumOfSquares = sumOfSquares + a[i]*a[i];
}
//print answer to screen
cout << "The sum of squares is "<< sumOfSquares << endl; //9
}
Related
I want a function that works.
I believe my logic is correct, thus my (vector out of range error) must be coming from the lack of familiarity and using the code correctly.
I do know that there is long code out there for this fairly simple algorithm.
Please help if you can.
Basically, I take the length as the "moving" window as it loops through j to the end of the size of the vector. This vector is filled with stock prices.
If the length equaled 2 for a 2 day moving average for numbers 1 2 3 4. I should be able to output 1.5, 2.5, and 3.5. However, I get an out of range error.
The logic is shown in the code. If an expert could help me with this simple moving average function that I am trying to create that would be great! Thanks.
void Analysis::SMA()
{
double length;
cout << "Enter number days for your Simple Moving Average:" << endl;
cin >> length;
double sum = 0;
double a;
while (length >= 2){
vector<double>::iterator it;
for (int j = 0; j < close.size(); j++){
sum = vector1[length + j - 1] + vector1[length + j - 2];
a = sum / length;
vector2.push_back(a);
vector<double>::iterator g;
for (g = vector2.begin(); g != vector2.end(); ++g){
cout << "Your SMA: " << *g;
}
}
}
}
You don't need 3 loops to calculate a moving average over an array of data, you only need 1. You iterate over the array and keep track of the sum of the last n items, and then just adjust it for each new value, adding one value and removing one each time.
For example suppose you have a data set:
4 8 1 6 9
and you want to calculate a moving average with a window size of 3, then you keep a running total like this:
iteration add subtract running-total output average
0 4 - 4 - (not enough values yet)
1 8 - 12 -
2 1 - 13 13 / 3
3 6 4 15 15 / 3
4 9 8 16 16 / 3
Notice that we add each time, we start subtracting at iteration 3 (for a window size of 3) and start outputting the average at iteration 2 (window size minus 1).
So the code will be something like this:
double runningTotal = 0.0;
int windowSize = 3;
for(int i = 0; i < length; i++)
{
runningTotal += array[i]; // add
if(i >= windowSize)
runningTotal -= array[i - windowSize]; // subtract
if(i >= (windowSize - 1)) // output moving average
cout << "Your SMA: " << runningTotal / (double)windowSize;
}
You can adapt this to use your vector data structure.
Within your outermost while loop you never change length so your function will run forever.
Then, notice that if length is two and closes.size() is four, length + j - 1 will be 5, so my psychic debugging skills tell me your vector1 is too short and you index off the end.
This question has been answered but I thought I'd post complete code for people in the future seeking information.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<double> vector1 { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
double length;
cout << "Enter number days for your Simple Moving Average:" << endl;
cin >> length;
double sum = 0;
int cnt = 0;
for (int i = 0; i < vector1.size(); i++) {
sum += vector1[i];
cnt++;
if (cnt >= length) {
cout << "Your SMA: " << (sum / (double) length) << endl;
sum -= vector1[cnt - length];
}
}
return 0;
}
This is slightly different than the answer. A 'cnt' variable in introduced to avoid an additional if statement.
I have an assignment in which I am supposed to
1.) Read in 2 char arrays of numbers
2.) add together the arrays, performing carry addition, carrying the tens place
3.) print out the newly added array.
I am also supposed to print an error if I need to carry on the last digit of the array (overflow)
so something like 99999999999999999999 +
1 =
________________________
ERROR
That's the part I'm having trouble with.
The above outputs something like "99999999999999999:0" so I have no idea what's going wrong.
I'll post my code, but please be nice :( I know it certainly isn't the most efficient, but I'm just trying to lay things out in a way that is easy for my brain to understand right now.
And yes, I HAVE to use char arrays. I guess it's to help us understand the ascii table.
#include <iostream>
using namespace std;
void InitNumber(char[]);
int AddArrays(char first[], char second[], char combined[]);
void OutputNumber (char[]);
const int LENGTH = 20; // global variable
int main()
{
char set1[LENGTH];
char set2[LENGTH];
char sum[LENGTH];
InitNumber (set1);
InitNumber (set2);
if(AddArrays (set1, set2, sum)) {
cout << "overflow!" << endl;
}
OutputNumber(sum);
}
void InitNumber (char list[])
{
int numberOfDigits;
cout << "Please enter the number of digits in the number: ";
cin >> numberOfDigits;
cout << "Please enter the digits in the number with the LEAST significant first: ";
for (int i = 0; i < numberOfDigits; i++) {
cin >> list [i];
}
for (int l=(numberOfDigits); l < LENGTH; l++) {
list [l] = '0';
}
}
int AddArrays(char first[], char second[], char combined[])
{
for (int h = 0; h < LENGTH; h++)
combined[h]= '0';
int overflow = 0;
for (int i = 0; i < LENGTH; i++) {
int currentSum = (first[i]-'0' + second[i]-'0');
cout << "currentSum = " << currentSum << endl;
if(currentSum / 10 == 0 )
combined[i] += currentSum;
else if (currentSum/10 !=0) {
if (i == LENGTH-1 && currentSum/10 !=0){
overflow = 1;
}
else{
combined [i] += currentSum%10;
cout << "current i: " << combined[i] << endl;
combined [i+1] += currentSum/10;
cout << "current i+1: " << combined[i+1] << endl;
}
}
}
return overflow;
}
void OutputNumber(char arrayOut[])
{
for (int l=LENGTH - 1; l >= 0; l--)
cout << arrayOut[l];
}
working input
input
6
1 2 3 4 5 6
7
1 2 3 4 5 6 7
output
00000000000008308642
Not-working output
input
20
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
1
1
output
999999999999999999:0
I'm going to reproduce small parts of your inner loop where you are carrying out the addition, in order to explain why your overflow detection is broken.
for (int i = 0; i < LENGTH; i++) {
int currentSum = (first[i]-'0' + second[i]-'0');
if(currentSum / 10 == 0 )
combined[i] += currentSum;
Here you're adding the corresponding pair of digits from the two numbers you're adding, and checking (in your particular style) if they overflowed. Try to remember this part, it's important. In order to check for overflow, you're only checking the result of adding the pair of digits from the two large numbers you're adding.
else if (currentSum/10 !=0) {
This is a completely useless check. You can only get here if the division is known to produce a non-zero result. This if() can be removed completely. Now, the relevant part of your code is
combined [i] += currentSum%10;
combined [i+1] += currentSum/10;
Do you see the problem yet?
Your approach is, once overflow is detected, is to increment the next higher order digit in the result.
Unfortunately, on the next loop iteration, in order to check for carry over, you're just checking the sum of the next corresponding digit pair, from the two large numbers you're adding. The carry-over you're saving here is going to get completely ignored.
Say your numbers are two digits long max, rather than 20, and you entered the numbers 99 and 1.
On the first iteration, you'll add 9 and 1, save 0 as the first digit, and add 1 to the second digit in the sum.
On the second iteration, you'll add 9 and 0, and, given your logic above, conclude that nothing overflowed.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
My task is: in every language is n most used words. A boy after d days is leaving for Sweden. Wanting to understand Swedish, the first day he learns z words and the each following day k words more than a day before. Write a program, which would check if a boy will successfully will learn n words during d days.
Let's say that he needs to learn 100 words. He has 20 days. The first day he learned 5 words. Each following day he learned 1 words more than a day before.
In this case answer should be: yes (he will successfully will learn it during 20 days), and 11 (during 11 days he will learn 100 words).
I have a code written.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
int n, d=0, k, z;
ofstream fr("Rezults.txt");
ifstream fd("Data.txt");
fd>>n>>d>>z>>k;
int learned_words = 0;
for(int i=0; i<d; i++){
learned_words += z;
z = z+k;
}
if(n<=learned_words) {
fr<<"Yes"<<endl;
}
else
{
fr<<"No"<<endl;
}
z=z-d; d=0;
for(int m=0; m<=n; m+=z, z+=k, d++) {}
cout << "You need " << d << " days to learn " << n << " words";
fd.close();
fr<<d;
fr.close();
return 0;
}
You can simply count the loop by using the for loop in this way:
for (i=z; i<=n; i++)
{
}
cout<< i << endl;
You can simply see the variable "i"'s value right after the loop
This simple function solves the problem in the beginning of your question:
// z : the number of words learned during the first day
// k : this much more we learn after every day
// (i.e first day we learn z words, then z+k, then z+k+k etc.)
// d : this many days we have time to learn
// n: this many words we should learn
bool solve(int z, int d, int k, int n) {
int learned_words = 0;
for(int i=0; i<d; i++){
learned_words += z;
z = z+k;
}
if(n<=learned_words) {
return true;
}
return false;
}
To answer your question about loops, I think the following very simple loop would work:
int n = 100;
int z = 5;
int k = 1;
int d = 0;
for(int m=0; m<n; m+=z, z+=k, d++) {}
cout << "You need " << d << " days to learn " << n << " words";
Here the loop will get executed the minimal number of times needed to learn those n words. The variable d counts the days needed and must be declared before the loop. m counts how many words we have learned.
Despite having for loop in the title, there's no requirement for the loop in the task and no reason to actually use it here (unless you're limited to integer arithmetic).
It would be much easier to simply compute days needed to learn n words (it's simple quadratic equation) and compare it with d.
Number of words (y) learnt during first x days is:
y = z * x + k * x * (x-1)/2. So just solve this equation for y = n.
I'd do something like: (variables a and b are coefficients of the quadratic equation).
const double a = k/2.0;
const double b = z-k/2.0;
const double days_needed = -b + ::sqrt(b*b + 4 * a * n)/(2.0 * a);
std::cout << (days_needed <= d ?"yes":"no") << ", you need " << ::ceil(days_needed) << "days\n";
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm working on a C++ program that determines and prints the prime numbers between 3 and an integer 'x' the user inputs. I'm assuming that I need a double nested loop for this, one to iterate from 3 to x and the other to check if the number is prime. I think it needs to do something like go from 2 to x-1? I'm just really not sure how to do this syntax-wise. Thanks for any help! :)
EDIT:
This is what I have:
#include <iostream>
#include <cmath>
using std::cout;
using std::endl;
using std::cin;
int main(){
int x;
int i;
int j;
cout << "Please enter an integer 'x' greater than 3: " << endl;
cin >> x;
if (x <= 3){
cout << "Please enter new value 'x' greater than 3: " << endl;
cin >> x;
}
for(int i=3; i<=x; i++){
for(j=2; j<i; j++){
if(i%j == 0)
break;
else if(i == j+1);
cout << i << endl;
}
}
return 0;
}
And I when I enter 10 as 'x' I get the output:
3
5
5
5
7
7
7
7
7
9
Can anyone tell me how to fix this?
Provided your X is small enough, you can use the Sieve of Eratosthenes to do it more efficiently. This is ideal for the "primes up to X" case since it maintains a memory of previously discarded primes. It does so by keeping a set of flags for each candidate number, all initially set to true (except for 1, of course).
Then you take the first true value (2), output that as a prime, and then set the flags for all multiples of that to false.
Then carry on with:
3;
5 (since 4 was a multiple of 2);
7 (since 6 was a multiple of 2 and 3);
11 (since 8 and 10 were multiples of 2 and 9 was a multiple of 3);
13 (since 12 was a multiple of 2);
17 (since 14 and 16 were multiples of 2 and 15 was a multiple of 3 and 5);
and so on.
Pseudo-code would be similar to:
def showPrimesUpTo (num):
// create array of all true values
array isPrime[2..num] = true
// start with 2 and go until finished
currNum = 2
while currNum <= num:
// if prime, output it
if isPrime[currNum]:
output currNum
// also flag all multiples as nonprime
clearNum = currNum * 2
while clearNum <= num:
isprime[clearNum] = false
clearNum = clearNum + currNum
// advance to next candidate
currNum = currNum + 1
Otherwise, you can do trial division as per your suggestion. The basic idea is to check each number from 2 up to the square root of your target number to see if it's a multiple. In pseudo-code, that would be something like:
def isPrime (num):
// val is the value to check for factor
val = 2
// only need to check so far
while val * val <= num:
// check if an exact multiple
if int (num / val) * val == num:
return false
// no, carry on
val = val + 1
// if no factors found, it is a prime
return true
The reason you only need to check up to the square root is because, if you find a factor above there, you would have already found the corresponding factor below the square root.
For example, 3 x 17 is 51. If you're checking the numbers from 2 through 50 to see if 51 is prime, you'll find 3 first, meaning you never need to check 17.
int main (char argv)
{
int tempNum = atoi(argv);
for (int i=3; i<=tempNum; i++)
for (int j=2; j*j<=i; j++)
{
if (i % j == 0)
break;
else if (j+1 > sqrt(i)) {
cout << i << " ";
}
}
return 0;
}
Printing prime numbers from 1 through 100
Basically this, but modified
I find this one pretty fast and efficient
int main(){
for(int i=3; i<=X; i++)
if(IsPrime(i)){
cout<<i<<endl;
}
}
bool IsPrime(int num){
/* use commented part if want from 2
if(num<=1)
return false;
if(num==2)
return true;
*/
if(num%2==0)
return false;
int sRoot = sqrt(num*1.0);
for(int i=3; i<=sRoot; i+=2)
{
if(num%i==0)
return false;
}
return true;
}
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 11 years ago.
#include <iostream>
using namespace std;
void main()
{
int i = 0;
while (i < 1000)
{
int TEMP = i * 2;
cout << i << endl;
TEMP = i;
i = i +1;
// ???
}
return;
}
I'm so confused?? :(
The Fibonacci sequence F is F(n) = F(n - 1) + F(n - 2), F(0) = 0, F(1) = 1.
Here's some psuedo-code:
Start Counter1 at 0
Start Counter2 at 1.
For i = 0 to 1000
New value = Counter1 + Counter2
Print new value
Counter2 = Counter1
Counter1 = New Value
End For
This doesn't print out 0 or 1; it starts at F(2). You can easily fix this by just printing out 0 and 1 first. Also, this code prints the first 1000 numbers. If you change this to: While Counter1 < 1000, you'll stop when you reach or pass 1000.
It's up to you to implement it, and make sure you understand how it works.
First you should check that you understand the definition of the Fibonacci numbers.
By definition, the first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.
You need two variables to remember the state, not just one as you were trying to do. And you don't multiply by two, you just add the two variables.
#include <iostream>
using namespace std;
int main()
{
int i = 0;
int j = 1;
while (i < 1000)
{
/* Print a number. */
cout << i << endl;
/* Set j to the sum of i and j, and i to the old value of j. */
int TEMP = j;
j += i;
i = TEMP;
}
return 0;
}
If you would like just a hint, Google "recursion".
If you would like the answer, Google "recursion fibonacci C++", but PLEASE try to work it out with the hint above :) It's worth it.