How to scan an integer array - c++

I am new to C++. I am trying to define a binary converter function and return a pointer. Then U want to display generated binary in the main function:
#include <iostream>
using namespace std;
int* binary_con(int n)
{
int i;
int binary[100];
for (i = 0; n > 0; i++)
{
binary[i] = n % 2;
n = n / 2;
}
return binary;
}
int main()
{
int n;
int* a;
cout << "Input the number:";
cin >> n;
a = binary_con(n);
while (*a)
{
cout << *a;
a++;
}
return 0;
}
But after I run my code, I got this:
Can anyone explain this to me?

you can't return an array from a function, the way is to pass that array as an argument to the functionm using this approach:
void binary_con(int n, int *binary)
now you have access to binary array inside your function, hence you can edit it and see the changes outside of the function without returning anything.
inside your main, instead of writing a = binary_con(n);, you should write this:
binary_con(n, a);

Related

How do I use pointers with arrays in c++ and return a pointer value?

I am trying to use pointers whenever possible in the following code and am having difficulty figuring out how, exactly, to institute the pointers and how to return a pointer value at the end of my first function. I have done some research on the subject but none of the methods I found have been helpful so far, so I was hoping you may have some specialized tips.
Note: I am a beginner.
#include <iostream>
using namespace std;
int mode(int *pies[], int size) {
int count = 1;
int max = 0;
int *mode=pies[0];
for (int i=0; i<size-1; i++)
{
if (pies[i] == pies[i+1])
{
count++;
if (count>max)
{
max = count;
mode = pies[i];
}
}
else
count = 1;
}
return *mode;
}
int main() {
int n;
cout<<"Input the number of people: "<<endl;
cin>>n;
int survey[n];
cout << "Enter the amount of pie eaten by each person:" << endl;
for(int i = 0; i < n; i++) {
cout <<"Person "<<(i + 1)<< ": "<<endl;
cin>>survey[i];
}
cout<<"Mode: "<<mode(survey, n)<< endl;
return 0;
}
Here is an attempt to answer.
In your main(), you call the mode() function with mode(survey, n) while int survey[n]; is an array of int, so you may use int mode(int *pies, int size) instead of int mode(int *pies[], int size) (as the array int survey[n] can be implicitly converted into pointer).
However, you need to modify two more things in your function:
int *mode=pies[0]; is wrong as pies[0] is the first element of an array of int, thus is an int, while int* mode is a pointer on an int which is incompatible. mode should be an int to receive pies[0]. The correct code is then int mode = pies[0].
Your function signature is int mode(int *pies, int size), thus, again, you should return an int. You should then just return mode;
These are only hints on how to make the code compile.
Your next step is to formalize what you would like it to do and then modify the code accordingly
NB: The correct practice is to think about what you would like to achieve first and then code afterwards (but let us say that this is for the sake of helping each other)
To get started using pointers, you may look at some simple tutorials at first:
http://www.cplusplus.com/doc/tutorial/arrays/
https://www.programiz.com/c-programming/c-pointers
https://www.programiz.com/c-programming/c-pointers-arrays
https://www.geeksforgeeks.org/pointer-array-array-pointer/
https://www.geeksforgeeks.org/how-to-return-a-pointer-from-a-function-in-c/
https://www.tutorialspoint.com/cprogramming/c_return_pointer_from_functions.htm
Here is the modified code with the stated modifications above (it compiles):
#include <iostream>
using namespace std;
int mode(int *pies, int size) {
int count = 1;
int max = 0;
int mode=pies[0];
for (int i=0; i<size-1; i++)
{
if (pies[i] == pies[i+1])
{
count++;
if (count>max)
{
max = count;
mode = pies[i];
}
}
else
count = 1;
}
return mode;
}
int main() {
int n;
cout<<"Input the number of people: "<<endl;
cin>>n;
int survey[n];
cout << "Enter the amount of pie eaten by each person:" << endl;
for(int i = 0; i < n; i++) {
cout <<"Person "<<(i + 1)<< ": "<<endl;
cin>>survey[i];
}
cout<<"Mode: "<<mode(survey, n)<< endl;
return 0;
}

