If statement inside of a for cycle - c++

first of all, sorry if my title isn't appropriate. English isn't my first language so I didn't really know how to phrase it correctly and understandably.
So, I'm learning some C++ and I got stuck on a problem. Right now my code looks like this:
#include <iostream>
using namespace std;
int main()
{
int start, finish;
cout << "Enter range start" << endl;
cin >> start;
cout << "Enter the range end" << endl;
cin >> finish;
if (start < finish)
{
for (int i = start; i <= finish; i++)
{
cout << "Number " << i << " is divisible by ";
for (int j = 2; j <= 10; j++)
{
if (i % j == 0)
{
cout << j << " ";
}
}
cout << endl;
}
}
return 0;
}
And the output I get is:
Number i is divisible by j1, j2 and etc.
Number i is divisible by
Number i is divisible by j1, j2 and etc.
You get the idea.
What I'm trying to get is this
Number i is divisible by j1, j2 and etc.
Number i isn't divisible by any numbers
Number i is divisible by j1, j2 and etc.
I tried doing this:
#include <iostream>
using namespace std;
int main()
{
int start, finish;
cout << "Enter range start" << endl;
cin >> start;
cout << "Enter the range end" << endl;
cin >> finish;
if (start < finish)
{
for (int i = start; i <= finish; i++)
{
cout << "Number " << i;
for (int j = 2; j <= 10; j++)
{
if (i % j == 0)
{
cout << " is divisible by " << j << " ";
}
else
{
cout << " isn't divisible by any numbers";
}
}
cout << endl;
}
}
return 0;
}
But the output is just a mess. Sorry if this is something straight forward and something I could've looked up on the net, but I just didn't know how to phrase my problem correctly and what to look for. I'll appreciate any help.

You should
create a flag that indicates if any j that divides i.
after the loop, check the flag and print the message if applicable.
#include <iostream>
using namespace std;
int main()
{
int start, finish;
cout << "Enter range start" << endl;
cin >> start;
cout << "Enter the range end" << endl;
cin >> finish;
if (start < finish)
{
for (int i = start; i <= finish; i++)
{
cout << "Number " << i;
bool divisorFound = false;
for (int j = 2; j <= 10; j++)
{
if (i % j == 0)
{
if (!divisorFound)
{
cout << " is divisible by ";
}
cout << j << " ";
divisorFound = true;
}
}
if (!divisorFound)
{
cout << " isn't divisible by any numbers";
}
cout << endl;
}
}
return 0;
}

Related

C++ Nested Loops: n*n grid

I need help with this assignment.
I already tried something and I can include the code that I wrote so far.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int i, j, n;
cout << "Please enter the positive integer:";
cin >> n;
if (n < 0) {
cout << "\nEntered integer is not positive! Please enter the positive integer:";
cin >> n;
}
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
if (i == 1 || i == n || j == 1 || j == n) {
cout << setw(n) << "*";
}
else {
cout << setw(n) << " ";
}
}
cout << endl << "\n";
}
return 0;
}
Thanks in advance!
There are several issues in your implementation:
if (n < 0) {
cout << "\nEntered integer is not positive! Please enter the positive integer:";
cin >> n;
}
The above condition will validate the user input only once. If the user enter a negative number more than once, it will not be checked.
cout << endl << "\n";
This will cause two end of lines to be printed, which is not needed.
Here is a working program which does the required job:
int main()
{
int n;
cout << "Please enter the positive integer: ";
cin >> n;
while (n < 0) {
cout << "\nEntered integer is not positive! Please enter the positive integer: ";
cin >> n;
}
for (int i = 0; i <= (n*n); i++) {
for (int j = 0; j <= (n*n); j++) {
if (i == 0 || (i % n == 0) || (j == 0) || (j % n == 0)) {
cout << setw(2) << "*";
} else {
cout << setw(2) << " ";
}
}
cout << '\n';
}
return 0;
}
Here is the output from the program:
Assuming a 1x1 grid looks like this:
****
* *
* *
****
e.g., is not also dependent on the number inputted, I would use the following:
for (int i = 0; i < n * 3 + 1; ++i) {
cout << "*"; //First row with stars
}
cout << endl;
for (int i = 0; i < n; ++i) {
cout << "*"; //First column with stars
for (int j = 0; j < n; ++j) {
cout << " *"; //Empty box and closing star
}
cout << endl;
cout << "*"; //First column with stars
for (int j = 0; j < n; ++j) {
cout << " *"; //Empty box and closing star
}
cout << endl;
for (int j = 0; j < n * 3 + 1; ++j) {
cout << "*"; //Bottom row of box with stars
}
cout << endl;
}
This code is not tested but just quickly typed, it might not work, so be careful using it. Let me know if there are some problems.

