C++ while loops and for loops not working - c++

First, I'll send the code.
#include <iostream>
using namespace std;
int main() {
int times = 0;
cout << "Enter a number of candies:";
int number;
cin >> number;
while (number >= 1000) {
cout << "Please enter an integer number between 0 and 999.\n";
cin >> number;
}
for (times <= 10; times++; number--) {
cout << "nomnom I have" << number - 1 << "candies left.\n";
}
}
I am trying to practice c++ because I'm a beginner so I made a little program that is supposed to allow you to enter a number between 1 and 999, then this is gonna be the number of candies. Then, it says how many there are left. It's not working though. Can anyone tell me why? Thanks.

You should have your for loop formatted like this:
for (; times <= 10; times++, number--) {
cout << "nomnom I have" << number - 1 << "candies left.\n";
}
The format of the for loop follows the following rule:
for(<initializer, which you can skip> ; <condition for execution which is required> ; <increment or decrement of the variable which you are bounding with the condition, this part is not required either>)
Within the initializer part you can create multiple variables, you just need to separate them with a ",", the same rule applies to the final part of the for loop. Neither the initializer not the modifier at the end are required for correct syntax. This is a valid example:
int i = 0;
for(; i < 5;)
{
++i;
}
For example:
for(int i = 0, j = 5; i < 5 && j > 0; ++i, --j){}
int i = 0, j = 5;
for(; i < 5 && j > 0; ++i, --j){}
int i = 0, j = 5;
for(; i < 5 && j > 0;){
++i;
--j;
}
All of these examples are accomplishing the same task of incrementing i and decrementing j.

Your for loop is incorrect - it should be done according to this:
for( <initialization> ; <checking> ; <run_in_each_loop> ){ ...}
You can read more about for loop here.
You want your code to do 2 "increments" (<run_in_each_loop>). You can't do this using ; in between
A common idiom is to use the comma operator which evaluates both
operands, and returns the second operand. Thus:
for(int i = 0; i != 5; ++i,++j)
do_something(i,j);
read more here.
Other way would be to put number-- inside of { ... } brackets.
In the end, your code should look like that:
#include <iostream>
using namespace std;
int main() {
int times = 0;
cout << "Enter a number of candies:";
int number;
cin >> number;
while (number >= 1000) {
cout << "Please enter an integer number between 0 and 999.\n";
cin >> number;
}
for ( ; times <= 10; times++, number--) {
cout << "nomnom I have" << number << "candies left.\n";
}
return;
}

You're pretty close! There was just a slight issue with the for loop syntax:
The first part of the for loop is actually the initializer, the middle bit is the conditional, and the last bit is the iterator, it's a bit different than the while loop.
Here is what you probably meant to do:
for (times = 0; times < 9; number--, times++) {
cout << "nomnom I have" << number - 1 << "candies left.\n";
}

Related

Nested For loop to Do while Loop