Why am I getting the wrong output for this C++ code? (one of the problem of hackerrank)

This is the program for printing out sum of array elements. It is showing run time error. The output is coming out to be 0 instead of printing out the sum of the elements.
#include<iostream.h>
using namespace std;
void simpleArraySum()
{
int ar[100],n,i,sum=0;
for(i=0;i<n;i++)
{
sum=sum + ar[i];
}
cout<<sum;
}
int main()
{
int ar[100],n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>ar[i];
}
simpleArraySum();
return 0;
}
On this line in your main:
int ar[100], n;
You create an array of 100 elements. You later fill that array using cin
for(int i = 0 ; i < n ; i++)
{
cin >> ar[i];
}
Then you do nothing with that array. You are not calculating any sum. You let that array go, forgotten.
Then, you call a simpleArraySum function. That function is creating an entirely new, distinct array.
// v-----v------There
int ar[100],n,i,sum=0;
That array has no value assigned to it. In fact, reading from it is undefined behavior.
What you want is to receive that array in the arguments of your function:
void simpleArraySum(int* ar, int n) {
// ...
}
And call it like that in your main:
simpleArraySum(ar, 100);
You can avoid the issues of arrays and functions by not using them:
int main()
{
int quantity = 0;
std::cin >> quantity;
int sum = 0;
int value;
while (std::cin >> value)
{
sum += value;
}
std::cout << sum << "\n";
return EXIT_SUCCESS;
}
In simpleArraySum, the variable n is uninitialized. So this loop:
for(i=0;i<n;i++)
invokes undefined behavior when reading from n.
Also, you are summing a different array in the function, than the one you read in mian. It seems that you need to pass in the array from main to this function:
void simpleArraySum(int *ar, int n) {
and call it like this:
simpleArraySum(ar, n);
Finally, you don't even need a function for this, since there is an existing algorithm std::accumulate that you can use:
cout << std::accumulate(ar, ar + n, 0);
In the function, you're adding the elements of ar which is local to the function simpleArraySum() and is not of the array ar that is local to main().
So, pass the array and its length to the function and return its sum. Here is your corrected code:
#include<iostream>
using namespace std;
void simpleArraySum(int ar[], int n)
{
int i, sum = 0;
for(i=0;i<n;i++)
{
sum=sum + ar[i];
}
cout<<sum;
}
int main()
{
int ar[100],n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>ar[i];
}
simpleArraySum(ar, n);
return 0;
}

Function and Array in C++: Unexpected output

I need some help here please.
I just started learning C++ (coming from Python background).
I'm trying to familiarize myself with arrays and functions. Wrote a bunch of functions to do as stated, above each one.
However, the function which is supposed to sum elements in an array and return their sum, seem to be adding 10 to the result, no matter the argument supplied as input. What am I doing wrong please, as I can't seem to find this out. Any help on general layout of my code also would be appreciated.
// WORKING WITH ARRAYS AND FUNCTIONS
#include<iostream>
using namespace std;
// FUNCTION TO INSTANTIATE ARRAY INT OF LENGTH N.
int* array_creator(int n)
{
static int ary_of_ten[10]; //declare array
for (int i=0; i<n; i++) //use loop to fill it up
{
ary_of_ten[i] = i+1;
}
return ary_of_ten;
}
//FUNCTION TO PRINT ARRAY ELEMENTS
void* array_printer(int arr[], int array_lenght)
{
for (int i=0; i<array_lenght-1; i++)
{
cout << arr[i] << " ";
}
cout << arr[array_lenght-1] << endl;
}
//FUNCTION ACCEPTS INT ARRAYS AND RETURNS ARRAY OF SQUARE OF EACH ELEMENT
int* square_array(int *p, int array_length)
{
const int ary_sz(array_length);
static int sqd_values[10];
for (int i=0; i<ary_sz; i++)
{
*(sqd_values + i) = *(p+i) * *(p+i);
}
return sqd_values;
}
//FUNCTION ACCEPTS INT ARRAYS AND RETURNS SUM OF ITS ELEMENTS
int sum_array(int *arry, int array_length)
{
int summation;
for(int i=0; i<array_length; i++)
{
summation += *(arry + i);
}
return summation;
}
int main()
{
cout << sum_array(array_creator(10), 3) << endl;
array_printer(array_creator(10), 10); //print array of 1-10 elements
array_printer(square_array(array_creator(10), 10), 10); //prt arry of sqrd values
return 0;
}
summation shuld be initialized to 0.
int summation=0;

