What's wrong with the coding in my array? [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
This is code I've written for an array that has 14 slots, each should have 4 in it except for the 6th and 13th slot, which are reverted back to 0. However, it doesn't compile. Does anyone know what I did wrong here?
using namespace std;
#include <iostream>
const int MAX = 14;
int main ()
{
void printArray ();
system ("pause");
return 0;
}
void startArray (int beadArray[MAX])
{
for(int i=0; i<MAX; i++)
{
beadArray[i]=4;
}
beadArray[6]=0;
beadArray[13]=0;
}
//**********************************************//
void printArray ()
{
startArray (int beadArray[MAX]);
for(int i=0; i<MAX; i++)
{
cout<<i;
}
}

startArray (int beadArray[MAX]);
You're trying to declare beadArray and use it in one step. You should declare it before using it:
int beadArray[MAX];
startArray (beadArray);
You also have a multitude of other problems:
using namespace std; has no effect because <iostream> hasn't been #included yet. You shouldn't use a global using namespace std; as well.
system ("PAUSE"); should be replaced. I personally use:
cin.sync();
cin.get();
the compiler doesn't know about the functions when in main(). Before main(), you should put prototypes:
void printArray();
void startArray (int []);
in main() you say void printArray();. When calling a function, just use the function name and arguments:
printArray();
in printArray(), you're outputting i instead of beadArray [i]. There's also no spacing.
global constants are a bad thing to use.
The fixed code I had looks like this:
#include <iostream>
const int MAX = 14;
void startArray (int (&beadArray)[MAX]);
void printArray();
int main ()
{
printArray ();
std::cout << "\n\nPress enter to continue...";
std::cin.sync();
std::cin.get();
return 0;
}
void startArray (int (&beadArray)[MAX])
{
for(int i=0; i<MAX; ++i)
beadArray[i]=4;
beadArray[6]=0;
beadArray[13]=0;
}
void printArray ()
{
int beadArray[MAX];
startArray (beadArray);
for(int i=0; i<MAX; i++)
std::cout << beadArray[i] << ' ';
}
I did leave the constant in, but there's lots you can do to replace it.

Some corrected mistakes :
declare your array outside startArray() function call if you want to use it outsite.
pass the array as reference if you want to modify it
cout << beadArray[i] instead of cout << i
.
using namespace std;
#include <iostream>
const int MAX = 14;
int main ()
{
void printArray ();
system ("pause");
return 0;
}
void startArray (int &beadArray[MAX])
{
for(int i=0; i<MAX; i++)
beadArray[i]=4;
beadArray[6]=0;
beadArray[13]=0;
}
//**********************************************//
void printArray ()
{
int beadArray[MAX];
startArray (beadArray);
for(int i=0; i<MAX; i++)
cout<<beadArray[i];
}

Related

C++ - Passing 2D array to function [duplicate]

This question already has answers here:
Passing a 2D array to a C++ function
(17 answers)
Variable length arrays (VLA) in C and C++
(5 answers)
Closed 3 months ago.
I am trying to pass a 2D array to a function but I am failing to do so. There is no problem with passing 1D array. How can I do this?
#include <iostream>
using namespace std;
void DisplayBoard(int matrix[],int n) // Prints out the given array.
{
for (int j = 0; j < n; j++)
{
cout << matrix[j];
}
}
int main()
{
int n,m;
cin>>n;
//int matrix[n]={};
DisplayBoard(matrix,n);
return 0;
}
i think you want to input index number (n) from user and then input array object from user too
i complete your code like this :
#include <iostream>
using namespace std;
void DisplayBoard(int matrix[],int n) // Prints out the given array.
{
cout<<endl ;
for (int j = 0; j < n; j++)
{
cout << matrix[j]<<" ";
}
}
int main() {
int n,m;
cin>>n ;
int matrix[n];
for(int i=0;i<n;i++) {
cin>>matrix[i];
}
DisplayBoard(matrix,n);
return 0;
}
remember to declare array in main function too ,
that was one of your code error !
and this is incorrect to declare array :
int matrix[n]={} // incorrect !
Well. int matrix[n]={}; fills it with zeros and that's what I wanted to do. And my code with 1D array works fine but if I do it like so it does not.
#include <iostream>
using namespace std;
void DisplayMatrix(int matrix[][],int n,int m)
{
for(int i=0;i<n;i++)
{
for (int j = 0; j < m; j++)
{
cout << matrix[j];
}
}
}
int main()
{
int n,m;
cin>>n>>m;
int matrix[n][m]={};
DisplayMatrix(matrix,n,m);
return 0;
}

