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());
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have added bits/stdc+.h and vector both.
Still this error is coming .
Can anyone tell me why this is happening.
#include <bits/stdc++.h>
#include<vector>
void rotate(int arr[], int n);
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
int a[n] , i;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
rotate(a, n);
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
return 0;
}
// } Driver Code Ends
//User function Template for C++
void rotate(int arr[], int n)
{
vector<int> a;
a[0] = arr[n-1];
for(int i = 0 ; i<n-1 ;i++)
{
a.insert(a.back(), arr[i]);
}
for(int j : a)
cout<<j;
}
main.cpp:30:5: error: ‘vector’ was not declared in this scope
vector<int> a;
^~~~~~
Follow these: (EDITED)
(SOLUTION TO YOUR PROBLEM) Use, using namespace std as it means if the compiler finds something that is not declared in the current scope then it will go and check std.
Don't mix c and c++ syntax. Either use printf or cout.
Also check the 1st comment on this answer, as there is something you should know about "using namespace std" and "cout/cin".
No need to work two times, you can also declare and define your function at once.
Solution (but have an error in other parts)
#include <bits/stdc++.h>
using namespace std;
void rotate(int arr[], int n)
{
vector<int> a;
a[0] = arr[n - 1];
for (int i = 0 ; i < n - 1 ; i++)
{
a.insert(a.back(), arr[i]); // ITS YOUR SYNTAX, CONSIDER TO UPDATE IT
}
for (auto &it : a)
cout << it;
}
int main()
{
int t;
cin>>t;
while (t--)
{
int n;
cin>>t;
int a[n] , i;
for (i = 0; i < n; i++)
cin>>a[i];
rotate(a, n);
for (i = 0; i < n; i++)
cout<<a[i];
cout<<"\n";
}
return 0;
}
CHECK LINE NO 9 line,
and see if it's correct or not.
a.insert(a.back(), arr[i]); WRONG
You are doing something wrong there. Check this statement
error: ‘vector’ was not declared in this scope
Solved by using namespace
If you liked this answer. Please consider ticking this answer.:)
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.
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.
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 was testing one of my classes, but for some reason I can't seem to cast an intiger from a 2d array to double. Here is my (very simplified) code:
In main.cpp
#include<iostream>
#include<conio.h>
#include<string>
#include "trajectories.h"
int main()
{
std::string response;
int numOfCoords;
int speed;
int ** coords;
std::cout<<"enter the number of coordinates: ";
std::cin>>numOfCoords;
std::cout<<"enter speed: ";
std::cin>>speed;
coords=new int *[numOfCoords];
for (int i=0; i<numOfCoords; i++)
coords[i] = new int[2];
for(int i=0; i<numOfCoords*2; i++)
{
if(i%2==0)
std::cout<<"enter point "<<i/2<<".x : ";
else
std::cout<<"enter point "<<i/2<<".y : ";
std::cin>>coords[i/2][i%2];
}
NPCTrajectory traj(numOfCoords, speed);
traj.AddCoordinates(coords);
std::cout<<coords[0][0]<<", "<<coords[0][1]<<std::endl;
getch();
double currentCoords[2];
currentCoords[0]=double(coords[0][0]);
currentCoords[1]=double(coords[0][1]);
for(;;)
{
traj.HandleEvents(currentCoords);
std::cout<<"current coordinates : ("<<currentCoords[0]<<", "<<currentCoords[1]<<")"<<std::endl;
std::cout<<"do you wish to continue? ";
getch();
}
}
Trajectories.h contains class declaration only, so I believe it is irrelevant. Here is my trajectories.cpp
#include "trajectories.h"
int FPSCap=5;
NPCTrajectory::NPCTrajectory(int npoints, int newSpeed)
{
numOfPoints=npoints;
this->speed=newSpeed;
points = new int * [npoints];
for (int i=0; i<npoints; i++)
points[npoints] = new int[2];
state = 0;
maxOffset=speed/FPSCap;
}
void NPCTrajectory::AddCoordinates(int ** coordinates)
{
for(int i=0;i<this->numOfPoints; i++)
{
points[i][0]=coordinates[i][0];
points[i][1]=coordinates[i][1];
}
}
void NPCTrajectory::HandleEvents(double (¤tCoordinates)[2])
{
if(state+1==numOfPoints) return;
if(Distance(currentCoordinates[0], currentCoordinates[1], (double)points[state+1][0], (double)points[state+1][1])<maxOffset) state++;
double ratio = maxOffset/Distance(currentCoordinates[0], currentCoordinates[1], (double)points[state+1][0], (double)points[state+1][1]);
currentCoordinates[0]+=(points[state+1][0]-currentCoordinates[0])*ratio;
currentCoordinates[1]+=(points[state+1][1]-currentCoordinates[1])*ratio;
}
Please note that removing command traj.AddCoordinates(coords) will make the problem disappear. Am I passing the array correctly to the function?
The problem is in your constructor NPCTrajectory. Replace npoints with loop variable i. The following code:
for (int i=0; i<npoints; i++)
points[npoints] = new int[2];
should be like:
for (int i=0; i<npoints; i++)
points[i] = new int[2];
Because of this incorrect allocation, you are getting error (segmentation fault) in AddCoordinates function when you try to access points[i][0] with i=0 (assuming you are giving npoints>0 in NPCTrajectory).
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];
}