Two Dimensional Array outputs one continuous row - c++

Hello I am new to C++ and am having trouble understanding why this two dimensional array is only producing one row and many columns. It reads the correct information but does not output it with the correct columns and rows.
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
char pat [9][9]= {'$','$','$','$','$','$','$','$','$',
'$','$','$','$','$','$','$','$','$',
'$','$','$','$','$','$','$','$','$',
'$','$','$','$','$','$','$','$','$',
'$','$','$','$','$','$','$','$','$',
'$','$','$','$','$','$','$','$','$',
'$','$','$','$','$','$','$','$','$',
'$','$','$','$','$','$','$','$','$',
'$','$','$','$','$','$','$','$','$'}; // 9x9 matrix
int main ()
{
int pattern,
dimensions;
do
{
cout << "1) Display Pattern 1" << endl; //menu selections
cout << "2) Display Pattern 2" << endl;
cout << "3) Display Pattern 3" << endl;
cout << "4) Display Pattern 4" << endl;
cout << "5) Exit Program" << endl << endl;
cout << "Please select an option. ";
cin >> pattern;
if (pattern == 1)
{
system("cls");
do
{
cout << "Note: Choose a number between 1 and 10." << endl;
cout << "Choose a number ";
cin >> dimensions;
cout << endl;
if (dimensions > 1 && dimensions < 10)
/* based on the user's input for dimension
it will output a square i.e. 2x2, 3x3, 4x4 etc */
{
cout << "True!" << endl;
for (int rows = 0; rows < dimensions; rows++)
{
for (int cols = 0; cols < dimensions; cols++)
cout << pat[cols][rows];
}
}
else
{
cout << "Error! Number is not between this set!" << endl;
Sleep(3000);
cout << endl;
}
}
while (pattern == 1);
}
else if (pattern == 2)
{
system("cls");
do
{
cout << "Note: Choose a number between 1 and 10." << endl;
cout << "Choose a number ";
cin >> dimensions;
cout << endl;
if (dimensions > 1 && dimensions < 10)
{
cout << "True!";
}
else
{
cout << "Error! Number is not between this set!" << endl;
Sleep(3000);
cout << endl;
}
}
while (pattern == 2);
}
else if (pattern == 3)
{
system("cls");
do
{
cout << "Note: Choose a number between 1 and 10." << endl;
cout << "Choose a number ";
cin >> dimensions;
cout << endl;
if (dimensions > 1 && dimensions < 10)
{
cout << "True!";
}
else
{
cout << "Error! Number is not between this set!" << endl;
Sleep(3000);
cout << endl;
}
}
while (pattern == 3);
}
else if (pattern == 4)
{
system("cls");
do
{
cout << "Note: Choose a number between 1 and 10." << endl;
cout << "Choose a number ";
cin >> dimensions;
cout << endl;
if (dimensions > 1 && dimensions < 10)
{
cout << "True!";
}
else
{
cout << "Error! Number is not between this set!" << endl;
Sleep(3000);
cout << endl;
}
}
while (pattern == 4);
}
else if (pattern == 5)
{
return 0;
}
else
{
cout << "Please input a valid entry." << endl << endl;
Sleep(3000);
cout << endl;
}
}
while (pattern != 5);
}

When you're printing the array:
for (int rows = 0; rows < dimensions; rows++)
{
for (int cols = 0; cols < dimensions; cols++)
cout << pat[cols][rows]
}
You never print a new line, so it's all on one row. You want something like this:
for (int rows = 0; rows < dimensions; rows++)
{
for (int cols = 0; cols < dimensions; cols++)
cout << pat[cols][rows]
cout << endl;
}

If you want to initialize a multidimensional array, you have to do it like so:
int multiarray[3][3] =
{
{1,2,3},
{4,5,6},
{7,8,9}
};
Using nested braces to separate the dimensions.
After this to output it the way you want you do it as such:
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
std::cout << multiarray[i][j];
}
std::cout << std::endl;
}

Related

Trying to multiply matrices. Getting absurd result

