C++ How to change the output on a new array - c++

So I wrote a program that is supposed select the perfect squares from an array and put it into another array. Example: (2,4,13,5,25,66) and the second array(the result) should look like this (4,25)
My result looks like this (0,4,0,0,25,0) ...so its half good ...how to make it show only 4,25 ?
#include<iostream.h>
#include<math.h.>
int main()
{
int A[100],i,n,p,j;
cout << "Number of array elements=";
cin >> n;
for(i=1;i<=n;i++)
{
cout<<"A["<<i<<"]=";
cin>>A[i];
}
for(i=1;i<=n;i++)
{
p=sqrt(A[i]) ;
if(p*p==A[i])
A[j]=A[i];
else
A[i]=0;
cout << A[i] << " ";
}
return 0;
}
USING ONLY c++ basic commands...as i did

You need to keep a separate count of how many perfect squares you've found and use that to place your answers into an array of perfect squares:
int squares[???];
// ...
if(p*p==A[i]) {
squares[squaresFound]=A[i];
squaresFound++;
}
The problem now will be to decide how long the squares array should be. You don't know ahead of time how many squares you're going to get. Are you going to have it the same size as A and fill the rest with 0s? Or do you want the array of squares to be exactly the right size?
If you want it to be the right size, you're much better off using a std::vector:
std::vector<int> squares;
// ...
if(p*p==A[i]) {
squares.push_back(A[i]);
}
But I think your silly "only basic C++ commands" restriction will not allow you to do this.

You talk about a second array (the result), yet your code declares only one array! Additionally, you reference A[j], but your j has not be initialized.
You should declare another array B[100], initialize j to zero, and then use this code when you find a square:
int j = 0;
for (int i=0 ; i != n ; i++) {
int p = sqrt(A[i]);
if(p*p==A[i]) {
B[j++] = A[i];
}
}

Make another array, remove all occurrences of 0 from the resultArray and add non-0 to newArray.
OR
int j=0
if(A[i]==p*p)
squares[j++]=A[i];

#include <cmath>
#include <iostream>
using namespace std;
int main()
{
int A[100];
int n;
cout << "Number of array elements = " << endl;
cin >> n;
for(int i = 0; i < n; i++)
{
cout << "A[" << i << "] = ";
cin >> A[i];
}
int B[100];
int cnt_sqr = 0;
for(int i = 0; i < n; i++)
{
int p = sqrt(A[i]);
if (p * p == A[i])
{
B[cnt_sqr++] = A[i];
}
}
for (int i = 0; i < cnt_sqr; i++)
{
cout << B[i] << ' ';
}
return 0;
}
Full code of that about what you were told above

If you do not want to modify your code you can write the following:
for(i=1;i<=n;i++)
{
p=sqrt(A[i]) ;
if(p*p==A[i])
{
cout << A[i] << " ";
}
}
It will print you only perfect squares.
If you want to copy elements to another array:
int squares[100] = {0}; // Assuming that all values can be perfect squares
int square_count = 0;
for(i=1;i<=n;i++)
{
p=sqrt(A[i]) ;
if(p*p==A[i])
{
squares[square_count++] = A[i];
}
}

Related

Want to reverse an array of numbers C++

I have some code written but I'm not sure why the reversed array is not giving me the exact values I need. I created a second array the same size as the first and used nested for loops to fill the second with the contents of the first in reverse.
See below:
#include <iostream>
using namespace std;
int main()
{
// Ask for how big the array is
int n;
cout << "how big is the array?" << endl;
cin >> n;
// create array
int a[n];
// create second array
int b[n];
// ask for contents of the 1st array
cout << "what's in the array?" << endl;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
// reverse the array
for (int i = n - 1; i >= 0; i--)
{
for (int k = 0; k < n; k++)
{
b[k] = a[i];
break;
}
}
// print out the new array
for (int k = 0; k < n; k++)
{
cout << b[k] << endl;
}
return 0;
}
you don't need 2 bucles for fill the second array
try with:
//reverse the array
s = 0;
for (int i=n-1;i>=0;i--){
b[n]=a[s];
s++;
}
Try something like this:
#include <algorithm>
#include <iostream>
#include <vector>
namespace {
template <typename IStream>
[[nodiscard]] int readOneIntFrom(IStream& istream) {
int x;
istream >> x;
return x;
}
}
int main()
{
// Ask for how big the array is
std::cout << "how big is the array?" << std::endl;
auto n = readOneIntFrom(std::cin);
// create array
std::vector<int> a;
// ask for contents of the 1st array
std::cout << "what's in the array?" << std::endl;
for (int i = 0; i < n; i++)
{
a.emplace_back(readOneIntFrom(std::cin)); // Make a new entry at the end of a.
}
// Construct b from a backward. (Or do auto b = a; std::reverse(b.begin(), b.end());
auto b = std::vector<int>(a.rbegin(), a.rend());
// print out the new array
for (const auto& bi : b)
{
std::cout << bi << std::endl;
}
return 0;
}

