Visual studio C programming function defenition - c++

The program below is to sort number in ascending order using a function. It is written in Visual Studio.
I know that I have made a mistake in function declaration as I have declared int LinearSort(); above main and not inside main.
The program executes without error but sorting does not happen since the function is not called.
The program is saved as C++.
Can anyone help me to call the function and do sorting by editing program below?
Main file
#include <stdio.h>
#include <stdafx.h>
#include "sort.h"
#include <conio.h>
#include <iostream>
int LinearSort();
int main()
{
int sort[50];
int i=0;
int j=0;
int k=0;
int a = 0;
printf("Enter 10 Numbers");
for ( i = 0; i < 10; i++ )
{
scanf_s("%d",&sort[i]);
}
for ( i = 0; i < 10; i++ )
{
printf("%d\n",sort[i]);
}
return 0;
}
.C file
#include "stdafx.h"
#include "sort.h"
#include <stdio.h>
#include <conio.h>
#include <iostream>
void LinearSort(int i, int j, int k, int a, int sort[])
{
for ( j=0; j < i-1; j++ )
{
for ( k=0; k < i-j-1; k++ )
{
if(sort[k] < sort[k+1])
{
a = sort[k];
sort[k] = sort[k+1];
sort[k+1] = a;
}
else
{
sort[j] = sort[j];
}
}
}
for ( j = 0; j < i; j++ )
{
printf("ascending %d\n",sort[j]);
}
_getch();
}
Header file
#pragma once
#include <stdio.h>
extern void LinearSort(int i, int j, int k, int a, int sort[]);

