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.
Related
I have a question about the exercise from my course:
Write a program that takes array of real numbers as parameter and replaces each element that is smaller than average of the first and last element, by this average. This is my code:
#include <iostream>
#include <string>
using namespace std;
void replaverage(int arr[], int n)
{
for (int i; i < 6; i++) {
cout << "Enter the numbers" << endl;
cin >> arr[i];
}
int f = arr[0];
int l = arr[n - 1];
double av = f + l / 2;
for (int i; i < n; i++) {
if (arr[i] < av) {
arr[i] = av;
}
}
}
int main()
{
int n;
int arr[n];
replaverage(arr, n);
cout << arr << " " << endl;
return 0;
}
Code is working, however as an output, it is giving some kind of address "0x7fff2306a5c0". I'm beginner so I apologize, maybe my error is stupid but I don't know how to fix it. Thanks for helping!
#include <iostream>
#include <string>
using namespace std;
void replaverage(int arr[], int n)
{
for (int i = 0; i < n; i++) {
cout << "Enter the number: ";
cin >> arr[i];
cout << endl;
}
int f = arr[0];
int l = arr[n - 1];
double av = (f + l) / 2;
for (int i = 0; i < n; i++) {
if (arr[i] < av) {
arr[i] = av;
}
}
}
int main()
{
int n = 6; // Making 6 since you had it hardcoded
int arr[n];
replaverage(arr, n);
for (int i = 0; i < n; i++) {
cout << arr[i] << endl;
}
return 0;
}
First problem: Initialize your loop counters to 0;
Second problem: Initialize n in main being passed as parameter to
something
Third problem: Your average calculation is incorrect. It should be (f+l) / 2. Otherwise it will be doing l/2 + f, which is incorrect.
Fourth problem: You need to loop over your array to see all the
elements
I want to count how many times does algorithm makes comparisons and how many times algorithm makes copying.
#include <stdio.h>
#include <random>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <time.h>
void generuoti(int _N, const char *_file);
void nuskaityti(const char *_file);
int ps = 0;
int ks = 0;
void heapify(double arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
ps+=1;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
ps += 1;
// If largest is not root
if (largest != i)
{
std::swap(arr[i], arr[largest]);
ps += 1;
ks += 1;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// pagr funkcija haep sortui
void heapSort(double arr[], int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--)
{
// Move current root to end
std::swap(arr[0], arr[i]);
ks+=1;
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
void insertion_sort(double arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
ks+=1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
ks+=1;
ps+=1;
}
arr[j + 1] = key;
ks+=1;
}
}
using namespace std;
double *Data;
double* A;
double* B;
double N;
int main()
{
srand(time(NULL));
cout << "Generuojame atsitktinius duomenis" << endl;
generuoti(20000, "duom.txt");
cout << "Nuskaitome duomenis" << endl;
nuskaityti("duom.txt");
A = new double[(int)N];
B = new double[(int)N];//jeigu algoritmui reikia papildomo masyvo
for (int i = 0; i < N; i++) {
A[i] = Data[i];
}
cout << "Pradine skaiciu seka:" << endl;
for (int i = 0; i < N; i++)
cout << A[i] << " ";
cout << endl;
//
insertion_sort(A, N);
//heapSort(A, N);
//truksta veiksmu sk
cout << "Surusiuota skaiciu seka:" << endl;
for (int i = 0; i < N; i++)
cout << A[i] << " ";
cout << endl;
cout << "Kopijavimu skaicius " << ks << endl;
cout << "Palyginimu skaicius " << ps << endl;
system("pause");
return 0;
}
void generuoti(int _n, const char *_file) {
ofstream os(_file);
os << _n << endl;
for (int i = 0; i<_n; i++)
os << " " << 500+ (double)(rand() % 3001) ;
os.close();
}
void nuskaityti(const char *_file) {
ifstream is(_file);
if (is.fail()) {
cout << "Failo nera" << endl;
exit(1);
}
is >> N;
Data = new double[(int)N];
for (int i = 0; i < N; i++) {
is >> Data[i];
}
}
This is my code, and ps - is equal to a number of comparisons, and ks - is equal to number of copying. I want to ask if I counted all comparisons and all copying in the algorithms? Thanks for answers.
No
if (l < n && arr[l] > arr[largest])
largest = l;
ps+=1;
There are two problems here. Assuming you are talking about double comparisons (rather than integer), the comparison may or may not occur.
Secondly your indentation is deeply misleading. (You always increment.)
You need
if (l < n) {
ps++; // About to compare
if (arr[l] > arr[largest])
largest = l;
}
There are probably other errors, but it is impossible to tell because I can't read your language, so the printed text, comments, and names are meaningless.
Given you are writing in C++, I would write a class with operator <() and operator =, and a copy constructor, and instrument those. That way you cannot possibly get it wrong.
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
in this program i am separating integers from a character array which consists of a space between them
#include<iostream>
#include<stdio.h>
#include<conio.h>
using namespace std;
int main()
{
int i = 0, t, l = 0, j, c, k, q = 0, num = 0;
char ch[10][10];
int ach[10][1];
cout << "enter the number of test cases";
cin >> t;
for (i = 0; i < t; i++)
{
fflush(stdin);
cin.getline(ch[i], 9);
}
for (i = 0; i < t; i++)
{
num = 0;
for (j = 0; ch[i][j] != '\0'; j++) //calculating length
{
l = j;
}
l = l + 1;
for (j = 0; j < l; j++)
{
if (ch[i][j] == ' ') //finding the space
c = j;
}
for (k = 0; k < c; k++) //taking first integer out of char array
{
q = ch[i][k] - 48; //parsing char to int
num = (num * 10) + q;
}
cout << "\n previous row element " << ach[0][1] << "\n"; //checking the value
ach[i][0] = num; // this statement is updating the previous row's last element of the array
cout << "\n previous row element " << ach[0][1] << "\n"; //checking the value
cout << ach[i][0];
num = 0;
q = 0;
for (k = c + 1; k < l; k++) //taking second element out of char array
{
q = ch[i][k] - 48; //parsing char to int
num = (num * 10) + q;
}
ach[i][1] = num;
cout << ach[i][1];
}
for (i = 0; i < t; i++)
{
cout << "\n" << ach[i][0] << "\t" << ach[i][1] << "\n"; //displaying the values
}
getch();
return 0;
}
I have marked the code that is malfunctioning , it is updating the previous row's last element. please help.
Oups your code is not really optimized and is mainly C with the exception of cin.getline. But your real problem is that with int ach[10][1], ach is a 2D array of size 10x1, so ach[i][1] may not be what you expect because you should define int ach[10][2] to safely use it. The rules for array indexes computing give &(ach[i][1]) == &ach[0][0] + i*1 + 1 so you are actually accessing ach[i+1][0] with a possible past end array access if i is 9.
Moreover, at first access, ach[0][1] is used without being first initialized.
So your ach definition should be:
int ach[10][2] = {0};
I am trying to learn C++, arrays and pointers. I decided to implement the insertion sort algorithm. So, here is my code and my wrong output. What should I do to correct it? Can you please tell me what is my mistake and what should I avoid if it is a common error?
My code:
// InsertionSort.cpp
#include "stdafx.h"
#include <iostream>
int DeclareAnInteger();
int* DeclareAndShowTheArray(int n);
int* InsertionSort(int *A, int n);
int main()
{
int n = DeclareAnInteger();
int *A;
A = DeclareAndShowTheArray(n);
int *B;
B = InsertionSort(A, n);
system("PAUSE");
return 0;
}
int DeclareAnInteger()
{
int n;
std::cout << "Please enter a positive integer n: ";
std::cin >> n;
return n;
}
int* DeclareAndShowTheArray(int n)
{
int *A;
A = (int *)alloca(sizeof(int) * n);
for (int i = 0; i < n; i++)
{
std::cout << "Please enter the value of A[" << i + 1 << "]: ";
std::cin >> A[i];
}
std::cout << "The unsorted array is: ";
for (int i = 0; i < n; i++)
{
std::cout << A[i];
std::cout << "\t";
}
std::cout << "\n";
return A;
}
int* InsertionSort(int *A, int n)
{
int k;
//int *A = new int[n];
for (k = 1; k < n; k++)
{
int key = A[k];
int m = k - 1;
while (m >= 0 & A[m] > key)
{
A[m + 1] = A[m];
m = m - 1;
}
A[m + 1] = key;
}
std::cout << "The sorted array is: ";
for (int i = 0; i < n; i++)
{
std::cout << A[i];
std::cout << "\t";
}
std::cout << "\n" << std::endl;
return A;
}
My output:
This here is a big problem:
A = (int *)alloca(sizeof(int) * n);
The alloca function allocates on the stack, and it will be lost when the function returns which gives you a stray pointer and undefined behavior when you dereference this pointer.
If you're programming C++ then use new, if you program C then use malloc.