Exception handling in c++ how do I implement it here

I just created a program in c++ about adding matrices but I just dont know how to exception handle the part where to choose a number from 1 to 10 so that the user can only choose a number from 1 to 10 and if he puts a wrong input in it shows an error message and is asked to input a number again
#include <iostream>
using namespace std;
int r, c, a[10][10], b[10][10], sum[10][10], i, j;
void matrix(string s) {
cout << "Enter number of rows (between 1 and 10): ";
cin >> r;
cout << "Enter number of columns (between 1 and 10): ";
cin >> c;
}
void storeValues(string s) {
cout << endl << "Enter elements of " << s << " matrix:" << " " << endl;
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j)
{
cout << "Enter element " << i + 1 << j + 1 << " : ";
if (s == "1st") {
cin >> a[i][j];
}
else
cin >> b[i][j];
}
}
void addMatrices() {
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j)
sum[i][j] = a[i][j] + b[i][j];
}
void displayResult() {
cout << endl << "Sum of two matrix is: " << endl;
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j)
{
cout << sum[i][j] << " ";
if (j == c - 1)
cout << endl;
}
}
int main()
{
string s = "1st";
matrix(s);
storeValues(s);
s = "2nd";
storeValues(s);
addMatrices();
displayResult();
return 0;
}
You could easily make a function that handles bounded input for you, something like:
int bounded_input(int lower, int upper, std::string message) {
int r;
bool valid = false;
cout << message << " (between " << lower << " and " << upper << "): ";
do {
cin >> r; // NOTE: You will want to check for invalid input like "three" ...
if (r < lower || r > upper) {
cout << "Invalid, please enter between " << lower << " and " << upper << ":";
} else {
valid = true;
}
} while (!valid);
return r;
}
Then you can simply call this for all of your bounds:
int row_bound = bounded_input(1, 10, "Enter row bounds");

Showing values in an array

I have been coding another programming challenge from a book. It is about asking a user to input n numbers inside an array. Every time the user inputs, the current numbers entered should show up. Numbers less than or equal to zero should not be accepted. I have managed to do the first condition. However, it even shows the "empty" slots. I have tMy code will explain it. Here:
#include <iostream>
using namespace std;
int main() {
int size = 0, input_num [100], i, j;
cout << "Enter an array size: ";
cin >> size;
if (size <= 0) {
while (size <= 0) {
cout << "Enter an array size again: ";
cin >> size;
}
}
cout << "\n\nYou may now enter " << size << " numbers ";
cout << "\n------ ------ ------ ------\n";
for (i = 0; i < size; i++) {
cout << "Enter a number: ";
cin >> input_num [i];
cout << "\nEntered Numbers: ";
for (j = 0; j < size; j++) {
cout << input_num [j] << " " ;
}
cout << "\n";
}
}
In your output section, it should be j <= i, not j < size.
cout << "\nEntered Numbers: ";
for (j = 0; j <= i; j++) {
cout << input_num [j] << " " ;
}
cout << "\n";

Cannot to print in for loop

Below is my code:
#include <iostream>
using namespace std;
int main()
{
int numboftimes, n, sumvalue = 0, strvalue = 0;
cout << "Enter Number of Times You Want The Loop to Run: ";
cin >> numboftimes;
for (n = 1; n <= numboftimes; n++)
{
sumvalue += n;
strvalue += 1;
}
cout << "You ran the for loop: " << numboftimes << " times. \n";
}
I can't get a cout in the for loop to print out an iteration. i.e., 1+2+3+4+5 = 15.
You need to print each iteration in the loop:
for (n = 1; n <= numboftimes; n++) {
sumvalue += n;
strvalue += 1;
cout << "This is the " << numboftimes << " iteration to print" << endl;
cout << "The sum is " << sumvalue << endl;
}
In this way you can print each iteration.
When you are printing the variable numboftimes you are just printing a constant value
for(int n=0; n < numboftimes ; n++)
cout << n << endl;
You put the cout anyways outside the for loop which will output only once, and only the integer numb of times

How do I properly run if statements and do while loops with functions?