You are on the right way and your code needs only a little tweeking. Others have given valuable suggestions, most of which I won't repeat.
First the definition of your LinearSort(). You are passing a number of variables (i..k) that we call local variables and that should not be passed. Local variables are only used by your function and are declared inside the function. The proper definition now becomes:
void LinearSort(int a, int sort[]); // prototype; put in header file or above main
void LinearSort(int a, int sort[]) // function itself
{
int i, j, k; // local variables
Then you must call it from your main, after you read all the data. Call it like:
LinearSort(10, sort[]);
You passs 10 for a because you read a fixed number of integers; would you have read an arbitrary number (but less than 50), you would have passed a variable with this amount.
For your information: you pass the array variable sort[] but note that this name sort is the same in your main and in your function. There is no need and this just coincidence.
As for the sort algorithm, it seems based on bubble sort but uses for-loops. That is at least unusual and probaby wrong; the outer loop must go as many times as is needed until no more elements have been exchanged; however, a for loop normally executes a fixed number of times, so you see why this is probably wrong. I suggest you read about bubble sort.

First, remove this statement
int LinearSort();
As you have already declared the function in header file and header is included in all files.
you should call LinearSort() with proper argument in your main() , after scanf() . And in your LinearSort() function, like this
int main()
{
int sort[50];
int i=0;
int j=0;
int k=0;
int a = 0;
printf("Enter 10 Numbers");
for ( i = 0; i < 10; i++ )
{
scanf_s("%d",&sort[i]);
}
LinearSort(i, j, k, a, sort);
for ( i = 0; i < 10; i++ )
{
printf("%d\n",sort[i]);
}
return 0;
}
And in LinearSort(), inside for loop,i don't see any specific use of else statement.

Related

Function and Pointers to find the amplitude (largest value) of a signal in an array

my lecturer created this function in a live code clinic and I am trying to copy it out then re-write it multiple times until I have learnt and understood the code.
Currently I'm unsure where I need to define the "findgreatest" function for the program to run. I was under the impression that you had to define functions within the main(). However, there are likely more errors I'm not seeing. Anyways, some help to get this code running and explained in more detail would be greatly appreciated.
Thanks
Alex
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, const char * argv[]) {
const unsigned int size = 15; // creates a const int for array
int a_sig [size]; // assigns int to array size
for(int i=0; i<size; i++) {
a_sig[i] = rand() % 100;
cout << *(a_sig+i) << endl;
}
int findgreatest (int size, int a_sig) { //"F deceleration not allowed"
int max = -1;
for (int i = 0; i < size; i++) {
if (*(a_sig+i) > max){
max = *(a_sig+i);
}
}
return max;
};
int maximum;
maximum = findgreatest(size, a_sig); //"undeclared identifier"
return 0;
};
Currently I'm unsure where I need to define the "findgreatest" function for the program to run. I was under the impression that you had to define functions within the main().
Actually, you cannot define named functions in main. You can see this in the error declaration not allowed.
Functions must be declared before use. During compilation, the compiler will note where functions are defined. When the compiler sees one of these functions called, it knows what instructions to put since it is aware that these functions exist. But if a function isn't declared (and defined), then the compiler cannot interpret function calls.
You should either define your function before main, or declare your function before main and define it after main.
Option: Defining function before main
If you want to define the function before main, your code might look like
#include <iostream>
#include <ctime>
#include <cstdlib> // rand is defined here
using namespace std;
// Defines findgreatest
// findgreatest is now available for use later in program
int findgreatest (int size, int a_sig[]) // I added a `[]` in this signature
{
int max = -1;
for (int i = 0; i < size; i++) {
if (*(a_sig+i) > max){
max = *(a_sig+i);
}
}
return max;
}
int main(int argc, const char * argv[]) {
const unsigned int size = 15; // creates a const int for array
int a_sig [size]; // assigns int to array size
for(int i=0; i<size; i++) {
a_sig[i] = rand() % 100;
cout << *(a_sig+i) << endl;
}
int maximum;
maximum = findgreatest(size, a_sig);
// You probably want to do something with the maximum?
cout << "\nMaximum is " << maximum << endl;
return 0;
} // (I removed an unnecessary semicolon here)
Option: Declaring function before main, define after
Alternately, you can declare the function (i.e. give a description of its name and signature) and define it later. You can do this with
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
// declares findgreatest
// The compiler knows that this function is defined somewhere and can make
// references to it. If the definition isn't also provided during compilation,
// an error is raised.
int findgreatest (int size, int a_sig[]);
int main(int argc, const char * argv[]) {
const unsigned int size = 15; // creates a const int for array
int a_sig [size]; // assigns int to array size
for(int i=0; i<size; i++) {
a_sig[i] = rand() % 100;
cout << *(a_sig+i) << endl;
}
int maximum;
maximum = findgreatest(size, a_sig);
// You probably want to do something with the maximum?
cout << "\nMaximum is " << maximum << endl;
return 0;
}
// Definition
int findgreatest (int size, int a_sig[])
{
int max = -1;
for (int i = 0; i < size; i++) {
if (*(a_sig+i) > max){
max = *(a_sig+i);
}
}
return max;
}
Additional notes
To use rand(), you need to #include <cstdlib>.
You compute maximum but don't do anything with it. I added a statement outputting this to the terminal at the end of main.
I removed a semicolon after main(){}.
Your function signature findgreatest(int size, int a_sig) isn't quite right. The second argument is an array, not an int. There are a few different ways to denote this, but I changed it to findgreatest(int size, int a_sig[]) to indicate to the compiler that it should be expecting an array.
When you learn more about arrays, you'll know a bit more about that. And you'll probably revisit the expressions *(a_sig + i), which are a bit odd.

How to set a matrix as a parameter to a function

I have an matris that the user will define it's size and it's elemant's value, i want to send it into a function from main as parameter or someway else, tried to use pointer for it but couldn't be successful, defining it as global is not a solution because the value i will give to matris' size is not set until the user enters. A matris can't be a functions parameter as well, so I'm stuck. Anyone can help me to send that matris to the function. - sorry for long question..
int main(){
int matris [k][k];
for(i=0 ; i<k ; i++){
for(t=0 ; t<k ; t++){
cin<<matris[i][t];
}
}
func(a,b,c,x);
}
func(int a, int b, int c, x){
//some stuff
}
That's in sum how the code looks like, i know using'x' like that is impossible, i am kinda trying to change the x with the matris value, but we are unable to set a matris as a parameter.
You can represent the matrix as a vector<vector<int> >. Try something like this:
#include <vector>
using namespace std;
void myFunction(const vector<vector<int> >& matrix) {
// do something w/ matrix passed in...
}
int main() {
// create a 3x4 matrix initialized to all zero
const size_t rowCount = 3;
const size_t colCount = 4;
vector<vector<int> > matrix(rowCount, vector<int>(colCount, 0));
// pass matrix to a function
myFunction(matrix);
return 0;
}
#include <iostream>
using namespace std;
int const k = 2;
void func( int (&m)[k][k] )
{
//some stuff
cout << "func!\n";
}
int main()
{
int matris[k][k];
for(int i=0 ; i<k ; i++)
{
for(int t=0 ; t<k ; t++)
{
//cin >> matris[i][t];
}
}
func( matris );
}