Function is not returning any value | C++

I'm writing a function that will find the number with max number of divisors but the function is not returning anything. Can someone point out my mistake?
This is the question
Write a C++ program that creates and integer array having 30 elements. Get input in this array (in main
function). After that, pass that array to a function called “Find_Max_Divisors” using reference pointer.
The function “Find_Max_Divisors” should find (and return) in the array that number which has highest
number of divisors. In the end, the main function displays that number having highest number of divisors.
#include <iostream>
using namespace std;
int main ()
{
int arr[30];
int* array = &arr[30];
cout << "Please enter values of the array" << endl;
for (int i=0; i<30; i++)
{
cin >> arr[i];
}
cout << "Number with most divisors in array is " << endl;
int Find_Max_Divisors (*array);
}
int Find_Max_Divisors (int p[])
{
int count=0, max_divisor, max_counter, prev=0, repeat=0, divisor;
for (int i=2; i<=30; i++)
{
if (p[i]%i==0)
{
count++;
}
if (count > prev)
{
prev = count;
divisor = p[i];
}
if (count==max_counter && max_counter!=0)
{
cout << p[i] <<" has maximum of "<< count <<" divisors.\n";
}
max_counter = prev;
max_divisor = divisor;
repeat++;
}
return count;
}
change
int Find_Max_Divisors (*array);
to
int value = Find_Max_Divisors(arr);
You can get rid of the array variable altogether.
It's quite possible you'll find you need to put your function before main, too.
Firstly, you declare an array that has 30 elements
int arr[30];
But here you make the pointer point to the out of arr.
int* array = &arr[30];
I guess you want to make pointer point to arr, if i am not wrong, you can do as:
int *array = &arr[0]; // or int * array = arr;
Then when you call the Find_Max_Divisors function, you should change to:
int return_value = Find_Max_Divisors(array);
One more thing, int this function:
for (int i=2; i<=30; i++)
When i=30, p[i] go to out of bount again. It should be:
for (int i=2; i< 30; i++)
you don't need pointers to do that this simple code can fix your problem just change the size of your array as you want i am testing with array of size 4 here
#include <iostream>
using namespace std;
int Find_Max_Divisors(int p[])
{
int count = 0, max = 0;
for (int i = 0; i < 4; i++) {
for (int j = 1; j < p[i] / 2; j++) {
if (p[i] % j == 0) {
count++;
}
}
if (count > max)
max = p[i];
}
return max;
}
int main()
{
int arr[30];
// int* array = &arr[30];
cout << "Please enter values of the array" << endl;
for (int i = 0; i < 4; i++) {
cin >> arr[i];
}
int value = Find_Max_Divisors(arr);
cout << "Number with most divisors in array is " << value << endl;
}
There are several mistakes in your code:
First, if your main function should know the funtions it calls, you should declare them previously. Just add a line Find_Max_Divisors (int p[]); Before the main function.
An array in C or C++ is a pointer, when you only call it by it's name. So call Find_Max_Divisors (arr) and get rid of that awful pointer-assignment.
In the last line just try to call the function, but never put it to stdout, you should change it to this:
cout << "Number with most divisors in array is " << Find_Max_Divisors(arr) << endl;
What you actually did with int Find_Max_Divisors (*array); was declaring a new variable and not calling a function.

How to debug my C++ program?