#include <iostream>
#include <malloc.h>
using namespace std;
int main()
{
int r,c,r2,c2;
cout << "Enter the number of rows:- \n";
cin >> r;
cout << "\n" <<"Enter the number of columns: \n";
cin >> c;
int **mat;
int **mat2;
mat=(int**)malloc(sizeof(int)*r); // allocating memory to a row
for (int i=0;i<r;i++)
{
*(mat+i)=(int*)malloc(sizeof(int)*c); /* allocating memory to
columns in rows ( double pointers ) */
}
cout << "\n\n" << "Please enter the 1st matrix of order:- " << r << 'x'
<< c<< endl;
for (int i=0;i<r;i++)
{ for (int j=0;j<c;j++)
{
cin >> *(*(mat+i)+j);
cout << endl;
}
}
cout << "Enter the number of rows(2nd):- \n";
cin >> r2;
cout << "\n" <<"Enter the number of columns(2nd): \n";
cin >> c2;
mat2=(int**)malloc(sizeof(int)*r2);
for (int i=0;i<r2;i++)
{
*(mat2+i)=(int*)malloc(sizeof(int)*c2);
}
cout << "\n\n" << "Please enter the 2nd matrix of order:- " << r2 << 'x'
<< c2 <<endl;
for (int i=0;i<r2;i++)
{
for (int j=0;j<c2;j++)
{
cin >> *(*(mat2+i)+j);
cout << endl;
}
}
cout <<"\n\n\n" <<"The 1st matrix you entered is:- \n";
for (int i=0;i<r;i++)
{ for (int j=0;j<c;j++)
{
cout << *(*(mat+i)+j) << '\t';
}
cout << endl;
}
cout << "\n\n" << "The second matrix you entered is:- \n";
for (int i=0;i<r2;i++)
{ for (int j=0;j<c2;j++)
{
cout << *(*(mat2+i)+j) << '\t';
}
cout << endl;
}
int **mat4;
mat4=(int**)malloc(sizeof(int)*r);
for (int i=0;i<r;i++)
{
*(mat4+i)=(int*)malloc(sizeof(int)*c2);
}
if (c!=r2)
{
cout << "\n\n These two matrices cannot be multiplied as number of
columns("<< c<< ")of 1st matrix \nis not equal to number of
rows("<< r2<< ") of second matrix.";
}
if( c==r2)
{
for (int i=0;i<r;i++)
{
for (int z=0;z<c2;z++)
{
for (int j1=0;j1<r2;j1++)
{
mat4[i][z]+= mat[i][j1] * mat2[j1][z]; /* logic to
multiply two matrices */
}
}
}
for (int i=0;i<r;i++)
{
for (int j=0;j<c2;j++)
{
cout << mat4[i][j] << '\t';
}
cout << endl;
}
}
return (1);
}
The problem occurs when I enter a 2x2 and a 2x3 matrix or any combination with c2=c+1. I get random large number in the output. Else if I enter any other combination of number of rows and columns, it works just fine. For example- If I put r2=3 and c2=4 , I'll get absurd values at column 1 and 3 no matter what input I do.

Nested For - Loops to create multiplication table C++

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

How to score yahtzee in c++