Hi I read the guidelines about homework questions and it says to clearly state that it is homework. This is homework, I have spent the last 45 minutes trying over and over again. I've hit a wall and need help.
My assignment was to take this code that came from a double For loop and convert it into a while loop nested into a for loop. I have successfully completed that. However, the 3rd part is to take that code and make the outer for loop into a do while loop.
The output needs to increment a "#" each line like so if the input was "4"
#
##
###
####
Below is my code that I wrote that I need to make the outer for loop into a do while loop:
int main()
{
int side;
cout << "Enter a number: ";
cin >> side;
for (int i = 0; i < side; i++)
{
int j = i;
while(j >= 0)
{
cout << "#";
j--;
}
cout << "\n";
}
}
This is my attempt so far:
int main()
{
int side;
int i;
cout << "Enter a number: ";
cin >> side;
int j=side;
do
{
while(j >= 0)
{
cout << "#";
j--;
}
cout << "\n";
i++;
}
while(j >= side);
}
My teacher said as long as the code is explained and I understand how it works that it's okay. Any help would be much appreciated.
Thanks.
The first mistake you made is this:
int i; //not initialized!
/*...*/
i++;
and you didn't even use it in your do-while condition.
So while(j >= side); > while (i >= side);
Actually, that's not true, either. Since side is the input, you want i to check if it's smaller not greater then the input. So it's while (i < side);
Another thing is int j=side;, when you decrement j it will never reset, so you must set this into your do-while loop and also initialize it with i rather than side....
Anyway, here's the full code:
#include <iostream>
using namespace std;
int main()
{
int side;
int i = 0;
cout << "Enter a number: ";
cin >> side;
do
{
int j = i;
while (j >= 0)
{
cout << "#";
j--;
}
cout << "\n";
i++;
} while (i < side);
return 0;
}
example output:
Enter a number: 10
#
##
###
####
#####
######
#######
########
#########
##########
I suggest
int main()
{
int side;
int i = 0;
cout << "Enter a number: ";
cin >> side;
do
{
int j = i;
while(j >= 0)
{
cout << "#";
j--;
}
cout << "\n";
i++;
}while(i < side)
}
A for loop usually consists in an initialization (i=0), a stop condition (i < side) and an increment (i++); why would you not use i anymore?
while(j >= side); should be while(i <= side);
j should be initialized in each iteration of the outer loop (j = i;)
int j=side; is unnecessary.
An friendly suggestion - name your variables and functions descriptively - row and column are much better than i and j.
They answer above solves your problem but let me show you a shorter way to do things:
int main()
{
int side;
std::cout << "Enter a number: ";
std::cin >> side;
int row = 1;
do
{
int col = 0;
while (col++ != row)
{
std::cout << "#";
}
std::cout << "\n";
} while (row++ != side); //This way, the condition is checked (row != side), and then row is incremented
}

Use C++ to Print a Floyd triangle

