Brand new programmer, so green behind the ears that I could be a frog. The intent of this program is to use a for loop (not a simple formula) to add all integers up to a user designated value. It executes all code up to the for loop perfectly, however the for loop does not seem to run. Here is the code in question:
#include "stdafx.h"
#include <iostream>
int main(int num=0)
{
int sum = 0;
std::cout << "This program will sum all integers up to a given value";
std::cout << std::endl << std::endl;
std::cout << "Please enter a number "<<std::endl;
std::cin >> num;
std::cout << std::endl << "You've chosen the number " << num<<std::endl;
for (int i = 1; i <= num; ++i)
sum += i;
return (sum);
std::cout << "The sum of all numbers up to " << num << " is " << sum;
}
Any help is appreciated!
When it meets return for the first time, the program will be end.
Please put the return at the end of main function.
One more thing, shouldn't use parameter num in main function.
Write a separately function sum_all_integers and then call it in main function.
Good news: your code works! The issue is that when return (sum); is called, the function is exited, and the line that would print out your answer is not executed.
I would also recommend adding the using namespace std; line after your includes, so that you don't end up with so much std:: pollution. Also main should not take any arguments, so put that int num=0 line inside the main block.
Oh, you should also be aware of your return line indentation.
In this section
for (int i = 1; i <= num; ++i)
sum += i;
return (sum);
Your program will exit.
This boils down to what other answers have mentioned: return from main means exiting the program. Keep in mind that is is true even from within a loop like while or for - doing so is how one might design a search function which exits as soon as it has a result, for example.
To exit a for loop prematurely, use break. To continue to the next iteration and skip further code in the loop, use continue.
Also note that the indentation of return is misleading - it will be executed after the for loop, since the lack of brackets ({}) will make for only loop through the next line, which is sum += i; Keep in mind that C++ is not a whitespace sensitive language, so indentation means nothing to the logic (I like to abuse this in large blocks of similar code by tab-aligning). This is also a good example of why it is common practice to use brackets even when not strictly necessary. EDIT See also Apple's infamous "goto fail" bug.
You return the sum right after the loop:
for (int i = 1; i <= num; ++i)
sum += i;
return (sum);
This means, you sum up the numbers and then exit the program before you print the result.
Related
I am a c++ beginner and I hope you could help me with some of the fun I am having, you all know what I actually mean.
Here is a snippet of c++ code that I will follow with a brief explanation my problem:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main() {
// this first for loop doesn't affect the execution of the first cout statement.
for (int i = 51; i >= 0; i--) {
srand(time(NULL));
int j = rand();
cout << j << endl;
};
cout << "first cout outside the first for loop" << endl; // executes fine
// this second for loop affects the execution of the following cout statement.
for (int i = 51; i >= 0; i--) {
srand(time(NULL));
int j = rand() % i; //by just adding % i, the next cout statement doesn't execute!
cout << j << endl;
};
cout << "second cout outside the second for loop" << endl; // doesn't execute
}
All right, so, I hope the issue is obvious. To put it in words, why adding the modulus i to the rand() in the second for loop prevents the second cout statement from execution? It took me a whole lot of time to pinpoint what seems to be a big problem in my entire class implementation to this single line. Any feedback/advise/explanation is greatly appreciated.
Cheers.
Programs that execute undefined behavior can have any apparent behavior, including code "in the past" not executing.
You do %0 at the end of your loop. This makes earlier print statements not output. That is acceptable behavior as far as C++ is concerned.
Don't do undefined behavior.
It seems like I always come here to ask silly questions, but here it goes. As of right now I am in my first compsci course and we are learning c++. I've had an extremely basic introduction to c before, so I had thought I'd go above and beyond my current assignment. Now I was doing this just to showboat, I felt like if I didn't practice my previous concepts they would eventually fade. Anyways, on to the problem! I was supposed to write some code that allowed the user to input their initials, and a series of exams. Now this was supposed to accomplish three things: average the exams, print out the entered exams, and print out their initials. Well, what was a simple assignment, got turned into a huge mess by yours truly.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
string uInitials;
float avgExam = 0, tExam = 0;
int aExams[10] = {'0'};
int i, nExam = 0, cExam;
cout << "Enter your three initials!";
cin >> uInitials;
do
{
cout << "Enter your exam(s) to be averaged. Enter 0 when complete!\n";
cin >> cExam;
aExams[nExam] = cExam; //I used this before nExam was incremented, in order to get nExam while it was '0' That way the first exam score would be properly saved in the first space
nExam++;
tExam += cExam; //This is just to add all the exams up to later calculate the average
}
while(cExam != 0);
avgExam = tExam/(nExam - 1); //subtracted '1' from nExams to remove the sentinel value from calculations.
cout << "The average for initials: " << uInitials << " is: " << avgExam << endl;
cout << "This average was obtained using the following scores that were entered: \n";
for(i = 0; i < (nExam+1); i++)
{
cout << aExams[i] << endl; //Used a for loop to prevent redundancy
}
return 0;
}
The previous is my code, and the problem is that I'm getting output errors where it adds two '0's when I print out the list of entered exams. Also I feel like I made the whole do{}while() loop one huge clunky mess, so I'd like to refine that as well. If anyone could assist this poor, ignorant, beginner I would greatly appreciate it. Thank you for your time!
Some advice that i can give is for example in the 5th line there is no need
to put the 0 between ' ' and not even need to use the assign = operator.
You can initialize the array like this:
int aExams[10]{0};
Which will initialize all elements to 0,but can't be used for other value.
For example you won't have all the elements with value 1 if you write
int aExams[10]{1};
If your intention to initialize all elements in an array is with value other than 0 you can use fill_n(); function.
fill_n(aExams, 10, 1);
The first argument is the name of the array, the second is up-to which element you want to be initialized with the third argument, and the third is the value you want all elements to have.
Do not leave uninitialized variables like in line 6 with cExam and i variables. Initialize it like cExam=0; (copy-assign initialization) or cExam(0); (direct initialization). The latter calls the constructor for int built-in type.
A negative i see in your do-while loop is that you do not make sure that the user will enter under 10 exams,bad things will happen if the user tries to input 15 exams in an array that can hold only 10.
Just change the while to something more like this:
while( cExam != 0 && (nExam<10) );
You can also write the first two lines of the do-while loop outside the loop.
It is needed only once to tell the user that to stop the loop he/she needs to enter 0. There is no need to tell them this on every iteration plus that you will have a good performance benefit if you put those two lines outside the loop.
Look here how i would write the code and ask if you have any questions.
http://pastebin.com/3BFzrk5C
The problem where it prints out two 0's at the end of your code is a result of the way you wrote your for loop.
Instead of:
for(i = 0; i < (nExam+1); i++)
{
cout << aExams[i] << endl; //Used a for loop to prevent redundancy
}
Use:
for (i = 1; i < (nExam); i++)
{
cout << aExams[i - 1] << endl; //Used a for loop to prevent redundancy
}
This question already has answers here:
'do...while' vs. 'while'
(31 answers)
Closed 8 years ago.
I would like someone to explain the difference between a while and a do while in C++
I just started learning C++ and with this code I seem to get the same output:
int number =0;
while (number<10)
{
cout << number << endl;
number++
}
and this code:
int number=0;
do
{
cout << number << endl;
number++
} while (number<10);
The output is both the same in these both calculations. So there seem to be no difference.
I tried to look for other examples but they looked way to difficult to understand since it contained mathemetical stuff and other things which I haven't quite learned yet. Also my book gives a sort of psychedelic answer to my question.
Is there an easier example to show the difference between these 2 loops?
I was quite curious
The while loop first evaluates number < 10 and then executes the body, until number < 10 is false.
The do-while loop, executes the body, and then evaluates number < 10, until number < 10 is false.
For example, this prints nothing:
int i = 11;
while( i < 10 )
{
std::cout << i << std::endl;
i++;
}
But this prints 11:
int j = 11;
do
{
std::cout << j << std::endl;
j++;
}
while( j < 10 );
The while loop is an entry control loop, i.e. it first checks the condition in the while(condition){ ...body... } and then executes the body of the loop and keep looping and repeating the procedure until the condition is false.
The do while loop is an exit control loop, i.e. it checks the condition in the do{...body...}while(condition) after the body of the loop has been executed (the body in the do while loop will always be executed at least once) and then loops through the body again until the condition is found to be false.
Hope this helps :)
For Example:
In case of while loop nothing gets printed in this situation as 1 is not less than 1, condition fails and loop exits
int n=1;
while(n<1)
cout << "This does not get printed" << endl;
Whereas in case of do while the statement gets printed as it doesn't know anything about the condition right now until it executes the body atleast once and then it stop because condition fails.
int n=1;
do
cout << "This one gets printed" << endl;
while(n<1);
If you consider using a different starting value you can more clearly see the difference:
int number = 10;
while (number<10)
{
cout << number << endl;
number++
}
// no output
In the first example the condition immeditately fails, so the loop won't execute. However, because the condition isn't tested until after the loop code in the 2nd example, you'll get a single iteration.
int number = 10;
do
{
cout << number << endl;
number++
}
while (number<10);
// output: 10
The while loop will only execute of the conditions are met. Whereas the do while loop will execute the first time without verifying the conditions, not until after initial execution.
I'm not sure how to title my question, but here goes. I am testing some features, and I have hit a snag.
What I want to know is how can I set up a "for" or "if" statement to only put values in an array that meet a criteria? For example, find every divisor for a number, but only put factors in an array.
Any help would be loved, source code can be provided if needed :). Yes, I am new, so be gentle!
#include <iostream>
using namespace std;
int main(){
int n;
int counter = 1;
cout << "What number would you like to use? ";
cin >> n;
int DiviArray[n];
for (int k=0,j=1;k<n;k++,j++)
{
DiviArray[k] = n-k;
}
int k = 3;
int factn[n];
cout << "Factors of " << n << ": " << endl;
for (int i=0, j=1;i<n;i++,j++)
{
factn[i] = n/DiviArray[i];
if(factn[i]*DiviArray[i]==n)
{
cout << counter << ". " << factn[i] << " x " << DiviArray[i] << endl;
counter++;
}
}
return 0;
}
EDIT: Decided to go with vectors, not sure if I can get it to work, but thanks for the feedback guys :)
Since you don't know in advance how many values will meet the condition, you should use a std::vector.
As a benefit, it keeps track of how many elements you've already added, so push_back will always use the next available index.
This also fixes
cin >> n;
int DiviArray[n];
which isn't legal C++.
If you only want to put the values into the array that match the condition, then you should only put a number into the array when the condition is matched. To do that, the statement that puts a number into the array has to be inside the if-block for the condition. I hope I don't need to explain why :)
This is the only time in your program where you actually do want two indices: one that is incremented every time through the loop (to count how many times to run the process), and one that is incremented only when you put a number in the array (to figure out where the next number goes). Everywhere else, you've created a completely useless j variable (the uselessness should be apparent from the fact that there is no code that actually uses the value, only code to set it).
#include <iostream>
using namespace std;
int main (void) {
cout << " 1\t2\t3\t4\t5\t6\t7\t8\t9" << endl << "" << endl;
for (int c = 1; c < 10; c++) {
cout << c << "| ";
for (int i = 1; i < 10; i++) {
cout << i * c << '\t';
}
cout << endl;
}
return 0;
}
Hey so this code produces a times table...I found it on Google Code's C++ class online...I'm confused about why "i" in the second for loop resets to 1 every time you go through that loop...or is it being declared again in the first parameter?
Thanks in advance!
It "reverts" to 1 because you explicitly set it to 1 as the start condition of the loop...
The "i" name does not exist outside this loop, so each time this loop is run (for each iteration of 'c'), then "i" is a new variable, set to a start of 1.
As TZHX has written. FOR statements usually have three clauses that are in the parantheses (technically they always have three but you don't have to specify them), and a statement that is repeated (often a statement block).
Of those three clauses, the first is an initializer, the second controls the looping, and the third is the increment. So as TZHX says, i is reset to 1 at the beginning due to the initializer clause. This will keep repeating while i<10 (the second clause), and i is incremented by 1 with each iteration (the third clause).