I am writing a yahtzee game for my c++ programming class. One of my difficulties I have ran into is the scoring system for different categories. I think I have figured out how to do it for adding 1s, 2s etc but I do not know how to have the program determine when a 3 of a kind, 4 of a kind, etc has been rolled. Here is my code so far.
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//Declare variables
int players;
int turn = 1;
vector<string> names;
string playerName;
int dice[5];
int finalScore = 0;
char reroll[5];
char rollDice;
int tries = 1;
const int DICE = 5;
int roll[DICE];
int scorecard;
int scoreThisTurn(int scorecard);
int turnScore = 0;
//Introduction, get number of players.
cout << "Hello, welcome to Yahtzee! How many players are there?" << endl;
cin >> players;
if (players > 4) {
cout << "Sorry, the maximum number of players is 4." << endl;
cout << "How many players are there?" << endl;
cin >> players;
}
//Get player names
string getNames();
for (int i = 0; i < players; i++) {
cout << "Hello player " << i + 1 << ", please enter your name" << endl;
cin >> playerName;
names.push_back(playerName);
}
srand(time(NULL)); //random seed
cout << "Welcome to Yahtzee!\n";
while (turn <= 13) { //roll dice
cout << "Press 'r' to roll" << endl;
cin >> rollDice;
if (rollDice == 'r') {
for (int i = 0; i < DICE; i++) {
roll[i] = rand() % 6 + 1;
}
}
cout << "You rolled: " << roll[0] << ", " << roll[1] << ", " <<
roll[2] << ", " << roll[3] << ", " << roll[4] << endl;
cout << "Type y to reroll or n to keep. For example yynnn would keep the first three dice" << endl;
cin >> reroll[0] >> reroll[1] >> reroll[2] >> reroll[3] >> reroll[4];
for (int i = 0; i < DICE; i++) {
if (reroll[i] == 'y') {
roll[i] = rand() % 6 + 1;
}
else if (reroll[i] == 'n') {
roll[i];
}
else cout << "Sorry you entered an invalid letter." << endl;
}
cout << "Your second roll is: " << roll[0] << ", " << roll[1] << ", " <<
roll[2] << ", " << roll[3] << ", " << roll[4] << endl;
cout << "Type y to reroll or n to keep. For example yynnn would keep the first three dice" << endl;
cin >> reroll[0] >> reroll[1] >> reroll[2] >> reroll[3] >> reroll[4];
for (int i = 0; i < DICE; i++) {
if (reroll[i] == 'y') {
roll[i] = rand() % 6 + 1;
}
else if (reroll[i] == 'n') {
roll[i];
}
else cout << "Sorry you entered an invalid letter." << endl;
}
cout << "Your third roll is: " << roll[0] << ", " << roll[1] << ", " <<
roll[2] << ", " << roll[3] << ", " << roll[4] << endl;
//displays scorecard categories
cout << "Which category would you like to score this in" << endl;
cout << "1 - ones: " << endl;
cout << "2 - twos: " << endl;
cout << "3 - threes: " << endl;
cout << "4 - fours: " << endl;
cout << "5 - fives: " << endl;
cout << "6 - sixes: " << endl;
cout << "7 - 3 of a kind: " << endl;
cout << "8 - 4 of a kind: " << endl;
cout << "9 - small straight: " << endl;
cout << "10 - large straight: " << endl;
cout << "11 - full house: " << endl;
cout << "12 - yahtzee: " << endl;
cout << "13 - chance: " << endl;
//asks player to choose where to score
cout << "\nEnter 1-14 to choose a category." << endl;
cin >> scorecard;
//assigns points
for (int i = 0; i < DICE; i++) {
turnScore = 0;
if (scorecard == 1) {
if (roll[i] == 1) {
turnScore = turnScore + 1;
}
}
if (scorecard == 2) {
if (roll[i] == 2) {
turnScore = turnScore + 2;
}
}
if (scorecard == 3) {
if (roll[i] == 3) {
turnScore = turnScore + 3;
}
}
if (scorecard == 4) {
if (roll[i] == 4) {
turnScore = turnScore + 4;
}
}
if (scorecard == 5) {
if (roll[i] == 5) {
turnScore = turnScore + 5;
}
}
if (scorecard == 6) {
if (roll[i] == 6) {
turnScore = turnScore + 6;
}
if (scorecard == 7) {
if (roll[i] == 2) {
turnScore = turnScore + 2;
}
}
}
cout << scorecard << endl;
turn++;
}
system("pause");
return 0;
}
As you can see I've set up the scoring for the first 6 categories but don't know how to proceed.
I do not know how to have the program determine when a 3 of a kind, 4 of a kind, etc has been rolled.
Create a variable to help you keep track of the number of dice that have a given number.
int diceCount[DICE] = {0};
and fill up the array with:
for (int i = 0; i < DICE; i++) {
diceCount[roll[i-1]]++
}
Create helper functions to determine whether five, four, or three of a kind have been thrown.
int getNOfAKind(int diceCount[], int N)
{
// This will need moving DICE out of `main`
// making it a global variable.
for ( int i = 0; i < DICE; ++i )
{
if (diceCount[i] == N )
{
return i+1;
}
}
return -1;
}
int getFiveOfAKind(int diceCount[])
{
return getNOfAKind(diceCount, 5);
}
int getFourOfAKind(int diceCount[])
{
return getNOfAKind(diceCount, 4);
}
int getThreeOfAKind(int diceCount[])
{
return getNOfAKind(diceCount, 3);
}
and use it as:
int fiveCount = getFiveOfAKind(diceCount);
if ( fiveCount != -1 )
{
}
int fourCount = getFourOfAKind(diceCount);
if ( fourCount != -1 )
{
}
int threeCount = getThreeOfAKind(diceCount);
if ( threeCount != -1 )
{
}

