about arrays in c++ - c++

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!

Related

Finding multidimensional array pattern for every odd j index

Ok, so I'm trying to insert a space character for every odd number of j (including 0), the problem is that 0 counts as an even number (I want it to count as odd so a space character can be placed) and I'm struggling with how to figure out a solution other than playing with odd or even j. The goal is to make every element in the array have a letter and have a space character for the next index. This function is responsible for filling up the array.
void createBoard(char arr [DIM][DIM], int size){
//ASCII number for capital A
char x = 65;
for(int i = 0; i<size; i++){
for(int j = 0; j<size; j++){
if(j%2==0){
arr[i][j] = x++;
}
else{
arr[i][j] = 32;
}
cout << "Element at x[" << i << "][" << j << "]: ";
cout << arr[i][j] << endl;
}
}
}
This is function main.
const int DIM = 7;
int main()
{
char arr [DIM][DIM];
int bsize;
char answer;
do{
cout << "Please enter the size of the board [1-7]: ";
cin >> bsize;
if(!cin){
cout << endl << "Invalid entry";
break;
}
if (bsize<=DIM && bsize>=1){
createBoard(arr,bsize);
}
else{
cout << endl << "Invalid size";
cout << endl << "Do you want to try again [y-n]?: ";
cin >> answer;
}
// As long as the answer is 'y' (in upper or lower case), keep looping
}while(answer=='Y'||answer=='y');
return 0;
}

Is there a way to clear empty array in c++ , check code below for explanation

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;

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)

Counting via For Loops

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

Resizing a dynamic bitset in C++ to a length entered by the user

This C++ program asks the user to enter the length of the bit sequence he/she will enter next. This length variable is named xx, it is of type int. I am using three dynamic bitset with the initial size of 5, these are inpSeq, operSeq and bit. I am resizing the bitsets by
inpSeq.resize(xx); for example. When compiling the program, a very big list of errors appears, I feel I can't paste it here. but I am sure that these errors are all related to this variable xx, the code was compiled fine before using it as a variable to resize the bitset. What is wrong with the way I am resizing the bitset? And can I make the bitsets of the size of inpSeq without asking the user to enter the length of inpSeq bitset?
#include <iostream> //Standard library.
#include <boost/dynamic_bitset.hpp> //Library for 10 handling.
#include <vector> //Variable size array.
#include <algorithm> //We use sorting from it.
using namespace std;
int main()
{
int y = 0;
int turnCount = 0;
int count1 = 0, count0 = 0;
int xx = 0;
boost::dynamic_bitset<> inpSeq(5);
int polyLoc;
boost::dynamic_bitset<> operSeq(5);
boost::dynamic_bitset<> bit(5);
vector <int> xorArray;
vector <int> keyReg;
cout << "What is the legnth of the sequence?";
cin << xx;
inpSeq.resize(xx);
operSeq.resize(xx);
bit.resize(xx);
cout << "Enter a bit sequence: \n";
cin >> inpSeq;
int seq_end = inpSeq.size() - 1;
cout << "Enter polynomial:";
cin >> polyLoc;
while(polyLoc>0)
{
xorArray.push_back(polyLoc%10);
polyLoc/=10;
}
cout << "xorArray is: ";
for ( unsigned int i = 0; i < xorArray.size(); i++)
{
cout << xorArray[i] << " ";
}
sort(xorArray.rbegin(), xorArray.rend());
cout << "\n";
operSeq = inpSeq;
keyReg.push_back(inpSeq[0]);
int x = xorArray[0];
cout << "x is: " << x << "\n";
for ( unsigned int i = 0; i < xorArray.size(); i++)
{
cout << xorArray[i] << "\n";
}
cout << "bit 3 of initial " << bit[seq_end] << "\n";
do {
for (unsigned int r = 1; r < xorArray.size(); r++)
{
bit[seq_end] = operSeq[x];
y = xorArray[r];
bit[seq_end] = bit[seq_end] ^ operSeq[y];
}
operSeq >>= 1;
operSeq[seq_end] = bit[seq_end];
keyReg.push_back(operSeq[0]);
turnCount ++;
cout << "--\n";
}
while ((operSeq != inpSeq) && (turnCount < 20));
cout << "Generated key is: ";
for (unsigned int k = 0; k < keyReg.size(); k++)
{
cout << keyReg[k];
}
cout << "\n";
cout << "Bit 1 positions: ";
for ( unsigned int g = 0; g < xorArray.size(); g++)
{
cout << xorArray[g];
}
cout << "\n";
cout << "Key length is: " << keyReg.size();
cout << "\n";
for ( unsigned int i = 0; i < keyReg.size(); i++)
{
if (keyReg[i]==1)
{
count1++;
}
else {
count0++;
}
}
cout << "Number of 0's: " << count0 << "\n";
cout << "Number of 1's: " << count1 << "\n";
if ( keyReg.size()%2 ==0)
{
cout << "key length is even. \n";
if (count1==count0)
{
cout << "Key is perfect! \n";
}
else {
cout << "Key is not perfect! \n";
}
}
else
{
cout << "key length is odd. \n";
if ((count1==count0+1) || (count0==count1+1))
{
cout << "Key is perfect! \n";
}
else {
cout << "Key is not perfect! \n";
}
}
cin.get();
}