I have to create a program using a for loop that will count by 3 from the given number from the user 20 times. So far this is what i have.
#include <iostream>
using namespace std;
int main(){
int num, newNum, add;
cout << "Enter a number: ";
cin >> num;
for(int count = 0; count < 20; count++){
for(int sum = 0; sum <= count; sum++){
newNum = num * (count +1);
}
cout << num << " ";
}
}
I have no idea where to go from here. I know that i would have to put the number given into a variable like i do with num and i know i would somehow have to store the new number in another variable like i do with newNum. Any help would be appreciated! Also this is what the output should look like in case i did not explain it good enough.
Enter a number: 3
3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60.
And bonus points if you can have the last number end with a period instead of a comma :)
This should work:
int main(){
int num, currentNum, add, newNum;
std::cout << "Enter a number: ";
std::cin >> num;
std::cout << num
for(int count = 0; count < 20; count++){
num += 3;
std::cout << ", " << num;
}
std::cout << " ." << std::endl;
}
Also try to not use using namespace std. It clutters the namespace.
You can add 3 to the number either inside the loop's third statement (you can also have multiple conditions etc.)
for(int count = 0; count <= 20; count++, num+=3){
// ...
}
or inside the loop's code block
for(int count = 0; count <= 20; count++){
num += 3;
}
As for the comma you just need to add it to the output:
cout << num << ", ";
Since you want a dot at the end you need to handle this in an if-else case
if (count < 20)
cout << num << ", ";
else
cout << num << ".";
or a ternary operator:
cout << num << (num < 20) ? ", " : ".";
Bonus points: don't expose the complete namespace (here: std). While in such a small example it's not an issue it may lead to hard to detect bugs later on if you happen to use one or multiple namespaces that offer the same functionality.
OK, we have so far an answer explaining pretty well and another one optimising the if inside the loop away. We still can optimise away one addition, if you count up the num variable directly:
for(auto end = num + 57; num < end; num += 3)
// ^ still one number less, last one follows the loop!
{
std::cout << num << ", ";
}
std::cout << num << '.' << std::endl;
// ^ ^ not much difference, but just outputting a single character
// is more efficient, no need to iterate to find the
// trailing null character...
std::endl not only adds a newline, but flushes the stream immediately (i. e. the so far possibly buffered output is forced to be printed to console). This is especially useful if there's more output to follow, but possibly quite a while later (without flushing, user might see incomplete last line). Admitted, in given case not necessary, as std::cout's destructor will flush anyway, so you could go, too, with the slightly simpler std::cout << num << ".\n"...
Without using the extra variables.
#include
using namespace std;
int main(){
int num, currentNum, add, newNum;
cout << "Enter a nummber: ";
cin >> num;
for(int count = 0; count <= 20; count++){
cout << (num + count * 3);
if(count == 20)cout<<".\n";
else cout<<", ";
}
}
More general solution would be:
#include <iostream>
using namespace std;
int main(){
int num, currentNum, add;
cout << "Enter a nummber: ";
cin >> num;
add = 3;
currentNum = num;
for(int count = 0; count <= 20; count++){
cout << (currentNum); //Print current number
currentNum = currentNum + add; // increase the number
if(count == 20)cout<<".\n"; //if the last one print dot
else cout<<", "; //else place comma
}
}
Related
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.
I wrote a code to get the number of sequences occurring in the user input sequence.
This is my code. It excludes the subsequence which I wish to be tested.
I need to consider 12,23,34,123,234,1234 as sequences.
Overlapping of sequences should not be considered (12 in 123 should not be considered).
For e.g. constant number 1234
User given number 124312341211423
Output : No.of Sequence found 4
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
string num1;
string seq;
cout << "Enter constant number: ";
cin >> num1;
cout << "Enter the sequence: ";
cin >> seq;
int count=0;
for (int t=0; t<=num1.size()-2; t++)
{
string num = num1;
for (int k = num1.size(); k>=2-t ;k--)
{
cout << num <<"\n";
if (t==2 && k<=2)
break;
//num=num.substr(t,t+k-1);
for (int j = 1; seq.find(num) != string::npos; j++)
{
seq = seq.substr(0,seq.find(num)) + " " + seq.substr(seq.find(num)+num.size());
count = count + 1;
}
num = num.substr(t,t+k-1);
}
cout<< seq << "\n";
}
cout << "No. of sequences found: " << count << "\n";
return 0;
}
Hi I tried running your code and I got it outputting 5 sequences found. I'm assuming your request is to figure out why it's not 4.
I'll make a couple recommendations:
The logic of your for-loops and forming num should be adjusted to test all substrings of num1 such that each substring is at least 2 characters in length.
Change your most-interior for-loop into a while loop, because your iterator j really isn't doing anything.
Call string::find() once per iteration of your most-interior loop. String::find() is expensive and you call it three times without changing the arguments.
Pull the declaration of num out of the for-loop so it's only declared once.
Here is the result of these recommendations in effect:
You'll notice I added a variable numStart to save the location of the beginning of num in seq, thus allowing recommendation #3 to be done.
I also moved cout << seq << "\n" into the most-interior loop so you can see the state of seq every time a sequence is found.
int main() {
string num1;
string num;
string seq;
cout << "Enter constant number: ";
cin >> num1;
cout << "Enter the sequence: ";
cin >> seq;
int count=0;
for (int t=0; t<=num1.size(); t++) {
for (int k = num1.size(); k>t+1; k--) {
num = num1.substr(t, k-t);
size_t numStart = seq.find(num);
while (numStart != string::npos) {
seq = seq.substr(0, numStart) + " " + seq.substr(numStart + num.size());
count++;
numStart = seq.find(num);
cout << seq << "\n";
}
}
}
cout << "No. of sequences found: " << count << "\n";
return 0;
}
I hope this helps!
I've been having trouble with a problem from my C++ book. It wasn't required to do, but I want to get it to work:
Sum of numbers
Write a program that asks the users for a positive integer value and that uses a loop to validate the input.* The program should then use a second loop to compute the sum of all the integers from 1 up to the number entered. For example, if the user enters 50, the loop will find the sum of 1, 2, 3, 4, ... 50.
*I'm not asking for this first loop, just the second. But if you feel like coding it go ahead.
It's pretty simple to write a program that decreases a number until it reaches one:
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter a number: ";
cin >> number;
while(number >= 1)
{
cout << number << " ";
number--;
}
system("pause"); //I usually go with cin.get() but my current
//compiler doesn't handle it
return 0;
}
But if you to add "number - 1" to a number, the number becomes bigger and now number - 1 will increase from thereon. For example, 7 + 6 = 13, 13 + 12 = 25, 25 + 24 = 49, etc. Here's the program I am trying to adapt to make work:
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter a number: ";
cin >> number;
for(count = 1; count <= number; count++)
{
number += number - 1;
}
cout << "The sum is" << number << endl;
system("pause"); //
return 0;
}
This is an infinite loop, unfortunately.
Any ideas to how to adapt this program so it satisfies the question? Or links to source code that's already done it before, etc.
EDIT:
So this might be another issue entirely, but my code isn't compiling:
#include <iostream>
using namespace std;
int main()
{
int number, sum = 0;
cout << "Enter a number: ";
cin >> number;
for(count = 1; count <= number; count++)
{
number--;
sum += number;
}
cout << "The sum is" << sum << endl;
system("pause"); //
return 0;
}
EDIT 2: I just got rid of the for loop and changed it to "while(number >= 1)"
Something like this ?
int sum = number;
while (number-- > 0) {
sum += number;
}
I find a for loop neater, so I'll post an example for variety.
int n = Max Number
int sum = 0;
for(int i = 1; i <= n; i++) {
sum += i;
}
And for your compiling problem, unless I'm reading it wrong, you shouldn't be decrementing the number; it's defining what the max number is. Each loop you're incrementing the count, decrementing the number, then comparing them. I can't imagine that will give you anything meaningful. Erase the number--;, and it should work.
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
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.