Access Violation Issue with Bubble Sorting/Duplicate Arrays

This program seems to work fine until it goes to display the data after the sort function, it will display by destination but it bypasses displaying by airline. Then it gives the access violation window and I'm not 100% sure on what it even means. If anybody could explain and help that would be much appreciated.
#include <iostream>
#include <string>
using namespace std;
double flight_number[3], number_passengers[3], max_records, max_pass, min_pass;
string airline_name[3], destination[3], duplicate[3];
char reply, swapping;
int row, index[3];
void setup();
void load_arrays();
void display_airline();
void display_destination();
void sort();
int main()
{
setup();
load_arrays();
display_airline();
display_destination();
system("pause");
return 0;
}
void setup()
{
max_records = 3;
max_pass = 275;
min_pass = 50;
}
void load_arrays()
{
for (row = 0; row < max_records; row++)
{
cout << "Charter Number " << row << endl << endl;
cout << "Please enter..." << endl;
cout << "Airline Name----> ";
cin >> airline_name[row];
cout << endl;
cout << "Flight Number----> ";
cin >> flight_number[row];
cout << endl;
cout << "Destination----> ";
cin >> destination[row];
cout << endl;
cout << "Passenger Load----> ";
cin >> number_passengers[row];
cout << endl;
while (number_passengers[row] < min_pass || number_passengers[row] > max_pass)
{
cout << "You have entered an invalid amount of passengers." << endl;
cout << "There must be between 50 and 275 passengers. > ";
cin >> number_passengers[row];
cout << endl;
}
}
}
void display_airline()
{
system("cls");
for (row = 0; row < max_records; row++)
{
duplicate[row] = airline_name[row];
}
sort();
cout << "Airline" << " Flight" << " Destination" << " Passenger" << endl;
cout << "Name" << " Number" << " Load" << endl;
for (row = 0; row < max_records; row++)
{
cout << airline_name[index[row]] << " " << flight_number[index[row]] << " " << destination[index[row]] << " " << number_passengers[index[row]];
cout << endl;
}
}
void display_destination()
{
system("cls");
for (row = 0; row < max_records; row++)
{
duplicate[row] = destination[row];
}
sort();
cout << "Destination" << " Flight" << " Flight" << " Passenger" << endl;
cout << " Name" << " Number" << " Load" << endl;
for (row = 0; row < max_records; row++)
{
cout << destination[index[row]] << " " << airline_name[index[row]] << " " << flight_number[index[row]] << " " << number_passengers[index[row]];
cout << endl;
}
}
void sort()
{
for (row = 0; row < max_records; row++)
{
index[row] = row;
}
swapping = 'Y';
while (swapping == 'Y')
{
swapping = 'N';
for (row = 0; row < max_records; row++)
{
if (duplicate[row] > duplicate[row + 1])
{
swap (duplicate[row], duplicate[row + 1]);
swap (index[row], index[row + 1]);
swapping = 'Y';
}
}
}
}
also this is the full violation error: Unhandled exception at 0x009984F6 in Program 6.exe: 0xC0000005: Access violation reading location 0x03947188.
for (row = 0; row < max_records; row++)
if (duplicate[row] > duplicate[row + 1]).
What's duplicate[row+1] when row==3? You want the sort to go to max_records-1 since it works on pairs of elements rather than individual elements.

How to get rid of goto and flip in the following program

