I'd like to request some help on my HW. I think I'm really close to figuring this out. Our CompSci class is currently shifting from learning Python to (introductory) C++. Since the two are vaguely similar, we've been advised, since we're beginners, to code the problem in Python (which we're very familiar with) and to translate it into C++ using the basics we just learned. The problem to solve is a simple "add the consecutive integers from 1 to that number, given a positive integer input." So an example would be:
>>Enter a positive integer: 10
>>1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
The Python code (this was successful) that I'm attempting to translate into C++ is:
num = int(raw_input("Enter a positive integer: "))
sum = 0
for i in range(1, num):
sum += i
print i, "+",
print num, "=", sum+num
And my unsuccessful C++ code:
#include <iostream>
using namespace std;
int main()
{
int num;
int sum;
int i;
sum = 0;
cout << "Please enter a positive integer: " << endl;
cin >> num;
for (i=0; 1 <= num; i++)
{
sum = sum + i;
cout << i << "+" << endl;
}
cout << num << "=" << sum + num << endl;
return 0;
}
But the output is simply an infinite, non-ending addition sequence from 0 to infinity, going top to bottom. Even worse is that it did not print in a straight line like I want it. As you can see, I quite literally tried to translate it word-for-word; I thought that'd be foolproof. Something must be wrong with my for loop. Since C++ doesn't have a class of its own for "range" like Python does, I thought the middle condition statement ("1 <= num;") would act as the range. Why didn't my "=" sign print out? And I don't understand why it won't terminate when it reaches "num." Think you can help? I thank you in advance for the replies.
Fixed code:
#include <iostream>
using namespace std;
int main()
{
int num;
int sum;
int i;
sum = 0;
cout << "Please enter a positive integer: " << endl;
cin >> num;
// Here you had 1 <= num which was always true for positive num
// and it did not depend on value of i.
for (i = 1; i < num; ++i)
{
sum = sum + i;
cout << i << "+"; // Here you had endl which produced newline characters.
}
cout << num << "=" << sum + num << endl;-
return 0;
}
This:
for (i=0; 1 <= num; i++)
should be:
for (i=0; i <= num; i++)
try this.
#include <iostream>
using namespace std;
int main()
{
int num;
int sum;
int i;
sum = 0;
cout << "Please enter a positive integer: ";
cin >> num;
for (i=0; i < num; i++)
{
sum = sum + i;
cout << i << " + ";
}
cout <<num << " = " << sum+num << endl;
return 0;
}
I don't really know Python, but the code
for i in range(1, num):
looks really similar to
for (int i=1; i <= num; ++i)
or is it possibly
for (int i=1; i != num; ++i)
which looks more like C++?
loop in c++ are most basic than python, the for loop is more simpler, it is based on the three expression: initializer expression, the loop test expression, and the counting expression. In particular what is wrong in your code is the test expression. Remember that the loop is executed if the test expression is true. You need to loop if the condition i<num is true. Your loop is never ending because num is always >= 1, or as you wrote 1 <= num always.
To print everythig on a line don't use endl
Related
So in this program, I have to do multiplication in a very tedious fashion and for the second loop, the for loop, I'm multiplying one variable by 2 and the output is the product of that multiplication I am wondering how I could go about taking those output values and adding them together. The code and output of the code are below
#include <iostream>
using namespace std;
int main()
{
cout << "Time to do some Martian Math" << endl;
// variables for math
int righthandnum;
int lefthandnum;
cout << "Please enter two numbers" << endl;
// get values to do the martian math
cin >> lefthandnum;
cin >> righthandnum;
//while loop for right hand number
int i = 0;
while (righthandnum >= 1 ) {
//cout << righthandnum << endl;
//if to find out if any values are odd
if (righthandnum % 2 == 0) {
i -= 1;
}
righthandnum = righthandnum / 2;
i++;
}
int num;
for (num = 1; num <= i; num++) {
lefthandnum = lefthandnum * 2;
//lefthandnum + lefthandnum;
cout << lefthandnum << endl;
}
return 0;
}
The output is
Time to do some Martian Math
Please enter two numbers
50
30
100
200
400
800
Thank you so much for any help!
I don't know if this is what you are looking for but maybe a stack or an array might help you
with the array (the easy way), you make a list of N size for the data as an example:
int values[10];
for(int i = 0; i < 10; i++){
std::cin>>values[i];
}
for(int i = 0; i < 10; i++){
std::cout<<"List element "<<i<<": "<<values[i]<<std::endl;
}
while the stack as I've used it it's a bit more complex and requires pointers.
this is a video (sorry it's in Spanish): https://youtu.be/joAw2jWgZqA
C++ newbie here, basically I am trying to print out a list of random characters based off user input. I know my error involves the "m <= num" statement, but not sure how to go about fixing that. Or am I going about this completely wrong? Explanations are greatly appreciated!
Note My logic is that 'm' is the list of characters so for 'num' I am trying to print out a list of characters based on the value of 'num'. For example if the user selects 2 for list and 5 for elements I would want the output to be....
list 1: "wtwef"
list 2: "wopoe"
#include <iostream>
#include <string>
#include <vector>
#include <list>
using namespace std;
int main() {
srand (time(NULL));
int L;
string alpha = "abcdefghijklmnopqrstuvwxyz";
list<string> m;
cout << "Give the number of lists: ";
cin >> L;
for (int i = 1; i <= L; i++){
cout << "Give the number of elements for list " << L << " : "<< endl;
int num; cin >> num;
for (int k = 0; m <= num; k++){
cout << alpha[rand() %100] << " " << endl;
m.push_back(alpha[rand() %100]);
}
cout << "Give a word: " << endl;
cin >> s;
}
The issue with the expression "m <= num" is because m is of type std::list while num is of type int. It doesn't make sense to compare a list with an int, which is the real world equivalent of comparing a shopping list with 4, it just doesn't mean anything. You may have intended "k <= num".
The line cin >> s is also an error, s isn't defined.
You also have a line m.push_back(alpha[rand() % 100]); that will be an error, m has a type of string while the using the [] operator on alpha will return a character, see code below for solution.
You use the modulus operator in two places, where you mod by 100. If you want a character at a random index you should, in this case, do alpha.substr((double) rand() / RAND_MAX * alpha.length(), 1). Note that RAND_MAX is a constant that should be predefined, you shouldn't need to set it. I have a feeling what you're trying to accomplish in the inner loop looks like:
string randomCharacter = alpha.substr((double) rand() / RAND_MAX * alpha.length(), 1)
cout << randomCharacter << " " << endl;
m.push_back(randomCharacter);
You are also missing a left brace in the code somewhere (may be due to copy-paste) which would be another reason it wouldn't compile.
If what you want is to be able to type in the terminal how many sequences of random characters followed by how many characters are in each sequence, you would want to re-write the inner loop to look like:
string randomCharacters = "";
for (int k = 0; k <= num; k++){
string randomLetter = alpha.substr((double) rand() / RAND_MAX * alpha.length(), 1);
cout << randomLetter << " " << endl;
randomCharacters += randomLetter;
}
m.push_back(randomCharacters);
This will fill the list with strings filled with random characters from array alpha, which you can use later. You can remove the cout if you don't want to see all the characters printed to the terminal as they are randomly chosen.
After your edit to the question:
The solution should look like:
srand(time(NULL));
int L;
string alpha = "abcdefghijklmnopqrstuvwxyz";
vector<string> m;
cout << "Give the number of lists: ";
cin >> L;
cout << "Give the number of elements for the lists: ";
int num;
cin >> num;
cout << endl;
for (int i = 1; i <= L; i++){
string randomCharacters = "";
for (int k = 0; k < num; k++){
string randomLetter = alpha.substr((double) rand() / RAND_MAX * alpha.length(), 1);
randomCharacters += randomLetter;
}
m.push_back(randomCharacters);
}
for(int i = 0; i < m.size(); i++)
{
cout << "list" << (i+1)<< ": " << m[i] << endl;
}
Note, this solution switched list for vector as it's simpler in this case.
Consider a program that asks the user for an integer value greater than 10, say 15. The program should then calculate the sum of all positive values up to 15 and now I need to "show the
current sum after adding each number".
For the first part I made everything like this:
#include <iostream>
using namespace std;
int main()
{
int num = 0;
int sum = 0;
cout << " Please enter how many number you'd like to sum up\n";
cin >> num;
while (num <= 10)
{
cout << "Please enter an integer which is more than 10";
cin >> num;
}
for ( int i = 1; i <= num; i++)
{
sum += i;
}
cout << "The total sum is : " << sum;
But now I dont know what should i do?
It should look like this in the end.
You can do this by outputting the values used in the calculation, along with the 'running' total, inside your summation loop:
for (int i = 1; i <= num; i++)
{
cout << sum << " + " << i << " = " << sum + i << "\n";
sum += i;
}
Feel free to ask for further clarification and/or explanation.
I can get the sum every time the user inputs an integer until either a negative number or non-integer is inputted. Problem is my sum calculations are off. I.E user putting 1000; sum outputs 1111, then user inputs 2000, it adds up to 3333. Just any advice is appreciated. I'll still experiment around with my coding.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int j , i = 0, k = 0,number;
double sum = 0;
cout << "Enter Positive integer number: ";
while(cin >> number)
{
cout << endl;
if( number < 0)//test if the number is negative
{
cout << "Ending program since user has input a negative number" <<endl;
break;
}
int temp = number;
int p = 1;
while( temp > 0) //counting number of digits
{
sum = sum+temp; //Sum attempt.
temp /= 10;
p *= 10;
i++;
}
cout << sum << endl;
j = i % 3;
p /= 10;
while( i > 0 )//display integer number with 1000 seperator
{
//this is giving me error
cout << char ((number/p) +'0');
number %= p;
p /= 10;
i--;
k++;
j--;
if ((k % 3 == 0 && i > 0)||(j == 0 && i > 2) )
{
cout <<",";
k = 0;
}
}
cout << endl << endl;
cout << "This program will exit if you input any non-integer characters\n";
cout << "Enter another integer number: ";
}
return 0;
}
It looks like you're trying to output an integer number with commas inserted at 1000 boundaries. ie: 1000000 would be displayed as 1,000,000.
This being the case, the easiest way to approach it might not be involving maths but simply to get a string representation of the int (atoi() for example) and count through that. From the back, count forward three chars, insert a comma, repeat until you run out of string.
The specifics of string handling are left as an exercise for the reader - looks like it's his homework after all. ;-)
I know this probably really simple but Im not sure what im doing wrong...
The assignment states:
For the second program for this lab, you are to have the user enter an integer value in the range of 10 to 50. You are to verify that the user enters a value in that range, and continue to prompt him until he does give you a value in that range.
After the user has successfully entered a value in that range, you are to display the sum of all the integers from 1 to the value entered.
I have this so far:
#include <iostream.h>
int main () {
int num, sum;
cout << "do-while Loop Example 2"
<< endl << endl;
do {
cout << "Enter a value from 10 to 50: ";
cin >> num;
if (num < 10 || num > 50)
cout << "Out of range; Please try again..."
<< endl;
} while (num < 10 || num > 50);
{
int i;
int sum = 0;
for (num = 1; num <= 50; num ++)
sum = sum + num;
}
cout << endl << "The sum is " << sum << endl;
return 0;
}
Im just not sure exactly what i'm doing wrong... I keep getting the wrong sum for the total...
Your loop conditions are wrong.
First, you should use a separate variable as your index (in fact you already declared one using "int i" earlier).
Second, your upper limit shouldn't 50, it's whatever the user entered.
So you want to change all "nums" in the loop to "i", and the "50" to "num".
Actually, you can simplify the for loop into:
sum = ((num+1)*num)/2;
Credits to Carl Friederich Gauss. :D
The Corrected code is
#include <iostream.h>
int main () {
int num;
cout << "do-while Loop Example 2"
<< endl << endl;
do {
cout << "Enter a value from 10 to 50: ";
cin >> num;
if (num < 10 || num > 50)
cout << "Out of range; Please try again..."
<< endl;
} while (num < 10 || num > 50);
//<----Removed the extra set of {}
int i,sum=0;//<---- Changed the declaration here
for (i= 1; i <= num; i++) //<----Change Here
sum += i;
cout << endl << "The sum is " << sum << endl;
return 0;
}
Let me make sure I understand this correctly, your assignment asks for a user input for a given number and store it in num and then display a running sum of 1 up to num?
If that's the case, inside your loop you override the user's input of num when you call num = 1. You'll just calculate the running sum of 1-50 every time.
To correct that, you need to use a different variable to keep incrementing, i.e. count or the variable i since it's already been declared. Then you should loop up from i to num as long as i <= num.
Other than that, I cannot see any problems and it should work correctly.
Note to add about a good investment:
It would definitely be worth while to see if the IDE you are developing in has a debugger you can use. Debugging is a great tool to help figure out why your code is not being executing as it is intended to.
If there is no debugger (which would surprise me) might I suggest my go-to alternative method of stepping through the for loop on a sheet of paper and compare the sum to another hand-written solution already solved, i.e. num = 5 sum = 1+2+3+4+5 = 15
Hope this helps.
The for loop should be:
for (int x = 1; x <= num; x++)
{
sum += x;
}
#include <iostream.h>
int main () {
int num, sum; // here you define (but don't initialize) one variable named sum.
[ ... ]
{ // here you start an inner scope.
int i;
int sum = 0; // here you define *another* `sum`, local to the inner scope.
for (num = 1; num <= 50; num ++)
sum = sum + num; // here you add the numbers to the *second* sum.
} // here the second sum goes out of scope.
// and here you print out the first (still un-initialized) sum.
cout << endl << "The sum is " << sum << endl;
Your upper bound is not 50, but the number you entered.
Therefore your summation is from 1 t0 inclusive of your entered number.
Say you enter 10,
logic will be.
You add all the digits from 1 to 10.