Creating a while loop which increases by one - c++

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.

Related

Why doesn't cout work in my code and doesn't show (i - 1) to me?

Can anyone help me with this code?I don't know why cout doesn't work and it doesn't show the (i - 1) in line 14;
The question is:
Joe have 240 minute to do his exam.First question need 5 minute time,second question want 10 minute and etc.He need k minutes to eat dinner after exam.Now we want to know how many questions can he do.
n is number of questions and k is the time that takes for eating dinner.
#include <iostream>
using namespace std;
int main()
{
int i, n, k, sum = 0;
cin >> n >> k;
for(i = 1; i <= n; i++){
if(sum <= 240 - k){
sum += 5 * i;
}
else{
cout << i - 1;
break;
}
}
}
cout is buffered. i probably does appear, just not where you're looking: right before the next prompt, because you're not sending a newline.
cout << i - 1 << '\n';
You may also see:
cout << i - 1 << endl;
Here, endl is a newline plus an instruction. When inserted into the ostream, if causes a flush, forcing all pending output to be written. That can be handy when you need to interleave buffers on one device, as when sending standard input and standard output to the same file or terminal.
because there is case like for n = 5 and k = 10 where sum cannot reach the threshold to actually print. i'm not sure about what you want to do but printing out of the loop might help.
#include <iostream>
using namespace std;
int main()
{
int i, n, k, sum = 0;
cin >> n >> k;
for(i = 1; i <= n; i++){
if(sum <= 240 - k){
sum += 5 * i;
}
else{
break;
}
}
cout << i - 1;
}

Detecting the first digit in the second digits?

Needle in the haystack. I'm a beginner in programming and we only learned a thing or two so far, barely reached arrays yet.
Input: 1 4325121
Output: 2
Input two values in one line. The first one shall accept any integer from 0-9 and the other one shall take a random positive integer.
Using a while loop, count how many of the first integer (0-9) is present in the digits of the second inputted integer and print the result.
No arrays to be used here, only while loops and else-if conditions with basic coding knowledge and without the use of advanced coding.
As you said, you need to keep it as simple as possible. Then this can be a solution:
#include <iostream>
int main()
{
int first { };
int second { };
std::cin >> first >> second;
int quo { second };
int rem { };
int count { };
while ( quo > 0 )
{
rem = quo % 10;
quo /= 10;
if ( first == rem )
{
++count;
}
}
std::cout << "Result: " << count << '\n';
}
Using while loop
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 4325121;
int count = 0;
while(b > 0)
{
int m = b % 10;
if(m == a)
{
count++;
}
b /= 10;
}
cout << count;
return 0;
}
Nice little problem. But actually, to keep it as simple as possible no calculations are needed at all. I simplified my example, and it just keeps working on the input text, which is 100% sufficient to solve the problem:
#include <iostream>
#include <string>
using namespace std;
int main() {
char digit;
std::string number;
cout << "Input: ";
cin >> digit >> number;
int count = 0;
for (char const character : number)
if (character == digit)
count++;
cout << "Result: " << count << endl;
return 0;
}
Given the question, this code solves the problem.

Why is this do while loop infinitely executing?

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.

How to take numerous inputs without assigning variable to each of them in C++?

I'm beginning with C++. The question is: to write a program to input 20 natural numbers and output the total number of odd numbers inputted using while loop.
Although the logic behind this is quite simple, i.e. to check whether the number is divisible by 2 or not. If no, then it is an odd number.
But, what bothers me is, do I have to specifically assign 20 variables for the user to input 20 numbers?
So, instead of writing cin>>a>>b>>c>>d>>.. 20 variables, can something be done to reduce all this calling of 20 variables, and in cases like accepting 50 numbers?
Q. Count total no of odd integer.
A.
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int n,odd=0;
cout<<"Number of input's\n";
cin>>n;
while(n-->0)
{
int y;
cin>>y;
if(y &1)
{
odd+=1;
}
}
cout<<"Odd numbers are "<<odd;
return 0;
}
You can process the input number one by one.
int i = 0; // variable for loop control
int num_of_odds = 0; // variable for output
while (i < 20) {
int a;
cin >> a;
if (a % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
If you do really want to save all the input numbers, you can use an array.
int i = 0; // variable for loop control
int a[20]; // array to store all the numbers
int num_of_odds = 0; // variable for output
while (i < 20) {
cin >> a[i];
i++;
}
i = 0;
while (i < 20) {
if (a[i] % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
Actually, you can also combine the two while-loop just like the first example.
Take one input and then process it and then after take another intput and so on.
int n= 20; // number of input
int oddnum= 0; //number of odd number
int input;
for (int i = 0; i < n; i ++){
cin >> input;
if (input % 2 == 1) oddnum++;
}
cout << "Number of odd numbers :"<<oddnum << "\n";

Program Compiles, Runs, but doesn't end in DevC++

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