I need to use a For Loop to display all numbers from the input value down to 1.
I figured out the code to do the opposite of the question which is from 1 to input value but am confused if i should lower or increase the increment.
for (i = 1; i <= userChoice; i++)
{
cout << "Loop 1:" << endl;
cout << i << endl;
}
You may increment counter
for (int i = 0; i < userChoice; ++i)
{
std::cout << userChoice - i << std::endl;
}
or decrement it
for (int i = userChoice; i != 0; --i)
{
std::cout << i << std::endl;
}
Demo
You can do this to write the numbers in descending order.
for (i = userChoice; i >= 1; i--)
{
cout << "Loop 1:" << endl;
cout << i << endl;
}
Related
C++ is reading from a file and printing out the numbers backwards.
i got rid of the comma when it prints out forward. But I cannot figure out how to do the same for back wards.
so far this is what I have:
cout<<"Forwards: ";
for (int i=0; i<cnt; i++){
cout<<setprecision(2)<< fixed;
if (i == cnt - 1)
{
cout << arr[i];
}
else
{
cout << arr[i] << ", ";
}
}
cout<<endl;
//printing backwards
cout << "Backwards: ";
for (int i=cnt-1; i>=0; i--){
cout<<setprecision(2)<< fixed;
if (i == cnt + 1)
{
cout << arr[i];
}
else
{
cout << arr[i] << ", ";
}
the forwards part comes out correct:
1.00, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00, 8.00, 9.00, 10.00
but the backwards is what prints out
10.00, 9.00, 8.00, 7.00, 6.00, 5.00, 4.00, 3.00, 2.00, 1.00,
how do I get rid of that last comma
Try something like this:
bool first_item = true;
for (unsigned int i = 0u; i < LIMIT; ++i)
{
if (! first_item)
{
std::cout << ", ";
}
first_item = false;
std::cout << number;
}
std::cout << "\n";
The above code fragment works regardless of the direction, ascending or descending.
The important part is the "flag" to determine if the first item has been printed.
In the forward-moving loop, if (i == cnt - 1) is checking if i is on the last element of the array.
In the backward-moving loop, you want to check if i is on the first element, but if (i == cnt + 1) will never be true for that check, as cnt+1 is out of bounds. The first element is at index 0, so use if (i == 0) instead:
cout << "Forwards: ";
cout << setprecision(2) << fixed;
for (int i = 0; i < cnt; ++i){
if (i == cnt - 1){
cout << arr[i];
}
else{
cout << arr[i] << ", ";
}
}
cout << endl;
cout << "Backwards: ";
cout << setprecision(2) << fixed;
for (int i = cnt-1; i >= 0; --i){
if (i == 0){
cout << arr[i];
}
else{
cout << arr[i] << ", ";
}
}
cout << endl;
Alternatively, print the 1st output value outside of the loop, and then start the loop on the 2nd output value:
cout << "Forwards: ";
cout << setprecision(2) << fixed;
cout << arr[0];
for (int i = 1; i < cnt; ++i){
cout << ", " << arr[i];
}
cout << endl;
cout << "Backwards: ";
cout << setprecision(2) << fixed;
cout << arr[cnt-1];
for (int i = cnt-2; i >= 0; --i){
cout << ", " << arr[i];
}
cout << endl;
Just write
if(i == 0)
instead of
if(i == cnt+1)
It will do the work.
I need to write a function that checks if an array passed through it in order from smallest value to largest. The issue that I'm having is that the function is returning true for all arrays. I put a 'cout' statement within the function an noticed that the numbers did not match the array. For example, when 4 is pressed, since the array would be [30..1], it should return the array and that it is not ordered. Yet the actual return is:
18224
array is sorted
1
which is incorrect. What am I doing wrong?
int isOrdered(int arr[], int n) {
if (n <= 1) // array with 1 or no elements
return 1; // is always sorted
for (int i = 1; i < n; i++) {
cout << arr[i] << ' ';
cout << endl;
if (arr[i-1] >= arr[i]) {
cout << "array is not sorted " << endl;
return -1;
}
}
return 1;
}
int main() {
int input;
// Prompt for user
cout << "----------------------------------------------" << endl;
cout << " Press 1 to exit the program " << endl;
cout << " Press 2 to select the array that is sorted in increasing order " << endl;
cout << " Press 3 to select the array that is randomly sorted " << endl;
cout << " Press 4 to select the array that is sorted in decreasing order " << endl;
cout << "----------------------------------------------" << endl;
cin >> input;
// catch if input not within bounds
while (input != 1 && input != 2 && input != 3 && input != 4)
{
cout << "----------------------------------------------" << endl;
cout << " Press 1 to exit the program " << endl;
cout << " Press 2 to select the array that is sorted in increasing order " << endl;
cout << " Press 3 to select the array that is randomly sorted " << endl;
cout << " Press 4 to select the array that is sorted in decreasing order " << endl;
cout << "----------------------------------------------" << endl;
cin >> input;
}
while (input != 1)
{
int n = 30;
int* a = new int[n];
int* b = new int[n];
int* c = new int[n];
int* a_c = new int[n];
int* b_c = new int[n];
int* c_c = new int[n];
if (input == 2) {
for (int i = 0; i < n; i++) {
a[i] = i + 1;
}
// duplicated array needed to be created per instructions
for (int i = 0; i < n; i++) {
a_c[i] = a[i];
}
cout << isOrdered(a_c, n) << endl;
}
else if (input == 3) {
/* seed the PRNG (MT19937) using a variable value (in our case, s)*/
std::mt19937 generator(1); // seed by variable input
std::uniform_int_distribution<int> distribution(1, n); // random numbers need to be in range between 1, n
for (int i = 0; i < n; i++) {
b[i] = distribution(generator);
//cout << b[i] << ' '; // testing
}
// create duplicate
for (int i = 0; i < n; i++) {
b_c[i] = b[i];
cout << b_c[i] << ' ';
}
cout << isOrdered(b, n) << endl;
}
else {
for (int i = n-1; i >= 0; i--) {
c[i] = i + 1;
}
// create duplicate
for (int i = 0; i < n; i++) {
c_c[i] = c[i];
}
cout << isOrdered(c_c, n) << endl;
}
// Prompt user again
cout << "----------------------------------------------" << endl;
cout << " Press 1 to exit the program " << endl;
cout << " Press 2 to select the array that is sorted in increasing order " << endl;
cout << " Press 3 to select the array that is randomly sorted " << endl;
cout << " Press 4 to select the array that is sorted in decreasing order " << endl;
cout << "----------------------------------------------" << endl;
cin >> input;
// catch if input not within bounds
while (input != 1 && input != 2 && input != 3 && input != 4)
{
cout << "----------------------------------------------" << endl;
cout << " Press 1 to exit the program " << endl;
cout << " Press 2 to select the array that is sorted in increasing order " << endl;
cout << " Press 3 to select the array that is randomly sorted " << endl;
cout << " Press 4 to select the array that is sorted in decreasing order " << endl;
cout << "----------------------------------------------" << endl;
cin >> input;
}
}
exit(0);
}
You have a potential for Undefined Behavior iterating from i = 0; i < n and accessing arr[i+1] -- which will be one past the end of the array when i == n - 1. "Potential" because you never get there -- you are returning on your first iteration.
Instead, why not simply do:
int isOrdered(int arr[], int n) {
int i = 1;
for (; i < n; i++)
if (a[i-1] > a[i])
break;
return i == n ? 1 : -1;
}
Your function is return'ing on the 1st iteration regardless of the contents of the entire array. You need to return false as soon as you detect a mismatch, but do not return true until the loop has finished checking the entire array and did not detect a mismatch, eg:
bool isOrdered(int arr[], int n) {
if (n < 1) {
cout << "array is empty" << endl;
return false;
}
cout << arr[0];
for (int i = 1; i < n; ++i) {
cout << ' ' << arr[i];
if (arr[i] < arr[i - 1]) {
cout << "array is not sorted" << endl;
return false;
}
}
cout << "array is sorted" << endl;
return true;
}
You do create a sorted array [1..30] (you just start from the end while filling it) - to create [30..1] you'd need c[i] = n - i; and you don't need to loop backwards then.
You are checking only the first elements and then you immediately return from the function, so [5,6,1,2] would also be "sorted" because you look only at 5 and 6. You should return as "sorted" only when you are done with the whole loop without running into the "unsorted" condition, so put your "sorted" conclusion outside of the loop.
You access one element beyond the end of the array due to i < n instead of i < n - 1, which is dangerous undefined behavior (and will mess up your result).
Also, side note: Stepping through your code using a debugger would be a tremendous help for you to understand what is going wrong, and you wouldn't need to ask here every time something is not working. You would have noticed that the array actually contains ascending instead of descending numbers, and you would also have noticed that the comparison function returns after one check only, instead of looping.
generated = (rand() % 11);
cout << "GUESS THE NUMBER 10 TIMES" << endl;
for (int i = 0; i < 10; i++) {
cin >> guesses[i];
if (generated == guesses[i]) {
cout << "CONGRATS ! YOU HAVE FOUND THE CORRECT NUMBER ! " << generated << endl;
restart();
break;
}
}
cout << "HERE ARE YOUR GUESSES:" << endl;
for (int k = 0; k < 10; k++) {
cout << guesses[k] << endl;
}
If the array isn't filled up, the output gives me the guessed values and then in the empty slots are random numbers. Is there a way to clear or delete the untouched slots?
Yes. Keep a count of how many inputs you take c and loop up to c instead of 10 in your second loop:
int c = 0;
cout << "GUESS THE NUMBER 10 TIMES" << endl;
for (int i = 0; i < 10; i++) {
cin >> guesses[i];
c++;
if (generated == guesses[i]) {
cout << "CONGRATS ! YOU HAVE FOUND THE CORRECT NUMBER ! " << generated << endl;
restart();
break;
}
}
cout << "HERE ARE YOUR GUESSES:" << endl;
for (int k = 0; k < c; k++)
cout << guesses[k] << endl;
I've been trying to overcome this problem for a few hours now and I seem to have one approach to the situation. It seems that the use of selection statements worked in creating the table necessary. Although there are formatting issues.
I'd like to know if there was a way to create the same table
using only nested for-loops as mentioned by our professor.
Are the selection statements necessary or can we implement a system of nested for loops to acquire the same results?
The image below is the required table:
But the image below is what I have:
Below is my code:
for (int i = 0; i <= numChoice; ++i)
{
if (i == 0)
{
for (int k = 1; k <= numChoice; ++k)
{
cout << " " << k;
}
cout << "\n";
}
else
{
cout << i << " | ";
for (int j = 1; j <= numChoice; ++j)
{
if (j*i <= 9)
{
cout << " " << j*i << "|";
}
else if (j*i > 9 && j*i <= 100)
{
cout << " " << j*i << "|";
}
else if (j*i > 99 && j*i <= 999)
{
cout << " " << j*i << "|";
}
}
cout << "\n";
for (int k = 0; k <= numChoice; ++k)
{
if (k == 0)
{
cout << "-|";
}
else
{
cout << "----|";
}
}
cout << "\n";
}
}
The following code uses no if else constructs. The formatting can be got by using setw, used for setting the width of integers.Following code produces perfect output.
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int i,j;
cout<<" "<<1;//5 space chars
for(i = 2;i <= 10;++i)
cout<<" "<<i;//4 space chars
cout<<endl;
cout<<" ----|";
for(i = 2;i <= 10;++i)
cout<<"----|";
cout<<endl;
for(i = 1;i <= 10;++i)
{
cout<<setw(2)<<i<<"|";
for(j = 1;j <= 10;++j)
cout<<setw(4)<<j*i<<"|";
cout<<endl;
cout<<" -|----";
for(j = 2;j <= 9;++j)
cout<<"|----";
cout<<"|----|";
cout<<endl;
}
return 0;
}
#FranticCode. I'm also in the same class as you and was having problems with this homework assignment as well. I still don't understand it, but I figured out how to manipulate Sumeet's code to give us correct format. The ONLY thing I am having a problem with now is adding an empty space AFTER the first multiplication table and before the menu redisplay. I'll share what I have and maybe you can figure it out. Still going to ask the professor to review chapter 5 because I would like to learn it rather than just submit the homework.
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
char userSelection;
int numForTable;
int col;
int row;
do
{
cout << "MENU" << endl
<< "a) Generate Multiplication Table" << endl
<< "q) Quit the program" << endl
<< "Please make a selection: ";
cin >> userSelection;
if (userSelection == 'a')
{
cout << "Please enter a number for your multiplication table: " << endl;
cin >> numForTable;
while (numForTable < 1 || numForTable > 10)
{
cout << "Please enter a number between 1 & 10." << endl;
cin >> numForTable;
}
cout << "\n"
<< "MULTIPLICATION TABLE: " << numForTable << "'s" << endl
<< "\n"
<< " " << 1;
for (col = 2; col <= numForTable; ++col)
cout << " " << col;
cout << endl;
cout << " ----|";
for (col = 2; col <= numForTable; ++col)
cout << "----|";
cout << endl;
for (col = 1; col <= numForTable; ++col)
{
cout << setw(2) << col << "|";
for (row = 1; row <= numForTable; ++row)
cout << setw(4) << col * row << "|";
cout << endl;
cout << " -|----";
for (row = 2; row <= numForTable - 1; ++row)
cout << "|----";
cout << "|----|";
cout << endl;
}
}
else if (userSelection != 'q')
{
cout << "Invalid Selection\n" << endl;
}
else if (userSelection == 'q')
{
cout << " You have chosen to quit the program. Thank you for using!" << endl;
}
}
while (userSelection != 'q');
//system("PAUSE");
return 0;
}
got curious to see if i could add the lines as easy as i claimed, it took a bit of fiddling, but here's the result (updated code below to also have lines).
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int counter;
int counter2;
int amount;
cout << " |-----------------------------------------------------------|" << endl; // first line of table.
for(counter=1;counter<11;counter++){ // the 2 for lines create our 2 dimensional table
for(counter2=1;counter2<11;counter2++){
cout << " | " << setw(3) << counter*counter2; // setw(3) is a function of <iomanip>,
//setting minimum width to 3 for numbers.
}
cout << " |" << endl; // this here is being added to the end of each line and starts a new line.
cout << " |-----------------------------------------------------------|" << endl; // this is being inserted between each line, and starts a new line.
}
return 0;
}
Use the following construct:
for (int i=0; i<=numChoice; i++) // display first row of numbers
cout <<"\t" << i << "\t";
cout << "\n";
for (int i=0; i <=numChoice; i++) {
cout << i << "\t";
for (int j=0; j <=numChoice; j++)
cout << i*j << "\t";
cout << "\n";
}
i've been studying c++ for 3 months , and i studied the arrays , i wrote a program such that will take inputs from user , then the program will store these numbers in a special array , then the program will split them into two arrays , one for even numbers, the other one for odd numbers , my question is , when i tried to display them , there was something wrong happened , but i could not figure it out , can you help me please ?
int main () {
int even[5];
int odd[5];
int num;
cout << "enter 4 numbers!";
for(int i=0; i<4; i++) {
cin >> num;
if( num%2 == 0){
cout << "its an even number!";
even[i] += num;
}
else{
cout << "its an odd number!";
odd[i] += num;
}
}
cout << "The odd number/s is/are: ";
for( int u=0; u<4; u++){
cout << odd[u] << endl;
}
cout << endl;
cout << "The even number/s is/are: " << endl;
for(int z=0; z<4; z++){
cout << even[z] << endl;
}
}
Thank you for helping me!
From your question, it looks like you're trying to split a given integer array into two arrays even and odd. The problem here is the way in which you're allocating the values into the new arrays, You have a counter i which is responsible to put the values into even[i] and odd[i]. So you have a lot of broken sections even[0] might exist but the odd[1] might be the first odd value you obtain. You should have individual counters for storing these values. So the corrections to your code would look as follows
int main () {
int even[5];
int odd[5];
int num;
int evencount = 0;
int oddcount = 0;
cout << "enter 4 numbers!";
for(int i=0; i<4; i++) {
cin >> num;
if( num%2 == 0){
cout << "its an even number!";
even[evencount++] = num;
}
else{
cout << "its an odd number!";
odd[oddcount++] = num;
}
}
cout << "The odd number/s is/are: ";
for( int u=0; u < oddcount; u++){
cout << odd[u] << endl;
}
cout << endl;
cout << "The even number/s is/are: " << endl;
for(int z=0; z<evencount; z++){
cout << even[z] << endl;
}
}
I have a slightly different approach:
#include <iostream>
using namespace std;
int main () {
int array[4]; // array size needs to be 4 only and not 5
/*int num;*/ // not required
bool is_odd[4] = {false, false, false, false};
cout << "enter 4 numbers!\n";
for(int i=0; i<4; i++) {
cin >> array[i];
if( array[i]%2 == 0){
cout << "its an even number!\n";
}
else{
cout << "its an odd number!\n";
is_odd[i] = true;
}
}
cout << "The odd number/s is/are:\n";
for( int u=0; u < 4; u++){
if (is_odd[u] == true)
cout << array[u] << endl;
}
cout << endl;
cout << "The even number/s is/are:\n" << endl;
for(int u=0; u < 4; u++) {
if (is_odd[u] == false)
cout << array[u] << endl;
}
}
Check the answer here: check-answer
You access values of the array that are declared but not initialized. So there are any values in it. like 6.49e154. Always initialize when declaring!