I'm trying to build a program which will accept numbers from user and create Floyd triangle.
I tried using the logic of Floyd triangle, but its printing as a line.
Example:
Enter total numbers: 5
Enter the numbers: 3,8,2,4,9
O/p:
3
82
249
Here's my code:
#include <iostream>
using namespace std;
int main()
{
int totalnos, j, i;
cout << "Enter total numbers: ";
cin >> totalnos;
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 1; i <= totalnos; i++)
{
cin >> numbers[i];
}
for (i = 1; i <= totalnos; i++)
{
for (j = 1; j <= 1; j++)
{
cout << numbers[i];
}
}
}
You have a problem with the kind of loops shown below. I don't know wether this kind of solution is due to you coming from the Pascal world, or because you've seen it elsewhere. Anyway, you should not make loops start in 1 and go to i, or at least, you should take into account that in the C-like world (C, C++, Java, C#, and many others), arrays start at index 0, and end at index n - 1, being n the size of the array.
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 1; i <= totalnos; i++)
{
cin >> numbers[i];
}
The problem is actually not what indexes you use for loops, but that you must always use 0..n-1 when accessing arrays. So you can change your loop to just access the array correctly:
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 1; i <= totalnos; i++)
{
cin >> numbers[ i - 1 ];
}
Or you can do as all programmers in the C-like world, and directly start your indexes at 0:
int numbers[totalnos];
cout << "Enter the numbers: ";
for (i = 0; i < totalnos; i++)
{
cin >> numbers[i];
}
Instead of going from 1 to totalnos, now you go from 0 to totalnos - 1 (notice the i < totalnos instead of the i <= totalnos, that's a sutil change).
You were accessing memory past the limit of the array, which means that your program will show undefined behaviour (this means that it will probably crash, though under some conditions, nothing seems to happen, which is even more dangerous).
Now the algorithm itself. I haven't heard about the Floyd triangle. It seems that it is built with the natural numbers starting from 1. However, you are asking for totalnos numbers. You will need more than totalnos numbers in order to build a Floyd triangle with totalnos rows. That's why you need to adjust the position of the number being shown taking into account the number of columns for each row (numPos starts with 0).
cout << endl;
for (i = 0; i < totalnos; i++)
{
if ( ( totalnos - i ) < numPos ) {
numPos = totalnos - i;
}
for (j = 0; j < i; j++)
{
cout << numbers[numPos] << ' ';
++numPos;
}
cout << endl;
}
You can find the whole code here: http://ideone.com/HhjFpz
Hope this helps.
Internal loop can be modified as below :
for (i=0; i < 3; i++)
{
for (j=0; j<=i; j++)
{
cout << numbers[i+j];
}
cout<<" ";
}
Hard coded value "3" can be replaced with the "number of rows of Floyd triangle .
I think this will do the trick .
In inner loop you made mistake with j <= 1; should be j <= i;
And you missed '\n' char for new line.
Here is fix:
#include <iostream>
using namespace std;
int main()
{
int totalnos, j, i, k = 0;
cout << "Enter total numbers: ";
cin >> totalnos;
//int numbers[totalnos];
//cout << "Enter the numbers: ";
// for (i = 1; i <= totalnos; i++)
// {
// cin >> numbers[i];
// }
for (i = 1; i <= totalnos; i++)
{
// your code for (j = 1; j <= 1; j++)
for(j=1; j<=i; ++j) // fixed
cout << k+j << ' ';
++k;
cout << endl; // fix
}
}

Comparing digits and finding numbers with same digits

here is my problem.The program needs to print out the number of numbers in the range between m and n which have different digits.For example:m=97,n=104;output:5.I seem to have problem with comparing the numbers and finding a way to check if there are 2 same digits.Here what I've written up till now:
enter code here
#include <iostream>
using namespace std;
int main()
{
int m, n;
cout << "m=";
cin >> m;
cout << "n=";
cin >> n;
for (int i = m; i <=n; ++i)
{
if (i >= m && i <= n)
{
while (i > 0)
{
m=i%=10;
i/= 10;
cout << m;
}
}
}
system("pause");
return 0;
}
If you can give me the easiest possible solution.Thanks in advance
The best way to do this is to break it down into two parts. The main part is responsible for incrementing the number set (which is easiest if the variables are integers) and the second part is to compare each part of the number to see if a number has been repeated (which is best done as a string).
So first I would define the method responsible for determining if the value has all distinct digits:
bool hasDistinctDigits(int m) {
string number = to_string(m);
for (string::size_type i = 0; i < number.size(); i++) {
for (string::size_type j = i + 1; j < number.size(); j++) {
if (number[i] == number[j]) return false;
}
}
return true;
}
This should be pretty easy to understand. First we need to convert the number to a string. Then we use 2 loops to determine if a character is repeated in a higher index. For example, with the number 102, it will compare the following sets: {1, 0}, {1,2}, {0, 2}
Then in the main function, I would call it like this:
int main()
{
int m, n, matched = 0;
cout << "m=";
cin >> m;
cout << "n=";
cin >> n;
for (int current = m; current <= n; ++current){
if (hasDistinctDigits(current)) {
cout << current << " is distinct" << endl;
matched++;
}
}
cout << "Total Matched: " << matched << endl;
system("pause");
return 0;
}

How to count how many times each number has been encountered?

I am trying to write a program to count each number the program has encountered. by putting M as an input for the number of the array elements and Max is for the maximum amount of number like you shouldn't exceed this number when writing an input in the M[i]. for some reason the program works just fine when I enter a small input like
Data input:
10 3
1 2 3 2 3 1 1 1 1 3
Answer:
5 2 3
But when I put a big input like 364 for array elements and 15 for example for max. the output doesn't work as expected and I can't find a reason for that!
#include "stdafx.h"
#include <iostream>
#include<fstream>
#include<string>
#include <stdio.h>
#include<conio.h>
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int checker[1000];
int element_cntr = 0;
int cntr = 0;
int n = 0;
void main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue>> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
checker[i]= M[i] ;
element_cntr++;
if (M[i] > Max)
{
cout << "the element number " << element_cntr << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (M[n] == checker[j])
{
cntr+=1;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
n++;
}
}
You have general algorithm problem and several code issues which make code hardly maintainable, non-readable and confusing. That's why you don't understand why it is not working.
Let's review it step by step.
The actual reason of incorrect output is that you only iterate through the first Max items of array when you need to iterate through the first Max integers. For example, let we have the input:
7 3
1 1 1 1 1 2 3
While the correct answer is: 5 1 1, your program will output 5 5 5, because in output loop it will iterate through the first three items and make output for them:
for (int i = 0; i < Max; i++)
for (int j = 0; j < ArrayValue; j++)
if (M[n] == checker[j]) // M[0] is 1, M[1] is 1 and M[2] is 1
It will output answers for first three items of initial array. In your example, it worked fine because the first three items were 1 2 3.
In order to make it work, you need to change your condition to
if (n == checker[j]) // oh, why do you need variable "n"? you have an "i" loop!
{
cntr += 1;
}
It will work, but both your code and algorithm are absolutely incorrect...
Not that proper solution
You have an unnecessary variable element_cntr - loop variable i will provide the same values. You are duplicating it's value.
Also, in your output loop you create a variable n while you have a loop variable i which does the same. You can safely remove variable n and replace if (M[n] == checker[j]) to if (M[i] == checker[j]).
Moreover, your checker array is a full copy if variable M. Why do you like to duplicate all the values? :)
Your code should look, at least, like this:
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int cntr = 0;
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue >> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
if (M[i] > Max)
{
cout << "the element number " << i << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (i == M[j])
{
cntr ++;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
}
return 0;
}
Proper solution
Why do you need a nested loop at all? You take O(n*m) operations to count the occurences of items. It can be easily counted with O(n) operations.
Just count them while reading:
using namespace std;
int arraySize;
int maxValue;
int counts[1000];
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> arraySize >> maxValue;
int lastReadValue;
for (int i = 0; i < arraySize; i++)
{
cin >> lastReadValue;
if (lastReadValue > maxValue)
cout << "Number " << i << " is bigger than maxValue! Skipping it..." << endl;
else
counts[lastReadValue]++; // read and increase the occurence count
}
for (int i = 0; i <= maxValue; i++)
{
if (counts[i] > 0)
cout << i << " occurences: " << counts[i] << endl; // output existent numbers
}
return 0;
}