First time using arrays, getting an error that 'x was not declared in this scope' however I did declare it?

My compiler keeps saying that 'small' and 'x' were not declared in this scope, how do I fix my array so that they are accurately displayed? overall the code is supposed to find the smallest positive nonzero value stored in the array.
#include <iostream>
#include <string>
using namespace std;
int findthesmall( int small[x], int y)
{
for(int i=0; i< y; i++){
for(int j=0; j< y; j++){
int temp = small[i];
if( small[i] > small[j] )
small[i] = small[j];
small[j] = temp;
}
}
return small[0];
}
int main(){
return 0;
}
I think you need:
int findthesmall( int* small, int y) {
Try this:
int findthesmall( int small[], int y) {
for(int i=0; i< y; i++){
for(int j=0; j< y; j++){
int temp = small[i];
if( small[i] > small[j] )
small[i] = small[j];
small[j] = temp;
}
}
return small[0];
}
int main(){
return 0;
}
int small[x]
This is illegal for 2 reasons.
Like your compiler says, X is undefined
Size of the array cannot be set to the value of a non compile time constant.
To fix this you can do what #ajon suggested( pass array as pointer + length), it is historically the way to pass arrays.
There are other better ways in C++ though.
You can consider using std::array or std::vector. Both of them can be passed as you would any other variable, know their own size, and can be accessed like a normal array
Or you could use template code to capture the size of the array automatically.
template<int len>
int findthesmall(int (&small)[len]){
The 2nd option maybe a little convoluted and more complex than other options, especially now that you have got your answer, I'm just including it here for completeness.
Apart from other answers, there is also a bug in the logic. If your function is just to find the smallest element as function name indicated, one for loop should be enough.
Sample code presented below:
int findthesmall( int small[], int y)
{
int temp = small[0];
for(int i=1; i< y; i++)
{
if( temp > small[i] )
temp = small[i];
}
return temp;
}
Or you could use std::min_element algorithm as well
std::cout << *std::min_element(small, small+y) << std::endl;

Can't fill the array that is a member of a class. C++

#include <iostream>
using namespace std;
class SomeClass {
public:
bool someArray[4][4]={{0,0,0,0},{0,0,0,0}};
};
int main()
{
SomeClass super;
super.someArray={{1,1,1,0},{1,0,0,1}}; //This goes red, indicates a mistake. How do i properly fill it?
for (int i=0;i<4;i++){
for (int j=0;j<4;j++){
cout<<super.someArray[i][j];
}
cout<<endl;
}
return 0;
}
Please see the comments in the code above.
By the way: super.someArray[4][4]={{1,1,1,0},{1,0,0,1}}; doesn't work either and it probably shouldn't.
You probably mean to use bool someArray[2][4] (i.e, an array with two elements that contains arrays with four boolean elements).
You can't assign one array into another in C++; you'll need to copy the individual elements. I.e., something like:
super.someArray[0][0] = 1;
super.someArray[0][1] = 1;
super.someArray[0][2] = 1;
super.someArray[0][3] = 0;
super.someArray[1][0] = 1;
super.someArray[1][1] = 0;
super.someArray[1][2] = 0;
super.someArray[1][3] = 1;
(If you have some source for your data, you could use a loop of course.)
The following worked for me using the GNU compiler. Notice that I replaced your raw array with std::tr1::array. This class is more flexible with respect to assigning entire arrays (as opposed to just initializing arrays from literals).
#include <iostream>
#include <tr1/array>
using namespace std;
using namespace tr1;
typedef array<array<bool,4>,4> array4x4;
class SomeClass {
public:
array4x4 someArray;
SomeClass() : someArray((array4x4){{{{0,0,0,0}},{{0,0,0,0}}}}) {}
};
int main()
{
SomeClass super;
super.someArray=(array4x4){{{{1,1,1,0}},{{1,0,0,1}}}}; //Now works
for (int i=0;i<4;i++){
for (int j=0;j<4;j++){
cout<<super.someArray[i][j];
}
cout<<endl;
}
return 0;
}
However, the following approach is a bit closer to where you started, and demonstrates some of the things suggested in other comments...
#include <iostream>
#include <algorithm>
using namespace std;
class SomeClass {
public:
bool someArray[4][4];
SomeClass()
{
bool temp[4][4] = {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}};
for ( int j=0; j<4; j++ ) for ( int i=0; i<4; i++ ) someArray[j][i] = temp[j][i];
}
};
int main()
{
SomeClass super;
bool temp[4][4] = {{1,1,1,0},{1,0,0,1}}; // a local source of data
for ( int j=0; j<4; j++ ) for ( int i=0; i<4; i++ ) super.someArray[j][i] = temp[j][i];
for (int i=0;i<4;i++){
for (int j=0;j<4;j++){
cout<<super.someArray[i][j];
}
cout<<endl;
}
return 0;
}
super.someArray[4][4]={{1,1,1,0},{1,0,0,1}};
The line above just needs to be:
super.someArray[4][4]={1,1,1,0,1,0,0,1};
Explaination:
it will automatically go the next section of the array. If you think of it as a table, once the first row is filled up, it will start declaring it for the next row.
So if you wrote:
super.someArray[4][4]={1,1,1,1,1};
it would set:
someArray[0][0]
someArray[0][1]
someArray[0][2]
someArray[0][3]
someArray[1][0]
all equal to 1.
(I might have the numbers switched so it could be x and y places are changed, I can't recall for c++)

Multiple Functions Definition Errors

I have a header, and a cpp file I was attempting to build.
.cpp file:
#include "SelectionSort.h"
void SelectionSort::Fill(){
Buffer = new char[Size];
for(int i=0;i<Size;i++){
Buffer[i] = rand() % 10;
}
}
void SelectionSort::PrintOut(){
for(int i=0;i<Size;i++){
cout<<Buffer[i]<<endl;
}
}
void SelectionSort::Sort(){
int lowest;
for(int i=0;i<Size;i++){
lowest=i;
for(int j=i;j<(Size-i);++j)
if(Buffer[j]>lowest) lowest = j;
swap(Buffer[lowest], Buffer[i]);
}
}
.h file:
#ifndef SELECTIONSORT_H
#define SELECTIONSORT_H
#include <algorithm>
#include <stdlib.h>
#include <iostream>
using namespace std;
class SelectionSort {
public:
SelectionSort();
SelectionSort(int S){Size= S;}
void Fill();
void PrintOut();
void Sort();
private:
int Size;
char * Buffer;
};
#endif /* SELECTIONSORT_H */
But I get these errors:
SelectionSort.cpp:17: multiple definition of 'SelectionSort::PrintOut()'
SelectionSort.cpp:17: first defined here
SelectionSort.cpp:23: multiple definition of 'SelectionSort::Sort()'
SelectionSort.cpp:23: first defined here
SelectionSort.cpp:10: multiple definition of 'SelectionSort::Fill()'
SelectionSort.cpp:10: first defined here,
How am I defining my functions incorrectly?
I am using netbeans and their generic make/build settings. I've been meaning to get more into make files, should i try to write my own and solve the problem?
Once you get your code to compile, you have a number of logical mistakes (see comments):
void SelectionSort::Sort()
{
int lowest;
for(int i = 0; i < Size; i++)
{
lowest = i;
for(int j = i; j < (Size - i); ++j) // j should terminate at the end of Buffer, not one before the end
if(Buffer[j] > lowest) lowest = j; // comparing a data element to an index, comparison operator reversed
swap(Buffer[lowest], Buffer[i]);
}
}