Nested For loop to Do while Loop - c++

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
}

Related

Right angle triangle star pattern in C++ using while loops

I want a pattern in which for n=4 in 1st row it has 4 stars and in 2nd row I has 1 space & 3 stars and in 3rd row, it has 2 spaces and 2 stars and so on.
****
***
**
*
The code, I tried to solve this.
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
cout << endl;
int i = 1;
while (i <= n)
{
//Printing Spaces
int space = i - 1;
while (space)
{
cout << " ";
space++;
}
//Printing Stars
int j = 1;
while (j <= n)
{
cout << "*";
j++;
}
cout << endl;
i++;
}
return 0;
}
In your while (space) loop you aren't comparing space to anything, so it assumes that the expression is always true.
Here's a simplified way to do it:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
cout << endl;
int i = 1;
while (i <= n)
{
// print i-1 spaces
for (int j = i-1; j >= 1; j--)
{
cout << " ";
}
// print n-i+1 stars
for (int j = n; j >= i; j--){
cout << "*";
}
cout << endl;
i++;
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
cout << endl;
int i = 1;
while (i <= n)
{
int space = i - 1;
while (space>=1) // change 1.1
{
cout << " ";
space--; // change 1.2
}
int j = i; // change2
while (j <= n)
{
cout << "*";
j++;
}
cout << endl;
i++;
}
return 0;
}
I made only 2 changes in your code so it can work.
1st one
while (space>=1)
what you are doing is you are trying to add space in output so you add space variable in while() loop but that's not going to work because you have to decide first how many spaces you have to print according to that you have to put condition in while() loop. To achieve this space--; added .
For ex. line 4 i=4; space want 3, so space=3; while(space>=1); space--; so while loop runs 3 time and print 3 gaps/spaces.
2nd one
int j = i;
while (j <= n)
if you put j=1; then your gaps print properly but all stars print 4 times as loop runs 4 times always. Due to this condition for i=1; But if you make j=i;
loop runs 4 times for 1st line, 3 times for 2nd line,.....

C++ while loops and for loops not working

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";
}

issue with while loops

#include <iostream>
#include <math.h>
using namespace std;
int main() {
int arrowBaseHeight = 0;
int arrowBaseWidth = 0;
int arrowHeadWidth = 0;
int i = 0;
int j = 0;
cout << "Enter arrow base height:" << endl;
cin >> arrowBaseHeight;
cout << "Enter arrow base width:" << endl;
cin >> arrowBaseWidth;
cout << "Enter arrow head width:" << endl;
cin >> arrowHeadWidth;
cout << endl;
// Draw arrow base
while (i <= arrowBaseHeight){
while (j <= arrowBaseWidth){
cout << "*";
j++;
}
cout << endl;
j = 0;
i++;
}
// Draw arrow head (width = 4)
return 0;
}
I am trying to write a simple program that takes 3 user entered integers and assigns them to arrowBaseHeight, arrowBaseWidth, and arrowHeadWidth. The output should be a series of asterisks (*) that print out like:
**
**
**
****
***
**
*
to create an image of an arrow.
I have been trying to figure out the best way to print out the base portion of the arrow using nested loops (I have been using while but if for is better, let me know). I have tried multiple different ways and I have yet to figure one out that doesn't throw back an error. I have yet to get to the arrow head portion but if anyone wants to point me in the right direction, it would be helpful!
You were close, but if you want for a loop to be executed exactly n times, starting your counter i at 0, the condition should be i < n, not i <= n.
About the head, you just have to decrement the number of characters printed in every line, starting from the inputted width.
#include <iostream>
int main()
{
using std::cout;
using std::cin;
int arrowBaseHeight = 0;
cout << "Enter arrow base height:\n";
cin >> arrowBaseHeight;
int arrowBaseWidth = 0;
cout << "Enter arrow base width:\n";
cin >> arrowBaseWidth;
int arrowHeadWidth = 0;
cout << "Enter arrow head width:\n";
cin >> arrowHeadWidth;
cout << '\n';
// Draw arrow base
for ( int i = 0; i < arrowBaseHeight; ++i )
{
for ( int j = 0; j < arrowBaseWidth; ++j )
{
cout << '*';
}
cout << '\n';
}
// Draw arrow head
for ( int i = 0, width = arrowHeadWidth; i < arrowHeadWidth; ++i, --width )
{
for ( int j = 0; j < width; ++j )
{
cout << '*';
}
cout << '\n';
}
return 0;
}
You can see a lot of repeated code, consider refactoring it using some custom functions, instead.
You should change the condition of the while loops to:
while (i < arrowBaseHeight) and
while (j < arrowBaseWidth).
And for the arrowHeadWidth you could try to get the middle of the arrowBaseHeight. Maybe like this
int r = 0;
if(i == arrowBaseHeight / 2)
{
while(r < arrowHeadWidth)
{
cout << "*";
r++;
}
}
I haven't tested it. I hope it helps.
All you need to do is to add a new variable which could indicate what are you need to print right now.
The rule is :
If: up to half of "arrowBaseHeight" iteration you need to print the base
Else: print the head and after that decrease in 1
In addition finger rule - if you are using "while" and you need to increase an iterator it always indicate that you need to use For
#include <iostream>
#include <math.h>
using namespace std;
int main() {
int arrowBaseHeight = 0;
int arrowBaseWidth = 0;
int arrowHeadWidth = 0;
int newArrowBaseWidth=0;
cout << "Enter arrow base height:" << endl;
cin >> arrowBaseHeight;
cout << "Enter arrow base width:" << endl;
cin >> arrowBaseWidth;
cout << "Enter arrow head width:" << endl;
cin >> arrowHeadWidth;
cout << endl;
// Draw arrow base
for(int i=0; i < arrowBaseHeight; i++){
newArrowBaseWidth= i < arrowBaseHeight/2 ? arrowBaseWidth : arrowHeadWidth--;
for(int j=0; j < newArrowBaseWidth; j++){
cout << "*";
}
cout << endl;
}
// Draw arrow head (width = 4)
return 0;
}
Another thing is if you want to iterate n time you need to change the condition from =< that here mean - n+1 time, to <

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
}
}

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.