I try to enter 2d array and to sum all numbers in one row. Then I convert that number to binary (8 bit) and to set it again in new 2d array. Here's my code. I get output in negative numbers and I expect binary number.
I input
1 2 3
4 5 6
7 8 9
And i want this output
00000110
00001111
00011000
i get
00000000
00000000
00000000
#include<iostream>
using namespace std;
int main()
{
int n,m,j,i;
int a[50][50],b[50][8],c[50];
cin>>n>>m;
for(i=0;i<n;i++)
{
c[i]=0;
for(j=0;j<m;j++)
{
cin>>a[i][m];
cin.ignore();
c[i]+=a[i][j];
}
}
for(i=0;i<n;i++)
for(j=0;j<8;j++)
{
b[i][j]=c[i]%2;
c[i]/=2;
}
for(i=0;i<n;i++)
{
for(j=0;j<8;j++)
{
cout<<b[i][j];
}
cout<<endl;
}
}
I attempted to revise your code but I soon realised that you were doing some weird unnecessary things so I just started fresh and here's what I've got for you:
#include <iostream>
#include <vector>
using namespace std;
void add_array(int arr1[], int arr2[], int arrLength, int ret[]) {
for(int i = 0; i < arrLength; i++) {
ret[i] = arr1[i]+arr2[i];
}
return;
}
void to_binary(int n, vector<int> *ret) {
while(n!=0) {
ret->push_back(n%2==0 ?0:1);
n/=2;
}
}
int main() {
int a[5] = {1,2,3,4,5};
int b[5] = {6,7,8,9,10};
int c[5];
add_array(a, b, 5, c);
cout << "A:" << endl;
for(int i = 0; i < 5; i++) {
cout << i << " : " << a[i] << endl;
}
cout << "B:" << endl;
for(int i = 0; i < 5; i++) {
cout << i << " : " << b[i] << endl;
}
cout << "C:" << endl;
for(int i = 0; i < 5; i++) {
cout << i << " : " << c[i] << endl;
}
vector<int> vec;
for(int i = 0; i < 5; i++) {
to_binary(c[i], &vec);
for(int j = 0; j < vec.size(); j++) {
cout << vec[j];
}
cout << endl;
vec.clear();
}
return 0;
}
I don't know how you were handling the adding of the two functions so I just wrote a really simple function there, I'll start with the parameters
int arr1[], int arr2[]
These are the two functions you'll be adding, simple.
int arrLength
This tells the function what the length of the two arrays is for the 'for loop'
int ret[]
Ret is the return array and is passed in so that it can be modified with the added arrays, now you could do that with either of the other two arrays but this is better practice especially if you want to reuse the other arrays later.
Now here's the function itself
for(int i=0;i<arrLength;i++){ ret[i]=arr1[i]+arr2[i];}
Here we loop through each position in the arrays and place them in the variable 'ret', this is the whole thing.
The function
void to_binary(int n, vector<int> *ret)
handles the decimal to binary using a vector for variable sizes, it's basically what you were doing just in a function.
In the function main we create the three arrays and call add_array with the necessary arguments, then we create the vector vec and then proceed to loop through the array c getting the binary number of each position and then since we stored the binary number in an int vector instead of a string we loop through the vector
for(int j = 0; j < vector.size(); j++)
We are using vector.size() to get the dynamic size of the vector, then we print out each binary digit and then print an endl and clear the vector for reuse.

C++ Array of Pointers not assignable

