Why is this do while loop infinitely executing?
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
unsigned int base;
cout << "Base: ";
cin >> base;
for (int i = 1; i <= base; i++) {
int j = 0;
do {
cout << "#";
j++;
} while (j = i);
cout << endl;
};
system("pause");
// keep on building up until you reach 'base'
return 0;
}
I am really confused about this. This program is supposed to create a triangle like this
#
##
###
(user inputs bottom number, so in this example the base = 3)
Anybody help fix my rookie mistake?
You might wanna try while (j == i);.
j = i is a variable declaration/assignment which will always be true as long as it succeeds. It seems like you want to compare the two, so use the equal to operator: ==.
Edit: Made a typo and therefore the same mistake as your question shows. Fixed that.
Related
I have those two pieces of code as my home assignment. The code looks all fine to me, but it won't print out what I want, no matter what. In fact, the console output remains completely empty.
The first program is supposed to print out all numbers that fulfil the ladna() function requirements and are between 1 and a:
#include <iostream>
using namespace std;
int a;
int i = 1;
bool ladna(int a)
{
if((((a>>4)*5+a*2)%3)==1)
return true;
else
return false;
}
int main()
{
cerr << "Podaj liczbe: " << endl;
cin >> a;
while (i <= a){
if (ladna(a)){
cout << i << " ";
}
i++;
}
}
the ladna() function is premade and I have to use it as is.
I tried changing while into do...while and for, didn't help. Doesn;t work with cerr either.
The second code has to print out all the natural divisors of number a.
#include <iostream>
using namespace std;
int main()
{
int a;
cerr << "Podaj liczbe" << endl;
cin >> a;
for (int i = 0; i >= a; i++){
if (a % i == 0){
cout << i << endl;
}
}
return 0;
}
Doesn't work either.
To me it looks like both pieces of code have the same issue, because they are written in the same way, based on the same principle, and the error is the same. Hence my assumption, that the cause is the same as well.
Unfortunately, for the love of me, I simply can't see what said error is...
For the first code:
I think you should call ladna function with i, like ladna(i)
For the second code:
In for it should be i<=a
'%' is the modulo operator, during the execution of (a%i) you divide a with i and take the remainder, since i start with zero you will get "Floating point exception (core dumped)" due to division by zero. So, for should start with 1. This should work:
for (int i = 1; i <= a; i++){
if (a%i == 0){
cout << i << endl;
}
}
Below is the prompt that I have:
Write a while loop that prints 1 to userNum, using the variable i.
Follow each number (even the last one) by a space. Assume userNum is positive.
Ex: userNum = 4 prints:
1 2 3 4
I've tried a few things and below is the code that I have so far:
#include <iostream>
using namespace std;
int main() {
int userNum = 0;
int i = 0;
userNum = 4; // Assume positive
cout<<("userNum = %d\n",userNum);
while(i != userNum) {
i++;
cout<<("%d",i);
}
cout << endl;
return 0;
}
The output is close to whats needed but its not correct and I cant seem to figure out what I did wrong.
the output is 41234
Could someone please guide me in the right direction as to what I did incorrectly?
The basic mechanism for this is something like this:
#include <iostream>
int main() {
int i = 0;
int userNum = 0;
userNum = 4;
while(i < userNum) {
++i;
std::cout<<i<<" ";
}
}
Output:
1 2 3 4
You could initialize userNum to be from cin if you'd like, naturally.
The problem is because of this line: cout<<("userNum = %d\n",userNum).
cout does not support a formatting like that. And this resulted in a weird behaviour: it skipped the userNum = part and just printed userNum as int value, which is the first number 4 in your output.
Try to consider the following code instead:
#include <iostream>
using namespace std;
int main() {
int userNum = 0;
int i = 0;
userNum = 4; // Assume positive
cout << "userNum = " << userNum << endl;
while (i != userNum) {
i++;
cout << i;
}
cout << endl;
return 0;
}
The output will be
userNum = 4
1234
as you would've expected. There are many other good sources on how to use string formatting out there. I'll give some links here but it should be easy for you to search them as well.
Link 1 - cplusplus.com - basic input/output
Link 2 - SOF
I hope it helped.
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 wrote a program to sum all odd numbers less than or equal to N. It's not the most efficient or eloquent program, but it works in the compiler on Codepad.org and does not work in DevC++. Usually when a program I wrote is stuck in some kind of infinite loop the program crashes in DevC++ and Windows stops it and lets me know.
Here, the program compiles and runs, but just sits with the cursor blinking and does nothing. Windows doesn't stop it, nothing happens, the program doesn't finish, no matter for how long I let it sit. I'm guessing this is a problem with DevC++ unless it's a problem with my code that Codepad overlooks. Will anyone explain to me what is happening here?
Here is my code:
#include <iostream>
using namespace std;
int odd(int N)
{
int i;
int sum = 0;
for(i = 0; i <= N; ++i)
{
while((i % 2) != 0)
{
sum = sum + i;
}
}
return sum;
}
int main()
{
int N;
cout << "Pick a value: ";
cin >> N;
cout << "The sum of all numbers <= to " << N << " is: " << odd(N);
return 0;
}
I've made the suggested change to an if-statement and the same problem is occuring:
#include <iostream>
using namespace std;
int odd(int N)
{
int i;
int sum = 0;
for(i = 0; i <= N; ++i)
{
if ((i % 2) != 0)
{
sum = sum + i;
}
}
return sum;
}
int main()
{
int N;
cout << "Pick a value: ";
cin >> N;
cout << "The sum of all odd numbers <= to " << N << " is: " << odd(N);
return 0;
}
while((i % 2) != 0)
{
sum = sum + i;
}
This is a infinite loop.Because if (i % 2 != 0) is true then the program will increment sum again and again.What you are probably looking to do is have an if statement instead of while
Seems like the edit is working, please try deleting the old output file and rebuilding and re-compile the entire program.
The output seems to be as follows:
Pick a value: 52
The sum of all odd numbers <= to 52 is: 676
Process exited after 1.034 seconds with return value 0
Press any key to continue . . .
make sure the window of the previous run is closed else the compiler will not recompile but just runs the previous version before you changed it.you may see this as an error stated at bottom in debug mode.
the while() is an infinite loop because i is not changed inside the while() or its {} so use if
I have been trying different techniques to tackling this problem and I am quite new to C++ or programming in general. This problem comes from a book I'm reading over called "Accelerated C++" and so far I'm only on the 3rd chapter so I'm trying to tackle the problem with only what has been taught in the 3rd chapter. When I run the program it runs fine, but as soon as I input a single word I get a segmentation fault. Could anyone explain to me why that is happening? Also if my ways are extremely inefficient with the knowledge I know so far, hinting towards a better way to do things within the chapter boundaries would be great!
Here is the code:
#include <iostream>
#include <algorithm>
#include <ios>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
int main()
{
//ask for the first sentence to be typed in.
cout << "Please enter some words: ";
vector<string> word_storage;
vector<int> word_count;
string x;
int y = 0;
//words inputed pushed into vector(word_storage) or incremented if they exist
while(cin >> x) {
for(int i = 0; i <= y; i++) {
if(x != word_storage[i]) {
word_storage.push_back(x);
word_count.push_back(1);
} else {
word_count[i] += 1;
}
}
y++;
}
cout << endl;
//get size of word_storage
typedef vector<double>::size_type vec_sz;
vec_sz size = word_storage.size();
//system prints how many of each word exist
for(int j = 0; j <= size; j++) {
cout << "There are: " << word_count[j]
<< " of the word " << word_storage[j];
}
cout << endl;
return 0;
}
P.S. I apologize in advanced for the eye-sore coding.
Vectors contain their own size. I believe you've probably got two bugs. First, you the '<=' in your for loop is going to walk off the end of the vector, it should be '<'. Second, you're iterating y when you're not adding words to word_storage.
I think you're find part should look more like:
while(cin >> x) {
for(int i = 0; i < word_storage.size(); i++) {
if(x != word_storage[i]) {
word_storage.push_back(x);
word_count.push_back(1);
} else {
word_count[i] += 1;
}
}
}
There are also a few other improvements that could be made, not the least of which would be to use a structure to tie the storage and the count to the same vector, and using iterators. Consider that when you get to those chapters.
for(int i = 0; i <= y; i++) {
if(x != word_storage[i]) {
word_storage is an unintialized/empty vector. And you are trying to access on a empty vector is causing segmentation fault. As an example, at the beginning of the loop, there is nothing in the vector to do an subscript operation on it.
Do the [] operation on the word_storage, if it's size is greater than i.