Whats wrong with this one? C++ Array Pointer

It says:
[Error] invalid conversion from 'int*' to 'int' [-fpermissive] on line 9 col 5.
What was asked of me to do:
Make a program that would accept array of 10 integers and determine the highest and the lowest integers from the set of integers. Use pointer variables for the highest and lowest integer.
what i did:
#include<iostream>
using namespace std;
int main()
{
int kre_arr[10];
int *kre_p;
for(int k = 0; k<=10; k++)
{
kre_p[k] = &kre_arr[k];
}
int j,temp;
cout<<"Enter 10 Integers: ";
for (*kre_p=0; *kre_p < 10; *kre_p++)
{
cin>>kre_arr[*kre_p];
}
for(*kre_p=0;*kre_p<=10;*kre_p++)
{
for(j=*kre_p+1;j<=10;j++)
{
if(kre_arr[*kre_p] > kre_arr[j])
{
temp = kre_arr[*kre_p];
kre_arr[*kre_p] = kre_arr[j];
kre_arr[j] = temp;
}
}
}
for(*kre_p=0;*kre_p<=9;*kre_p++)
{
cout<<endl<<kre_arr[*kre_p];
}
}
code i did before adding pointer i dont seem to understand pointer that much.
#include<iostream>
using namespace std;
int main()
{
int kre_arr[10];
int *kre_p;
int i,j,temp;
cout<<"Enter 10 Integers: ";
for (int i=0; i < 10; i++)
{
cin>>kre_arr[i];
}
for(i=0;i<=10;i++)
{
for(j=i+1;j<=10;j++)
{
if(kre_arr[i] > kre_arr[j])
{
temp = kre_arr[i];
kre_arr[i] = kre_arr[j];
kre_arr[j] = temp;
}
}
}
for(i=0;i<=9;i++)
{
cout<<endl<<kre_arr[i];
}
}
Looking at what you are asked to do I think you just have to determine the highest and lowest int in the array and point to. You sort the array thats slower.
I think it should look like that:
#include<iostream>
using namespace std;
int main()
{
int kre_arr[10];
int *low;
int *high;
cout<<"Enter 10 Integers: ";
for (int i=0; i < 10; i++)
{
cin>>kre_arr[i];
}
//determine the lowest
low=&kre_arr[0];
for(int i=1;i<10;i++)
{
if(kre_arr[i] < *low)
{
low=&kre_arr[i];
}
}
//determine the highest
high=&kre_arr[0];
for(int i=1;i<10;i++)
{
if(kre_arr[i] > *high)
{
high=&kre_arr[i];
}
}
cout<<"lowest: "<<*low<<"\nhighest: "<<*high;
}
kre_p[k] = &kre_arr[k];
kre_arr is array.
kre_arr[k] is integer.
&kre_arr[k] is integer address ( similar int*)
kre_p is pointer.
kre_p[k] is integer.
So, as a result, you cannot pass directly int* to int.
I guess you want kre_p+k = &kre_arr[k]
Given the state of your code, I fear for your life... So, for your overal survival, and of course in the hopes that you will learn something:
Never use 'using namespace std'. It's bad form.
You are not allocating memory for your array of pointers (kre_p). That will cause your program to crash for sure.
You don't actually need an array of pointers. Your array elements can be conveniently referred to by their offset in the array.
You are doing what appears to be a bubblesort to find the lowest and highest value. That's incredibly inefficient, and completely unnecessary.
C++ can be such a nice language. It bothers me when teachers seem to think they should be teaching it in a form that's as ugly as possible. Consider:
#include <algorithm>
#include <array>
#include <iostream>
int main () {
std::cout << "Enter 10 Integers: ";
std::array<int, 10> kre_arr;
for (auto &Val : kre_arr)
std::cin >> Val;
const int Low = *std::min_element (kre_arr.begin (), kre_arr.end ());
const int High = *std::max_element (kre_arr.begin (), kre_arr.end ());
// The assignment calls for pointers, so let's not disappoint.
const int *LowPtr = &Low;
const int *HighPtr = &High;
}