sort the elements of an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to sort members of an array a[] with size s. I have firstly used a function to get the elements, and then another function to sort them in ascending order. The problem is in the sort function or in main or in both of them, because the execution of the program ends just after entering the data. Is there anyone here that can help me?
#include <iostream>
using namespace std;
void getdata() {
int s;
cin >> s;
int a[s];
for (int i=0; i<s; i++) {
cin >> a[i];
}
}
void sort(int a[], int s) {
for (int i=0; i<s-1; i++) {
for (int j=i+1; i<s; i++) {
if (a[i] > a[j]) swap(a[i], a[j]);
}
}
}
int main () {
int a[100],s;
getdata();
sort(a, s);
return 0;
}
You have a local definition of the array in your getdata() function:
void getdata() {
int s;
cin >> s;
int a[s]; // <<<
It stays local there and has nothing to do with the array you declared in main:
int main () {
int a[100],s; // <<<
You have to write your function such it takes these as parameters:
void getdata(int* a, int& s) {
cin >> s;
for (int i=0; i<s; i++) { // ...
and in main call
int main () {
int a[100],s;
getdata(a,s);
sort(a, s);
return 0;
}
UPDATE:
The condition in the inner for loop of your sort() function also looks pretty wrong, you probably meant j there not i:
for (int j=i+1; i<s; i++) {
// ^ ^
Always use std::vector if you have no definite advantage by using an array (and, in C++11, use std::array if s is known by compile time).
#include<vector>
#include<algorithm>
std::vector<int> a;
//fill it, then
std::sort(a.begin(),a.end());

Store returned array from a function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am just trying to make a simple two player game. First player enters the movie and second player guesses it by using some basics of C++.
movie[] = entered by player 1.
movie_temp[]= a temp array with '_' in it. It updates after every guess by player 2.
MY PROBLEM: Please refer the main function where I called the function movie_check().
This updates the life after every guess. I want the same to happen for my movie_temp array.
When I run this program, only the lives are updated properly, on correct guess the lives are not reduced, but in next turn the array_temp is not updated and the same array is displayed again and again after each gas.
Please help me to create a function which helps to return array and save it in movie_temp (just as I did for life).
IDE: Code::Blocks
Compiler: GCC Compiler
#include<iostream.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include<conio.h>
void display_movie(char movie_temp[], int);
void display_life(int);
int win_player2(char movie_temp[]);
int check_life(char movie[], char, int);
void display_movie(char movie_temp[], int len)
{
for(int i=0 ; i<len ; i++)
cout<<movie_temp[i];
}
void display_life(int life)
{
for(int i=0 ; i<=life ; i++)
cout<<"\3";
}
int check_life(char movie[], char ch, int life)
{
int count1=0;
for(int i=0 ; movie[i]!='\0' ; i++)
{
if(movie[i]==ch)
count1++;
}
if(count1==0)
return --life;
else
return life;
}
int win_player2(char movie_temp[])
{
int count=0;
for(int i=0 ; movie_temp[i]!='\0' ; i++)
{
if(movie_temp[i]=='_')
count++;
}
if(count==0)
return 0;
else
return 1;
}
int main()
{
char movie[100], movie_temp[100], ch;
cout<<"Enter the movie: ";
cin.getline(movie,100);
int len= strlen(movie);
system("cls");
for(int i=0 ; movie[i]!='\0' ; i++)
{
if(movie[i]=='a' || movie[i]=='e' || movie[i]=='i' || movie[i]=='o' ||
movie[i]=='u' || movie[i]==' ')
movie_temp[i]= movie[i];
else
movie_temp[i]='_';
}
int life=9;
cout<<"\nLives left: ";
display_life(life);
while(life!=0 || win_player2(movie_temp)!=0)
{
cout<<"\n";
display_movie(movie_temp, len);
cout<<"\nEnter your guess: ";
cin>>ch;
life=check_life(movie, ch, life);
cout<<"\n\nLives left: ";
display_life(life);
}
getch();
return 0;
}
enter code here
You make the usual mistake:
movie_temp[i]==movie[i];
should be
movie_temp[i]=movie[i];
Your compiler should have been screaming a warning at you... mine did:
note: use '=' to turn this equality comparison into an assignment
movie_temp[i]==movie[i];
Context (in case you have trouble finding the line):
if(movie[i]==ch)
{
movie_temp[i]==movie[i]; // <<<<<<<<<< this is the line that doesn't copy!
count1++;
}
update just following the warnings that the compiler was giving me, I made a few small changes to your code and now it is working. Mostly, I was heeding the "you are not returning a value!" types of warnings (when you don't explicitly return a value, the compiler will make something up - and most likely you won't find the result useful).
The key is to move the line
return movie_temp;
outside of the for loop in check_movie2:
char* check_movie2(char movie[], char movie_temp[], char ch)
{
for(int i=0 ; movie[i]!='\0' ; i++)
{
if(movie[i]==ch)
{
movie_temp[i]=movie[i];
}
}
return movie_temp;
}
There are other problems - but this is the one that was biting you the hardest.
Lesson learnt: if your compiler is warning you, LISTEN.
For your entertainment here is the code that I got to run (and that "mostly works". It doesn't currently print out lives correctly and it asks for input after I guessed the title. Also you might consider making the comparison case-insensitive as you are currently sensitive to correct capitalization).
updated added some comments and additional fixes in your code.
#include<iostream>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
using namespace std; // <<<< if you want to use 'cout' instead of 'std::cout' etc, you need this
void display_movie(char movie_temp[], int);
void display_life(int);
int win_player2(char movie_temp[]);
int check_movie(char movie[], char movie_temp[], char, int);
void display_movie(char movie_temp[], int len)
{
for(int i=0 ; i<len ; i++)
cout<<movie_temp[i];
}
void display_life(int life) //displays lives left after each guess
{
for(int i=0 ; i<=life ; i++)
cout<<"+"; // <<<<< I don't know what you are hoping to print with "\3"
// <<<<< Remember that `\` has a special meaning inside a string!
}
int check_movie(char movie[], char movie_temp[], char ch, int life)
{
int count1=0;
for(int i=0 ; movie[i]!='\0' ; i++)
{
if(tolower(movie[i])==tolower(ch)) // <<<<< consider case insensitive match
{
movie_temp[i]=movie[i];
count1++;
}
}
if(count1==0)
{
life--;
return life; //if none of the character is found, life is reduced by 1.
count1=0;
}
return life; // <<<<<< return life here
}
int win_player2(char movie_temp[])
{
int count=0;
for(int i=0 ; movie_temp[i]!='\0' ; i++)
{
if(movie_temp[i]=='_')
count++;
}
return (count==0)?0:1;
}
char* check_movie2(char movie[], char movie_temp[], char ch)
{
for(int i=0 ; movie[i]!='\0' ; i++)
{
if(movie[i]==ch)
{
movie_temp[i]=movie[i];
}
}
return movie_temp;
}
int main()
{
char movie[100], movie_temp[100], ch;
cout<<"Enter the movie: ";
cin.getline(movie,100);
int len= strlen(movie);
int life=9;
system("cls");
for(int i=0 ; movie[i]!='\0' ; i++)
{
if(movie[i]=='a' || movie[i]=='e' || movie[i]=='i' || movie[i]=='o' ||
movie[i]=='u' || movie[i]==' ')
movie_temp[i]= movie[i];
else
movie_temp[i]='_';
} //initially displays the movie to player 2 and shows only vowels.
cout<<"\nLives left: ";
display_life(life);
while(life!=0 && win_player2(movie_temp)!=0) // <<<<< change || to &&
{
cout<<"\n";
display_movie(movie_temp, len);
cout<<"\nEnter your guess: ";
cin>>ch;
life=check_movie(movie, movie_temp, ch, life);
/*I need to update the life after each round, or else the initially declared
life is passed. */
cout<<"\n\nLives left: ";
display_life(life);
}
return 0;
}
UPDATE - "returning pointers from functions"
To "return an array of values", you need to realize a number of things:
A function can only "return" a simple value (int, float, pointer, ...)
If you create an array inside a function, you need to make sure the
space allocated remains valid after you return
You can pass a pointer to a function, and let the function update values in the space pointer to
Simple example (C) on different approaches (including one that doesn't work):
does not work:
int * foo() {
int A[]={1,2,3,4,5};
return A;
}
int main(void) {
int *X;
X = foo();
printf("%d", X[0]); // UNDEFINED BEHAVIOR
return 0;
}
This doesn't work because the array A stops existing ('goes out of scope') when the function returns. Accessing memory pointed to by X results in undefined behavior.
works, but only use in single threaded environment:
int * foo() {
static int A[]={1,2,3,4,5};
return A;
}
this works because the array is static so it is allocated differently and "survives" after the function returns. Not recommended.
pass a pointer and size of array: (example increments an array)
void foo(int *a, int n) {
int ii;
for(ii=0;ii<n;ii++) a[ii]++;
}
int main(void) {
int n=5;
int X[5] = {1,2,3,4,5};
foo(X, 5); // values in X will be incremented in-place
Returning value in another array:
void foo(int *A, int *B, int n) {
int ii;
for(ii=0; ii<n; ii++) B[ii] = 2 * A[ii];
}
int main(void) {
int a[5] = {1,2,3,4,5};
int b[5];
foo(a, b, 5);
printf("%d\n", b[0]); // returns a value of 2
return 0;
}
This is starting to be more sensible. Finally, if you want an array to be created by the function, you can do
int *foo(int n) {
int *X, ii;
X = malloc(n * sizeof *X);
for(ii = 0; ii < n; ii++) X[ii] = 2 * ii;
return X;
}
int main(void) {
int *a;
a = foo(5);
printf("%d", a[4]); // will print 8
free(a); // remember to do this after you finished using the array or you get a memory leak!
return 0;
}
I hope these additional examples and their explanation improves your understanding of these techniques a little bit.

Program To Test whether or not a 4x4 matrix is a magic square using functions in C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Here is what I have. I have it outputting most of the sums just so i can check there values. I think the problem is with the value of the elements in the array storing the column sums.
I would greatly appreciate any feedback.
#include <iostream>
#include <cmath>
using namespace std;
void fillMatrix(int matrix[][4],const int SIZE);
int rowSum(int matrix[][4],const int SIZE,int row[]);
int columnSum(int matrix[][4], const int SIZE, int column[]);
bool isMagic(int matrix[][4], const int SIZE,int row[],int column[]);
int main()
{
const int SIZE=4;
int matrix[SIZE][SIZE];
int row[4],column[4];//arrays to be filled with row and column sums.
char response=0;
cout<<"This program determines whether or not a 4x4 square matrix is a magic square.\n";
do
{
fillMatrix(matrix,SIZE);
rowSum(matrix,SIZE,row);
columnSum(matrix,SIZE,row);
if(isMagic(matrix,SIZE,row,column))
cout<<"This is a magic square.\n\n";
else {
cout<<"This is not a magic square.\n\n";
}
cout<<"To end this program, enter q. To check another matrix, enter any other letter.\n";
cin>>response;
}while(response!='q'&&response!='Q');
return 0;
}
void fillMatrix(int matrix[][4],const int SIZE)
{
for(int i=0;i<4;i++)
{
cout<<"Enter four values for row "<<i+1<<".\n";
for(int j=0;j<4;j++)
{
cin>>matrix[i][j];
}
}
}
int rowSum(int matrix[][4],const int SIZE,int row[4])
{
int i=0;
int rowsum=0;
for(i=0;i<4;i++)
{
rowsum=0;
for(int j=0;j<4;j++)
{
rowsum+=matrix[i][j];
}
row[i]=rowsum;
cout<<row[i]<<endl;
}
return row[i];
}
int columnSum(int matrix[][4], const int SIZE, int column[4])
{
int j=0;
int columnsum=0;
for(j=0;j<4;j++)
{
columnsum=0;
for(int i=0;i<4;i++)
{
columnsum+=matrix[i][j];
}
column[j]=columnsum;
cout<<column[j]<<endl;
}
return column[j];
}
bool isMagic(int matrix[][4], const int SIZE,int row[4],int column[4])
{
int rightdiagonalsum=0, leftdiagonalsum=0, check;
for(int i=0;i<4;i++)
{
rightdiagonalsum+=matrix[i][i];
}
cout<<rightdiagonalsum<<endl;
for(int i=0;i<4;i++)
{
leftdiagonalsum+=matrix[i][3-i];
}
cout<<leftdiagonalsum<<endl;
for(int i=1;i<4;i++)
{
if (row[i]==row[i-1])
{
check=row[i];
}
else {
return false;
}
}
for(int j=0;j<4;j++)
{
if (column[j]!=check)
{
cout<<column[j]<<"*****";//For some reason, the value of column[j] is 0.
return false;
}
}
if (rightdiagonalsum!=check||leftdiagonalsum!=check)
{
return false;
}
return true;
}
This code:
rowSum(matrix,SIZE,row);
columnSum(matrix,SIZE,row);
should be:
rowSum(matrix,SIZE,row);
columnSum(matrix,SIZE,column);
So the column array in your code has zero values for the rather mundane reason that you never initialised it.
What's more you are accessing beyond the end of the arrays here:
return row[i];
and here:
return column[j];
At both of these points i and j have values 4. You would have avoided such a mistake had you declared the loop variables inside the for statement. That would have limited the scope of these variables.
To fix the problem, return rowsum and columnsum respectively.
I do wonder what purpose the various SIZE declarations serve since your hard code a value of 4 all over the place.

Filling 2-D arrays from user input

I have a bit of a problem, I am writing a program to ask the user to enter numbers for a Sudoku grid, and then store them in a 2-d array. I know how to print out the array to show the Sudoku grid, But I am having trouble getting the array elements set to the numbers that the user enters, can anyone help?
This is all that I have, which I know is not much but I have only ever done this with 1-d arrays before.
Code:
#include <iostream>
using namespace std;
void fillGrid1(int grid1, int sizeOfArray) {
for(int x = 0; x < sizeOfArray; x++) {
grid1[x][9] = x;
}
}
int main()
{
int grid1[9][9];
fillGrid1(grid1, 9);
for(int row = 0; row < 9; row++) {
for(int column = 0; column < 9; column++) {
cout << grid1[row][column] << " ";
}
cout << endl;
}
}
Here you have two functions, one to interactively fill the hole sudoku by getting the user input. The other for printing the sudoku. With the little information you gave it's what I think you seek:
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
using namespace std;
void interactiveSudokuFill(int grid1[9][9]){
for(int y=0;y<9;y++){
for(int x=0;x<9;x++){
string theString;
cout<<"Write the value to prace in Sudoku["<<y<<"]["<<x<<"] :"<<endl;
std::getline(cin,theString);
int nr=atoi(theString.c_str());
grid1[y][x]=nr;
}
}
}
void printSudoku(int grid[9][9]){
for(int y=0;y<9;y++){
for(int x=0;x<9;x++){
cout<<"["<<grid[y][x]<<"]";
}
cout<<endl;
}
}
int main()
{
int grid1[9][9];
interactiveSudokuFill(grid1);
printSudoku(grid1);
}
There are other more safe/elegant ways of doing this(for example user input should have been checked before delievering it to atoi()), but this way is the simpler I can think of.
Firstly, you're taking in an int where you expect an array:
void fillGrid1(int grid1, int sizeOfArray)
// ^^^^^^^^^
This should be something of the form,
void fillGrid1(int grid1[9][9], int sizeOfArray)
Next is that you should use a nested loop to access the elements of the multidimensional array:
void fillGrid1(int grid1[9][9], int sizeOfArray)
{
for (int i = 0; i < sizeOfArray; ++i)
{
for (int k = 0; k < sizeOfArray; ++k)
{
grid1[i][k] = x; // shouldn't x be the number the user entered?
}
}
}
You should also zero-fill your array:
int grid1[9][9] = {0};