How to get rid of goto statement in this program and end the flip:>>>?
int main()
{
int array[10];
int sum = 0;
int desending;
int mul = 1;
float avg = 10;
int option;
do
{
flip1:
cout << "\n\t\t------------------------------------------------" << endl;
cout << "\t\tlllllllll Menue lllllllllll" << endl;
cout << "\t\tlllllllll 1. Array Basics lllllllllll" << endl;
cout << "\t\tlllllllll 2. Searching Array lllllllllll" << endl;
cout << "\t\tlllllllll 3. Sorting Array lllllllllll" << endl;
cout << "\t\tlllllllll 4. Exit lllllllllll" << endl;
cout << "\t\t------------------------------------------------\n" << endl;
cout << "Please select an option" << endl;
cin >> option;
system("cls");
flip2:
if (option == 1)
{
int h = 1;
int i;
for (i = 0; i < 10; i++)
{
cout << h << " Enter the Numbers ";
cin >> array[i];
sum = sum + array[i];
mul = mul*array[i];
h++;
}
system("cls");
for (int j = 0; j < 10; j++)
{
cout << "Given numbers" << j << " = " << array[j] << "\n";
}
avg = sum / avg;
int max = array[0];
int min = array[0];
for (int i = 0; i < 10; i++)
{
if (array[i] > max)
{
max = array[i];
}
else if (array[i] < min)
{
min = array[i];
}
}
cout << "\nSum of the Numbers= 4" << sum << endl;
cout << "\nProduct of the Numbers is = " << mul << endl;
cout << "\nThe Avg of Numbers is = " << avg << endl;
cout << "\nmaximum of the Numbers is = " << max << endl;
cout << "\nminimum of the Numbers is = " << min << endl;
}
else if (option == 2)
{
int array[10], o, index = -1;
cout << "enter the elements of array" << endl;
for (o = 0; o < 10; o++)
{
cin >> array[o];
}
system("cls");
int p;
cout << "enter value to find" << endl;
cin >> p;
for (int c = 0; c < 10; c++)
{
if (array[c] == p)
index = c;
}
system("cls");
if (index == -1)
{
cout << "no value found" << endl;
}
else
cout << "Value found at\t" << index << endl;
}
else if (option == 3)
{
system("cls");
int a[10], r, t, temp;
cout << "Enter the array elements: " << endl;
for (r = 0; r<10; ++r)
cin >> a[r];
system("cls");
for (r = 0; r<10; ++r)
for (t = 0; t<9; t++)
if (a[r]<a[t])
{
temp = a[r];
a[r] = a[t];
a[t] = temp;
}
cout << "Array after sorting: " << endl;
for (r = 0; r<10; r++)
cout << a[r] << "\t ";
}
cout << "\nplease select an option\n" << endl;
cout << "press m for main menue" << endl;
cout << "press r for repeat" << endl;
cout << "press e for exit" << endl;
char q;
cin >> q;
if (q == 'm')
{
system("cls");
goto flip1;
}
if (q == 'r')
{
system("cls");
goto flip2;
}
if (q == 'e')
{
return 0;
}
} while (option != 4);
return 0;
}
You can refer the below code.
Before entering the loop.
cout << "\n\t\t------------------------------------------------" << endl;
cout << "\t\tlllllllll Menue lllllllllll" << endl;
cout << "\t\tlllllllll 1. Array Basics lllllllllll" << endl;
cout << "\t\tlllllllll 2. Searching Array lllllllllll" << endl;
cout << "\t\tlllllllll 3. Sorting Array lllllllllll" << endl;
cout << "\t\tlllllllll 4. Exit lllllllllll" << endl;
cout << "\t\t------------------------------------------------\n" << endl;
cout << "Please select an option" << endl;
cin >> option;
system("cls");
do {
if (option == 1)
{
int h = 1;
int i;
for (i = 0; i < 10; i++)
{
/* All text as same */
At the end: change
if (q == 'm')
{
system("cls");
goto flip1;
}
if (q == 'r')
{
system("cls");
goto flip2;
}
if (q == 'e')
{
return 0;
}
To.
if (q == 'e')
{
return 0;
}
system("cls");
if (q == 'm')
{
cout << "\n\t\t------------------------------------------------" << endl;
cout << "\t\tlllllllll Menue lllllllllll" << endl;
cout << "\t\tlllllllll 1. Array Basics lllllllllll" << endl;
cout << "\t\tlllllllll 2. Searching Array lllllllllll" << endl;
cout << "\t\tlllllllll 3. Sorting Array lllllllllll" << endl;
cout << "\t\tlllllllll 4. Exit lllllllllll" << endl;
cout << "\t\t------------------------------------------------\n" << endl;
cout << "Please select an option" << endl;
cin >> option;
system("cls");
}
PS: You can also create a function that prints the menu, get input from user and return the same.
If you divide your code into chunks of cohesive functionality, you can put them into their own functions and the main function can be much simpler. Here's my recommendation:
#include <iostream>
#include <cstdlib>
using namespace std;
int getOption1()
{
int option;
cout << "\n\t\t------------------------------------------------" << endl;
cout << "\t\tlllllllll Menue lllllllllll" << endl;
cout << "\t\tlllllllll 1. Array Basics lllllllllll" << endl;
cout << "\t\tlllllllll 2. Searching Array lllllllllll" << endl;
cout << "\t\tlllllllll 3. Sorting Array lllllllllll" << endl;
cout << "\t\tlllllllll 4. Exit lllllllllll" << endl;
cout << "\t\t------------------------------------------------\n" << endl;
cout << "Please select an option" << endl;
cin >> option;
system("cls");
return option;
}
char getOption2()
{
char option;
cout << "\nplease select an option\n" << endl;
cout << "press m for main menue" << endl;
cout << "press r for repeat" << endl;
cout << "press e for exit" << endl;
cin >> option;
return option;
}
void doArrayBasics()
{
int array[10];
int sum = 0;
float avg = 10;
int mul = 1;
int h = 1;
int i;
for (i = 0; i < 10; i++)
{
cout << h << " Enter the Numbers ";
cin >> array[i];
sum = sum + array[i];
mul = mul*array[i];
h++;
}
system("cls");
for (int j = 0; j < 10; j++)
{
cout << "Given numbers" << j << " = " << array[j] << "\n";
}
avg = sum / avg;
int max = array[0];
int min = array[0];
for (int i = 0; i < 10; i++)
{
if (array[i] > max)
{
max = array[i];
}
else if (array[i] < min)
{
min = array[i];
}
}
cout << "\nSum of the Numbers= 4" << sum << endl;
cout << "\nProduct of the Numbers is = " << mul << endl;
cout << "\nThe Avg of Numbers is = " << avg << endl;
cout << "\nmaximum of the Numbers is = " << max << endl;
cout << "\nminimum of the Numbers is = " << min << endl;
}
void doArraySearching()
{
int array[10];
int o;
int index = -1;
cout << "enter the elements of array" << endl;
for (o = 0; o < 10; o++)
{
cin >> array[o];
}
system("cls");
int p;
cout << "enter value to find" << endl;
cin >> p;
for (int c = 0; c < 10; c++)
{
if (array[c] == p)
index = c;
}
system("cls");
if (index == -1)
{
cout << "no value found" << endl;
}
else
cout << "Value found at\t" << index << endl;
}
void doArraySorting()
{
system("cls");
int a[10];
int r;
int t;
int temp;
cout << "Enter the array elements: " << endl;
for (r = 0; r<10; ++r)
cin >> a[r];
system("cls");
for (r = 0; r<10; ++r)
for (t = 0; t<9; t++)
if (a[r]<a[t])
{
temp = a[r];
a[r] = a[t];
a[t] = temp;
}
cout << "Array after sorting: " << endl;
for (r = 0; r<10; r++)
cout << a[r] << "\t ";
}
int main()
{
int option1;
char option2 = 'r';
do
{
if ( option2 == 'r' )
{
option1 = getOption1();
}
switch (option1)
{
case 1:
doArrayBasics();
break;
case 2:
doArraySearching();
break;
case 3:
doArraySorting();
break;
case 4:
break;
default:
cout << "Invalid option " << option1 << endl;
}
if ( option1 != 4 )
{
option2 = getOption2();
}
} while (option1 != 4 && option2 != 'e' );
return 0;
}
You can use an inner loop to remove all gotos.
Remove flip1:, change flip2: to do {. The loop should begin like that:
do
{
cout << "\n\t\t------------------------------------------------" << endl;
cout << "\t\tlllllllll Menue lllllllllll" << endl;
cout << "\t\tlllllllll 1. Array Basics lllllllllll" << endl;
cout << "\t\tlllllllll 2. Searching Array lllllllllll" << endl;
cout << "\t\tlllllllll 3. Sorting Array lllllllllll" << endl;
cout << "\t\tlllllllll 4. Exit lllllllllll" << endl;
cout << "\t\t------------------------------------------------\n" << endl;
cout << "Please select an option" << endl;
cin >> option;
system("cls");
do
{
if (option == 1)
{
At the end of the loop, change:
if (q == 'm')
{
system("cls");
goto flip1;
}
if (q == 'r')
{
system("cls");
goto flip2;
}
if (q == 'e')
{
return 0;
}
to :
if (q == 'e')
{
return 0;
}
system("cls");
} while (q == 'r');
Breaking your code into functions will also make it more readable but is not mandatory to remove gotos.
caveat: the following code not tested
int main()
{
int array[10];
int sum = 0;
int desending;
int mul = 1;
float avg = 10;
int option;
int done = 0;
int looping = 1;
while( !done )
{
cout << "\n\t\t------------------------------------------------" << endl;
cout << "\t\tlllllllll Menue lllllllllll" << endl;
cout << "\t\tlllllllll 1. Array Basics lllllllllll" << endl;
cout << "\t\tlllllllll 2. Searching Array lllllllllll" << endl;
cout << "\t\tlllllllll 3. Sorting Array lllllllllll" << endl;
cout << "\t\tlllllllll 4. Exit lllllllllll" << endl;
cout << "\t\t------------------------------------------------\n" << endl;
cout << "Please select an option" << endl;
cin >> option;
system("cls");
while( looping )
{
looping = 0;
switch( option )
{
case 1:
int h = 1;
int i;
for (i = 0; i < 10; i++)
{
cout << h << " Enter the Numbers ";
cin >> array[i];
sum = sum + array[i];
mul = mul*array[i];
h++;
}
system("cls");
for (int j = 0; j < 10; j++)
{
cout << "Given numbers" << j << " = " << array[j] << "\n";
}
avg = sum / avg;
int max = array[0];
int min = array[0];
for (int i = 0; i < 10; i++)
{
if (array[i] > max)
{
max = array[i];
}
else if (array[i] < min)
{
min = array[i];
}
}
cout << "\nSum of the Numbers= 4" << sum << endl;
cout << "\nProduct of the Numbers is = " << mul << endl;
cout << "\nThe Avg of Numbers is = " << avg << endl;
cout << "\nmaximum of the Numbers is = " << max << endl;
cout << "\nminimum of the Numbers is = " << min << endl;
break;
case 2:
int array[10], o, index = -1;
cout << "enter the elements of array" << endl;
for (o = 0; o < 10; o++)
{
cin >> array[o];
}
system("cls");
int p;
cout << "enter value to find" << endl;
cin >> p;
for (int c = 0; c < 10; c++)
{
if (array[c] == p)
index = c;
}
system("cls");
if (index == -1)
{
cout << "no value found" << endl;
}
else
cout << "Value found at\t" << index << endl;
break;
case 3:
system("cls");
int a[10], r, t, temp;
cout << "Enter the array elements: " << endl;
for (r = 0; r<10; ++r)
cin >> a[r];
system("cls");
for (r = 0; r<10; ++r)
{
for (t = 0; t<9; t++)
{
if (a[r]<a[t])
{
temp = a[r];
a[r] = a[t];
a[t] = temp;
}
}
}
cout << "Array after sorting: " << endl;
for (r = 0; r<10; r++)
cout << a[r] << "\t ";
break;
case 4:
done = 1;
break;
default:
cout << "\nplease select an option\n" << endl;
cout << "press m for main menue" << endl;
cout << "press r for repeat" << endl;
cout << "press e for exit" << endl;
char q;
cin >> q;
switch( q )
{
case 'm':
system("cls");
// looping already set = 0
break;
case 'r':
system("cls");
looping = 1;
break;
case 'e':
done = 1;
break;
default:
break;
} // end switch
break;
} // end switch
} // end while looping
} // end while not done
return 0;
} // end function: main