copying elements from one array to another

I am getting a crash error at run time and not sure what exactly to do with the function or how to get the data for it.
FUNCTION DETAILS
Write a function that accepts an int array and size as arguments, then create a new array that is one element bigger than the given. Setting the first element to 0, then copying over what is in the argument array to the new array.
MAIN DETAILS
Use in a program reading int n from input, then read int n from file data name data
passing it to element shifter, then printing it to output (one per line).
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int element_shift(int elmts[], int size) {
int new_size = size + 1;
int shifter[new_size];
int *elmt_sft;
shifter[0] = 0;
for (int i = 1; i >= new_size; i++) {
shifter[i + 1] = elmts[i];
}
return *elmt_sft;
}
int main() {
fstream infile;
infile.open("D:\\data.txt");
int n, x;
infile >> x;
cout << "size of array: ";
cin >> n;
const int ARRAY_SIZE = n + x;
int elements[ARRAY_SIZE];
element_shift(elements, ARRAY_SIZE);
system("PAUSE");
return EXIT_SUCCESS;
}
First of all ARRAY_SIZE declared in the main function is not a constant variable but defined at run-time depending on user inputs. This means that the array elements should be created dynamically. On the other hand you read some x variable which is only used to define the size of the array and didn't initialized the array at all. I guess that the problem statement is to read the size of the array from the input, then the data of the array from the file.
There are also lot of mistakes in element_shift function.
Your code should look like something similar to this:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
void element_shift(int* elmts, int size)
{
int new_size = size + 1;
int* shifter = new int[new_size];
shifter[0] = 0;
for(int i = 0; i < size; ++i)
{
shifter[i + 1] = elmts[i];
}
delete [] elmts;
elmts = shifter;
}
int main()
{
fstream infile;
infile.open("D:\\data.txt");
int n;
cout << "size of array: ";
cin >> n;
int* elements = new int[n];
for (int i = 0; i < n; ++i) {
infile >> elements[i];
}
element_shift(elements, n);
for (int i = 0; i < n; ++i) {
std::cout << elements[i] << std::endl;
}
return EXIT_SUCCESS;
}
First off, you spend alot of time creating the shifted array but don't return it back.
int element_shift(int elmts[], int size) {
int new_size = size + 1;
int shifter[new_size];
int *elmt_sft;
shifter[0] = 0;
for (int i = 1; i >= new_size; i++) {
shifter[i + 1] = elmts[i];
}
return *elmt_sft;
}
The elmt_sft pointer is never assigned. You are trying to access memory that is not there by using *elmt_sft. This may be causing your error. Also this function has no way of returning the new array shifter because that variable is locally declared and will disappear once the function exits. If you want to create something new in the function and still have it in memory once the function exits, I recommend creating the array dynamically and returning a pointer to it.
This is untested but should start you in the right direction. It will return a separate dynamically allocated array that will not override your other one.
int* element_shift(int elmts[], int size) {
int *result_array = new int[size + 1]; //dynamically create new array MAKE SURE TO DELETE
result_array[0] = 0; //set 0 index to 0
for (int i = 1; i < size + 1; i++)//start at 1 of the result and put value in
{
result_array[i] = elmts[i - 1];
}
return result_array; //returning pointer
}