I have 5 programs that run perfectly fine individually, but when I combine them I get error messages and won't build. I have a menu to pick which program to run using if statements. Also a do while loop to repeat the programs. I believe it has something to do with the functions because I haven't had this problem before with simple programs. The program should first ask which program you want to run from the menu. It will run that program, then ask if you want to repeat.
I don't know what to try other than what is now in the program. I did take the do while loop out but still had the issue with the if statements.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <fstream>
#include <stdlib.h>
using namespace std;
int main()
{
int choice;
char repeat;
if (repeat == 'm' || 'M'){
cout << "1. Perfect Scores\n"
"2. Larger Than n\n"
"3. Roman Numeral Converter\n"
"4. Monkey Business\n"
"5. Lottery\n"
"6. Exit\n";
cout << "Pick which program you would like to run." << endl;
cin >> choice;
}
else if (choice == 1){ // -----------Perfect Scores------------
do{
int countPerfect(int a[])
{
int i=0;
for(int l=0; l<10; l++)
if(a[1]==100)
i++;
return i;
}
{
int score[10];
for(int i=0; i<10; i++)
{
cout << "Enter score " << i+1 << endl;
cin >> score[i];
while(score[i]<0 || score[i] > 100)
{
cout << "Enter score between 1 and 100." << endl;
cin >> score[i];
}
}
int n = countPerfect(score);
cout << "No of perfect scores: " << n << endl;
cout << "To repeat, press Y. For main menu, press M" << endl;
cin >> repeat;
return 0;
}
}while(repeat == 'Y' || repeat == 'y');
}
// ------------Larger Than n--------------
else if (choice == 2){
do{
void display_greator(int A[], int size, int n)
{
int i;
for(i=0; i< size; i++)
{
if(A[i]>n)
{
cout << A[i] << endl;
}
}
}
int main(void)
{
int i, size;
cout << "Enter the size of your array:"<< endl;
cin >> size;
int N[size];
cout << "Enter a list of " << size << " numbers:" << endl;
for( i=0; i<size; i++)
{
cin >> N[i];
}
int num;
cout << "Enter your number n:" << endl;
cin >> num;
display_greator(N, size, num);
cout << "To repeat, press Y. For main menu, press M" << endl;
cin >> repeat;
}
}while(repeat == 'Y' || repeat == 'y');
}
// ----------------------Roman Numeral Converter------------------
else if (choice == 3){
char repeat;
do{
{
int n;
string romanNumbers[]={"I", "II", "III", "IV", "V", "VI", "VII",
"VIII", "IX", "X", "XI", "XII",
"XIII", "VIX", "XV", "XVI", "XVII", "XVIII", "XIX", "XX"};
cout << "Enter a decimal number or enter 0 to quit." << endl;
cin >> n;
if(n==0)
exit(0);
do
{
cout << "Enter number between 1 and 20" << endl;
cout << "Enter number or enter 0 to quit" << endl;
cin >> n;
} while(n < 0 || n > 20);
{
cout << "Enter decimal equivalent roman number:" << endl;
cout << "Enter a number between 1 and 20:" << endl;
cin >> n;
if(n==0)
exit(0);
cout << "To repeat, press Y. For main menu, press M" << endl;
cin >> repeat;
}
while(n > 0 || n < 20);
return 0;
}
}while(repeat == 'Y' || repeat == 'y');
}
// ---------------Monkey Business--------------------
else if(choice == 4){
do{
const int DAYS = 7;
double getTotalAmountOfFood(int[][DAYS],int);
double getLeastAmountOfFood(int[][DAYS],int, double);
double getGreatestAmountOfFood(int[][DAYS],int, double);
{
const int MONKEYS = 3;
double totalFood, averageFood, leastFood, greatestFood;
int foodInfo[MONKEYS][DAYS];
for(int i= 0; i< MONKEYS; i++)
{
cout << "Enter the food information of the monkey" <<
(i + 1) << ":" << endl;
for(int j = 0; j < DAYS; j++)
{
cout << "Day" << (j + 1) << ":" << endl;
cin >> foodInfo[i][j];
while(foodInfo[i][j] < 0)
{
cout << "Day " << (j+1) << ":" << endl;
cin >> foodInfo[i][j];
}
}
cout << endl;
}
totalFood = getTotalAmountOfFood(foodInfo, MONKEYS);
leastFood = getLeastAmountOfFood(foodInfo, MONKEYS, totalFood);
greatestFood = getGreatestAmountOfFood(foodInfo, MONKEYS, 0);
averageFood = totalFood / DAYS;
cout << "The average amount of food per day for three monkeys(in pounds):"
<< averageFood << endl;
cout << "The least amount of food per week for monkeys(in pounds) is:"
<< leastFood << endl;
cout << "The greatest amount of food per wek for a monkey is(in pounds):"
<< greatestFood << endl;
cout << "To repeat, press Y. For main menu, press M" << endl;
cin >> repeat;
return 0;
}
double getTotalAmountOfFood(int food[][DAYS],int mnks)
{
double total = 0;
for(int i = 0; i < mnks; i++)
{
for(int j = 0; j < DAYS; j++)
{
total += food[i][j];
}
}
return total;
}
double getLeastAmountOfFood(int food[][DAYS], int mnks, double leastAmount)
{
double least = leastAmount;
double weekTotal;
for(int i = 0; i < mnks; i++)
{
weekTotal = 0;
for(int j = 0; j < DAYS; j++)
{
weekTotal += food[i][j];
}
if(least > weekTotal)
least = weekTotal;
}
return least;
}
double getGreatestAmountOfFood(int food[][DAYS], int mnks, double greatestAmount)
{
double greatest = greatestAmount;
double weekTotal;
for(int i = 0; i < mnks; i++)
{
weekTotal = 0;
for(int j = 0; j < DAYS; j++)
{
weekTotal +=food[i][j];
}
if(greatest < weekTotal)
greatest = weekTotal;
}
return greatest;
}
}while(repeat == 'Y' || repeat == 'y');
}
// ----------------Lottery--------------------
else if (choice == 5){
char repeat;
do{
srand(time(NULL));
int winningDigits[5];
int player[5];
int num;
int matchCount = 0;
for (int i = 0; i < 5; i++)
{
winningDigits[i] = rand() % 10;
}
cout << "Enter 5 integers in the range of 0 to 9." << endl;
for(int i = 0; i < 5; i++)
{
cout << "Number #" << (i + 1) << ": " << endl;
cin >> num;
while (num < 0 || num > 9)
{
cout << "Invalid number! It should be in the range of 0 through 9." << endl;
cout << "Number #" << (i + 1) << ": " << endl;
cin >> num;
}
player[i] = num;
}
for (int i = 0; i < 5; i++)
{
if (winningDigits[i] == player[i])
{
matchCount++;
}
}
cout << "Winning digits: " << endl;
for (int i = 0; i < 5; i++)
{
cout << winningDigits[i] << " " << endl;
}
cout << "Player's digits: " << endl;
for (int i = 0; i < 5; i++)
{
cout << player[i] << " " << endl;
}
cout << endl << endl << "Number of digits matched: "
<< matchCount << endl;
cout << "To repeat, press Y. For main menu, press M" << endl;
cin >> repeat;
return 0;
}while(repeat == 'Y' || repeat == 'y');
}
else if (choice == 6)
{cout << "Bye" << endl;}
}
I'm expecting to be able to choose a program to run, repeat it, and repeat the entire program from main menu.
I am not going to point out all errors in your code, they are just too many. You went too fast too far. If you think the complexity of code and the errors it procudes are intimidating you are right. I wrote codes with more lines, but yours is too complicated for me. Go in small steps. Start with something along the line of:
int choose() { return 0; }
void func1() {}
void func2() {}
int main() {
int choice = 0;
while ( choice = choose() ) {
switch(choice) {
case 1 : func1(); break;
case 2 : func2(); break;
}
}
}
Your main function does not have to be more complex than that.
Write this, not more. Make sure it compiles, then in tiny steps fill the gaps, after each step compile, see if it does what you expect and only then continue to put more.
Some problems in your code (partly stolen from comments):
you cannot have more than one main
you cannot define functions inside functions
you cannot start an if statement with else if
int N[size]; is not standard C++ for a non-compile-time-constant size. Use std::vector instead
see here why using namespace std is considered bad practice
if (repeat == 'm' || 'M') is not doing what you expect, it should be if (repeat == 'm' || repeat == 'M'). In yours 'M' is taken as a bool which is always true (because it isnt 0).
make sure to initialize variables. Using variables that are not initialized causes undefined behaviour.
please next time reduce your code to a mcve and try to concentrate on a single problem, also include the error in the question
I cannot help myself than to point that for each single problem there are duplicate questions, which brings me back to: Don't do too many things at once. Fixing 100 errors at once is extremely difficult, fixing 1 error is doable.
last but not least, pay attention to compiler errors and warnings while you write the code (again: not after you wrote several pages, but after each single line)