I need to create 2 arrays, each with 4 elements. One array contains four int values gotten from the user, and the other array contains pointers to the elements of the first array. I keep getting the following error:
array type 'int *[4]' is not assignable
on this line:
my_ptrs = &my_ints;
Here is my code:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int my_ints[4];
int *my_ptrs[4];
float temp;
int num;
for (int x=0; x< 4; x++)
{
cout << "Enter Integer:" << endl;
cin >> num;
my_ints[x] = num;
}
my_ptrs = &my_ints;
for(int k=0; k<=3; k++)
{
for(int j=k+1; j<=3; j++)
{
if(my_ptrs[k]>my_ptrs[j])
{
temp=*my_ptrs[k];
my_ptrs[k]=my_ptrs[j];
*my_ptrs[j]=temp;
}
}
cout << my_ptrs[k] << " ";
}
return 0;
}
Your apparent intent is to have each pointer in my_ptrs to point to the corresponding value in my_ints.
I'm afraid there are no shortcuts here, using a single assignment. You have to do it the hard way:
for (int i=0; i<4; ++i)
my_ptrs[i]=&my_ints[i];
You cannot assign a pointer-to-an-array to an array variable, like you are trying to do. But what you can do instead is either:
initialize the second array in its declaration directly:
int my_ints[4];
int* my_ptrs[4] = {&my_ints[0], &my_ints[1], &my_ints[2], &my_ints[3]};
populate the array in a separate loop:
int my_ints[4];
int* my_ptrs[4];
for (int i = 0; i < 4; ++i)
my_ptrs[i] = &my_ints[i];
That being said, based on what you are trying to do ("i want to print the my_ptrs array in ascending order"), you could just get rid of the second array altogether and use the std::sort() algorithm instead:
Sorts the elements in the range [first, last) in ascending order.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int my_ints[4];
for (int x = 0; x < 4; ++x)
{
cout << "Enter Integer:" << endl;
cin >> my_ints[x];
}
std::sort(my_ints, my_ints+4);
for(int k = 0; k < 4; ++k)
cout << my_ints[k] << " ";
return 0;
}

Finding Max, Min, Avg using dynamic memory allocation and pointers

I am learning pointers so I tried to implement this simple code of finding Max, min and Avg of student grades.
I only could found the avg BUT for the Max and the Min I got the first element of the *p.
here is my code If you please can tell me what is my mistake
#include <iostream>
using namespace std;
int main()
{
int *p;
int x;
cout << "Enter a number of student: ";
cin >> x;
p = new int[x];
for (int i = 0; i < x; i++)
{
cout << "Enter a grade: ";
cin >> *(p + i);
}
int sum = 0;
int max = 0;
int min = 0;
max = *p;
min = *p;
for (int i = 0; i < x; i++)
{
if (min > *p)
{
min = *p;
p++;
}
}
for (int i = 0; i < x; i++)
{
if (max < *p)
{
max = *p;
p++;
}
}
for (int i = 0; i < x; i++)
{
sum += *p;
p++;
}
int avg = sum / x;
cout << "avg is : " << avg << endl;
cout << "Max num is : "<< max
<< "\n Min num is : " << min << endl;
}
Note the changes
for (int i = 0; i < x; i++)
{
if (min > *(p+i))
{
min = *(p+i);//changed
}
}
for (int i = 0; i < x; i++)
{
if (max < *(p+i))
{
max = *(p+i);//changed
}
}
for (int i = 0; i < x; i++)
{
sum += *(p+i);//changed
}
You only advance the pointer, if *p is greater than the current max or min. Either advance it on every iteration (and back up the original state) or use p[i] to get the element of the iteration.
Your code is wrong on a number of levels. First of all, have a look at how you initialize the pointer p, which is supposed to point to the beginning of your array containing int elements :
p = new int[x];
This is all good. However, if you now take a look at the first loop...
for (int i = 0; i < x; i++)
{
if (min > *p)
{
min = *p;
p++;
}
}
You will notice that you keep incrementing p, which was supposed to point to the beginning of the array. This way, you can't possibly visit every element of the array when you run the second loop, because p does not point at the start of your array anymore! Thus, you invoked what some people call undefined behaviour by accessing an array out of its bounds.
However, you were able to properly reference the array in the loop where you actually write the elements to it - with the line cin >> *(p + i);.
Also, you should always remember to delete everything you newed. However, if you lose the pointer to what new returned, you will never be able to successfully delete it.
Furthermore, if you're programming in C++, you really should avoid using raw pointers, and - if you really need to - wrap them inside an unique_ptr (if you're using C++11). When it comes to "dynamic arrays", std::vector is most often the better way.
That's because you're doing p++, thus "losing the pointer".
In each for loop except for the first one, change *p to p[i], and get rid of the p++.
Also, at the end of the function, call delete p.
You could inline the calculation of max, min, and sum:
int sum = 0;
int max = 0;
int min = 0;
for (int i = 0; i < x; i++)
{
int g=0;
cout << "Enter a grade: ";
cin >> g;
if (g > max)
max = g;
if (g < min)
min = g;
sum += g;
}
Then you wouldn't need p = new int[x]