i dont know whats wrong with my code but im getting same value of "sum" on the
screen..
assume that m and n are entered equal ....enter image description here
#include<stdio.h>
#include<malloc.h>
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
int n,m;
int *ptr1, *ptr2, *sum;
cout<<" enter the size of 1st and 2nd array : "<<endl;
cin>>n>>m;
ptr1=(int*)malloc(n*sizeof(int));
ptr2=(int*)malloc(m*sizeof(int));
sum=(int*)malloc((n)*sizeof(int));
cout<<"enter 1st array element :";
for(int i=0;i<n;i++)
{
cin>>*(ptr1+i) ;
}
cout<<"enter 2st array element :";
for(int i=0;i<m;i++)
{
cin>>*(ptr2+i);
}
for(int j=0;j<m||j<n;j++)
{
*(sum+j) = (*(ptr1) + *(ptr2)) ;
}
cout<<" the sum is "<<endl;
for(int j=0;j<m||j<n;j++)
{
cout<<*(sum+j)<<endl;
}
}
First, the reason you get the same number springs from where you form the sums.
In this loop
for (int j = 0; j<m || j<n; j++)
{
*(sum + j) = (*(ptr1)+*(ptr2));
}
you find the sum of the contents of ptr1 and ptr2 over and over which never change - this is always the first two numbers.
So, we could iterate over the arrays by indexing in j along as follows
for (int j = 0; j<m || j<n; j++)
{
*(sum + j) = (*(ptr1 + j) + *(ptr2 + j));
}
BUT what happens if m!=n? You'll walk off the end of the array.
If you change the loop to
for (int j = 0; j<m && j<n; j++)
{
*(sum + j) = (*(ptr1 + j) + *(ptr2 + j));
}
then you find the sum for pairs of numbers up to the smaller of m and n.
You will have to do likewise with the display of the results
for (int j = 0; j<m && j<n; j++)
{
cout << *(sum + j) << endl;
}
However, I believe you wanted to either display n numbers, regardless of which is bigger, or perhaps assume a 0 if there is no element. Also, I notice you have malloced and not freed - perhaps using a C++ array rather than C-style arrays is better? I'll come to that in a moment.
Let's do the C appraoch and have a 0 if we go beyond the end of an array.
This will work, but can be tidied up - comments inline about some important things
#include<stdlib.h>
#include <algorithm> //for std::max
#include <iostream>
using namespace std;
int main()
{
int n, m;
int *ptr1, *ptr2, *sum;
cout << " enter the size of 1st and 2nd array : " << endl;
cin >> n >> m;
ptr1 = (int*)malloc(n * sizeof(int));
ptr2 = (int*)malloc(m * sizeof(int));
sum = (int*)malloc((std::max(n, m)) * sizeof(int));
// ^--- sum big enough for biggest "array"
// data entry as before - omitted for brevity
for (int j = 0; j<m || j<n; j++)
{
*(sum + j) = 0;
if (j < n)
*(sum + j) += *(ptr1 + j);
if (j < m)
*(sum + j) += *(ptr2 + j);
}
cout << " the sum is " << endl;
for (int j = 0; std::max(n, m); j++)//however big it is
{
cout << *(sum + j) << endl;
}
free(ptr1); //tidy up
free(ptr2);
free(sum);
}
I know you said you wanted to use malloc and perhaps this is a practise with pointers, but consider using C++ idioms (at least you won't forget to free things you have maoolced this way).
Let's nudge your code towards using a std::vector:
First the include and the input:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n, m;
vector<int> data1, data2, sum;
cout << " enter the size of 1st and 2nd array : " << endl;
cin >> n >> m;
cout << "enter 1st array element :";
for (int i = 0; i<n; i++)
{
int number;
cin >> number;
data1.push_back(number); //there is a neater way, but start simple
}
cout << "enter 2st array element :";
for (int i = 0; i<m; i++)
{
int number;
cin >> number;
data2.push_back(number);
}
This post shows a way to neaten up the data entry. However, let's do something simple and get the sum:
for (int j = 0; j < std::max(m, n); j++)
{
int number = 0;
if (j < n)
number += data1[j];
if (j < m)
number += data2[j];
sum.push_back(number);
}
And now for a C++ way to do output
cout << " the sum is " << endl;
for (auto item : sum)
{
cout << item << '\n';
}
}
Finally, let's have a brief think about the sum.
If you now #include <iterator> you can use an algorithm to put your sum into sum
std::transform(data1.begin(), data1.end(),
data2.begin(), std::back_inserter(sum), std::plus<int>());
However, note this won't fill with zeros. You could either make the vectors the same size, filled with zeros first, or lookup/discover ways to zip vectors of different sizes. Or stick with ifs in a loop as I demonstrated above.
Avoid malloc in C++. Just saying.
I highly encourage you to use a modern cpp data structure like a vector for storing your data. Thus, you don't have to worry about malloc and can access them far more easyly.
But now to your question: Your summation for loop is broken. Use
for(int j=0;j<m||j<n;j++)
{
*(sum+j) = (*(ptr1+j) + *(ptr2+j)) ;
}
Best regrads, Georg
Related
I am writing an algorithm to do Gaussian elimination. I do not know why the elements of the matrix do not change after the calculations. I think I might need to defined the elements in a different way, but I do not know how. Is there any other easy way to fix this problem?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n, i, j, k;
float mult;
cout << "Enter the number of equations\n";
cin >> n;
int a[n][n], x[n], b[n];
for (i=0;i<n;i++)
{
for (int j=0;j<n;j++)
{
cout << "A[" << i+1 << "][" << j+1 << "]=";
cin >> a[i][j];
}
}
for (i = 0; i<n; i++)
{
cout << "b[" << i+1 << "] is ";
cin >> a[i][n];
}
for (j = 0; j< n; j++)
for (i=j+1; i< n ; i++)
mult = a[i][j] / a[j][j];
for (k = j+1; k < n ; k++)
a[i][k] = a[i][k] - mult * a[j][k];
x[n-1] = a[n-1][n]/ a[n-1][n-1];
for (i = n-2; i=0; i--)
for (j=n-1; j = i+1; j--)
a[i][n] = a[i][n] - a[i][j]*x[j];
x[i] = a[i][n] / a[i][i];
}
I see several problems with your code:
VLAs1 are not standard c++
In standard c++ int a[n][n], x[n], b[n]; is not valid, because n is not constant at compile time. Even if some compilers allow this, don't use it. Use std::vector instead.
The last line of code is not part of any loop
You should use an IDE or simple Editor to fix intendation for you, then you would see, that the last line x[i] = a[i][n] / a[i][i]; is not part of any loop. My tip: always use parantheses after for!
The last loops have a wrong condition
The condition of the last loop for(i = n-2; i=0; i--) is i=0. This will_assign_ the value 0 to i then evaluate i as condition and since i is zero it will exit the loop. Probably you meant to use == to compare the values.
The same thing goes for the nested loop for (j=n-1; j = i+1; j--).2
1Variable Length Arrays
2 Actually this loop will run forever for any n != 0
I have a task to square all the elements of array, separate them with ",", then find a sum of the squared array and find the biggest number of it. I managed to square them and find the sum, but I can't find the biggest number and the program is also printing "," at the end of new array.
This is my code:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[10];
int n,sum=0,kiek=0,max=a[0];;
cin>>n;
for(int i=0;i<n;i++)
{cin>>a[i];
a[i]*=a[i];
sum=sum+a[i];
}
for (int i = 0 ; i < n ; i++)
{ cout <<a[i] << ","; }
cout<<endl ;
cout<<"suma " <<sum;
cout<<endl;
for(int i=0;i<10;i++)
{if(max<a[i])
{
max = a[i];
}
}
cout<<"max "<<max;
return 0;
}
This is the screenshot of my program result when I run it
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[10];
int n, sum = 0; // Remove some unused variables
// Input //
cin >> n;
for(int i = 0; i < n; i++){
cin >> a[i];
a[i] *= a[i];
sum += a[i];
}
// List a[] and sum //
for (int i = 0 ; i < n - 1 ; i++) {
cout << a[i] << ", ";
}
cout << a[n - 1] << endl; // Just for a little beauty
cout << "suma " << sum << endl;
// Find Max //
int max = a[0]; // max should be declared there,
// because a[0] has not entered data at the first
for(int i = 0; i < n; i++) { // use n, not 10
if(a[i] > max){
max = a[i];
}
}
cout << "max " << max;
return 0;
}
Unchecked.
Please add indents, spaces and comment, this is a good habit.
Comment : If you are going to get the size of the array at run-time, it is better to use STL containers or pointers. Your issue lies here :
---> for(int i=0;i<10;i++)
{if(max<a[i])
Good luck.
I have a program, where I have to generate all R-digit numbers among N digits in C++, for example for N=3 (all digits from 1 to N inclusive) and R=2 the program should generate 12 13 21 23 31 32. I tried to do this with arrays as follows, but it does not seem to work correctly.
#define nmax 20
#include <iostream>
using namespace std;
int n, r;
void print(int[]);
int main()
{
cin >> n;
cin >> r;
int a[nmax];
int b[nmax];
int used[nmax];
for (int p = 1; p <= n; p++) {
//Filling the a[] array with numbers from 1 to n
a[p] = n;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < r; j++) {
b[j] = a[i];
used[j] = 1;
if (used[j]) {
b[j] = a[i + 1];
}
used[j] = 0;
}
print(b);
}
return 0;
}
void print(int k[]) {
for (int i = 0; i < r; i++) {
cout << k[i];
}
}
If I understand your question correctly, you can explore this website where it explains the problem and suggests the solution thoroughly.
Here is a slightly altered code:
Pay attention that time is an issue for bigger N values.
#define N 5 // number of elements to permute. Let N > 2
#include <iostream>
using namespace std;
// NOTICE: Original Copyright 1991-2010, Phillip Paul Fuchs
void PrintPerm(unsigned int *a, unsigned int j, unsigned int i){
for(unsigned int x = 0; x < N; x++)
cout << " " << a[x];
cout << " swapped( " << j << " , " << i << " )\n";
}
void QuickPerm(void){
unsigned int a[N], p[N+1];
register unsigned int i, j, PermCounter = 1; // Upper Index i; Lower Index j
for(i = 0; i < N; i++){ // initialize arrays; a[N] can be any type
a[i] = i + 1; // a[i] value is not revealed and can be arbitrary
p[i] = i;
}
p[N] = N; // p[N] > 0 controls iteration and the index boundary for i
PrintPerm(a, 0, 0); // remove comment to PrintPerm array a[]
i = 1; // setup first swap points to be 1 and 0 respectively (i & j)
while(i < N){
p[i]--; // decrease index "weight" for i by one
j = i % 2 * p[i]; // IF i is odd then j = p[i] otherwise j = 0
swap(a[i], a[j]); // swap(a[j], a[i])
PrintPerm(a, j, i); // remove comment to PrintPerm target array a[]
PermCounter++;
i = 1; // reset index i to 1 (assumed)
while (!p[i]) { // while (p[i] == 0)
p[i] = i; // reset p[i] zero value
i++; // set new index value for i (increase by one)
} // while(!p[i])
} // while(i < N)
cout << "\n\n ---> " << PermCounter << " permutations. \n\n\n";
} // QuickPerm()
int main(){
QuickPerm();
} //main
Here is a list of the modified items from the original code.
N defined to be 5 instead of 12.
A Counter has been added for more informative result.
The original swap instructions reduced by using c++ standard libraries' swap() function.
The getch() has been removed.
The 'Display()' function has been renamed to be 'PrintPerm()'.
The printf() function has been replaced by cout.
Printing number of permutation has been added.
I'm having problems figuring out where my bubble sort code went wrong. I'm almost positive it's in the sorting algorithm. Here is what I need my code to accomplish:
-Initialize an array a fill it with random numbers (I use getNumbers() to accomplish this)
-Compare the first element with all later elements. If the first element is larger, swap them.
-Compare the second element with all later elements one by one. If the second element is larger, swap them.
-Continue comparing and swap operations until the second to last element.
-Print out the sorted array
And here's my code:
#include <iostream>
#include <cstdlib>
using namespace std;
void swap(int *, int *);
int *getNumbers(int);
int main()
{
//Get the size of the array from keyboard
int arraySize;
cout << "How many integers would you like to declare: ";
cin >> arraySize;
//Initialize array
int *array;
array = getNumbers(arraySize); //getNumbers should return a pointer
//Print out original array
cout << "Original array" << endl;
for(int count = 0; count < arraySize; count++)
{
cout << *(array + count) << " ";
}
//Sort array using the swap function
//Have a for loop to swap numbers one by one from min to max
//Compare values using a second for loop
//Swap values if former value is larger
//swap(&array[i],&array[j]);
for(int i = 0; i < arraySize; i++)
{
for(int j = 0; j < (arraySize - 1); j++)
{
if(array[j] > array[j + 1])
{
swap(&array[i], &array[j]);
}
}
}
//Print out sorted array
cout << "\nSorted Array" << endl;
for(int count = 0; count < arraySize; count++)
{
cout << *(array + count) << " ";
}
return 0;
}
void swap(int *num1, int *num2)
{
//Keep record of original value of num1
int tempNum;
tempNum = *num1;
*num1 = *num2; //num1 value has been changed
*num2 = tempNum; //Fetch the original value of num1 and assign it to num2
}
int *getNumbers(int size)
{
int *array;
array = new int[size];
srand(time(0));
for(int i = 0; i < size; i++)
{
array[i] = rand() % 100;
}
return array;
}
Here is the correct code.
#include <iostream>
#include <cstdlib>
using namespace std;
void swap(int *, int *);
int *getNumbers(int);
int main() {
//Get the size of the array from keyboard
int arraySize;
cout << "How many integers would you like to declare: ";
cin >> arraySize;
//Initialize array
int *array;
array = getNumbers(arraySize); //getNumbers should return a pointer
//Print out original array
cout << "Original array" << endl;
for (int count = 0; count < arraySize; count++) {
cout << *(array + count) << " ";
}
//Sort array using the swap function
//Have a for loop to swap numbers one by one from min to max
//Compare values using a second for loop
//Swap values if former value is larger
//swap(&array[i],&array[j]);
for (int i = 0; i < arraySize; i++) {
for (int j = 0; j < (arraySize - 1); j++) {
if (array[j] > array[j + 1]) {
/*********** This line was changed ***********/
swap(&array[j+1], &array[j]); // You were earlier swapping ith and jth entries.
/*********************************************/
}
}
}
//Print out sorted array
cout << "\nSorted Array" << endl;
for (int count = 0; count < arraySize; count++) {
cout << *(array + count) << " ";
}
return 0;
}
void swap(int *num1, int *num2) {
//Keep record of original value of num1
int tempNum;
tempNum = *num1;
*num1 = *num2; //num1 value has been changed
*num2 = tempNum; //Fetch the original value of num1 and assign it to num2
}
int *getNumbers(int size) {
int *array;
array = new int[size];
srand(time(0));
for (int i = 0; i < size; i++) {
array[i] = rand() % 100;
}
return array;
}
You were swapping array[i] with array[j] in line 32. array[j] and array[j+1] should be swapped. Also, as pointed out by dd2, your loop bounds are not strict. The code would work correctly nonetheless but would take more steps. You can change the bound to j < (arraySize - i - 1)
Your loop bounds are not correct and swapping was wrong as well.
for(int i = 0; i < arraySize; i++)
{
for(int j = 0; j < (arraySize - i - 1); j++)
{
if(array[j] > array[j + 1])
{
swap(&array[j], &array[j+1]);
}
}
}
I'm new to C++ so bear with me.
I am trying to create a histogram from certain parameters (interval size, length of array containing quantities of numbers, highest number yadayada).
The details are irrelevant and a problem for myself to fiddle with, although I think I got the correct formula in my function.
When I assign variables from the C++ IO "cin" I can output those with the "cout" call, however, when I call my histogram function, also containing "cout" instructions, nothing gets printed.
My code:
#include <iostream>
#include <cmath>
using namespace std;
void histogram(int l, int n, int k, int *a)
{
int quantity = 0;
for (int i = 1; i <= l; i++)
{
for (int j = 0; i < n; j++)
{
if (a[j] >= (i-1) * k || a[j] <= i * k)
{
quantity++;
}
}
cout << (i-1) * k + ": " + quantity << endl;
quantity = 0;
}
}
int main()
{
int l,n,k;
int *a;
a = new int[n];
cin >> l >> n;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
k = ceil((double)a[0]/l);
// cout << k;
histogram(l,n,k,a);
return 0;
}
There might be something funky going on with this line and string concatenation:
cout << (i-1) * k + ": " + quantity << endl; You might try rewriting as cout << ((i-1) * k) << ": " << quantity << endl; just to ensure that things are adding and concatenating correctly.