Ensure unique input is entered and stored in an array

Is this program OK, or can it be improved (but simply)? How do I make sure no repeat numbers are entered?
int n;
int array[9];
cout<<"Enter Number Between 9-0 Only"<<endl;
for(int i = 0; i<=10; i++){
cout<<"Enter Number" <<(i+1)<<endl;
cin >> n;
if((n >= 0) && (n <=9)){
array[i]=n;
}
else{
cout<<"Numbers from 0-9 only\n"<<endl;
break;
}
}
(edit) complete, compiling code
To check if the numbers are used with higher performance, try something like this (using the working code from Jack Radcliffe):
#include <iostream>
using namespace std;
int main()
{
int n = 0;
int array[9] = {0};
bool isUsed[10] = {0};
for(int i = 0; i < 9; i++)
{
cout << "Enter Number " << (i + 1) << endl;
cin >> n;
if((n >= 0) && (n <= 9))
{
if (isUsed[n] == false)
{
array[i] = n;
isUsed[n] = true;
}
else
{
cout << "Number has already been used." << endl;
i--;
}
}
else
{
cout << "Numbers from 0-9 only." << endl;
i--;
}
}
return 0;
}
Optimization isn't exactly necessary with this simple of code, but it's this seems to be an exercise of practice, so why not practice optimized code, too?
Most of it is fine, though there are two problems standing out.
First, you have an array of size 9, but you are taking in 11 numbers since you're starting the for loop at 0 and going through to 10.
Second, since you have it so if the entered number is not between 0 and 9, inclusive, the for loop breaks. This entails that fewer than 9 numbers will be put into the array if an invalid number is entered. Change the entire loop to read this and you should be good:
for(int i = 0; i < 9; i++) {
cout << "Enter Number " << (i + 1) << endl;
cin >> n;
if((n >= 0) && (n <= 9))
array[i] = n;
else {
cout << "Numbers from 0-9 only\n" << endl;
i--;
}
}
The whole fire part was right, but I removed the break in the else-statement and added in the i--. I added that in so when the user is prompted to re-enter the number, the entry number will be at the correct index.
I hope this was helpful.