Program crashes when I try to input values - c++

so I've got integers m and n in my program, once you input the values it should create an array with values from m to n (for example m = 1 and n = 10, it creates array q with values from 1 to 10). Then it looks in the array if there are any numbers that are equal to any two number summ that are squared (for example, in the array, number 5 is equal to 1 squared + 2 squared). The problem is when I try to input the first value it crashes, pretty sure the problem is in the function but can't seem to figure it out. Thanks
#include <iostream>
using namespace std;
int squared (int a, int b, int q[]){
while (a<=0 || b<=0){
cout <<"You can't input an integer that is 0 or below: ";
cin >>a;
cin >>b;
if (a>0 || b>0) break;
}
for (int p=0; p<b; p++){
for (int i=a ; i<b; i++){
q[p] = a;
}
}
for (int z=0; z<b; z++){
for (int x=0; x<b; x++){
for (int c=0; c<b; c++){
if (q[z] == (q[x] * q[x]) + (q[c] * q[c])){
int result= (q[x] * q[x]) + (q[c] * q[c]);
return result;
}
}
}
}
}
int main () {
int m,n;
int M[100];
cout <<"Input integers m un n: ";
cin >>m,n;
cout <<squared(m,n,M);
return 0;
}

Most likely it crashes because of this: cin >>m,n;, it should be cin >> m >> n;, else you use n uninitialized on the next line, thus getting undefined behaviour, e.g. crash.
What compiler are you using and with what flags, since this would trigger some warnings/errors at compile normally.

cin >> m, n; is incorrect which inputs only m which can be interpreted as:
(cin >> m), n; which means: cin, n; to correct it:
cin >> m >> n;
if(a > 0 || b > 0) break; is redundant because you check for this condition twice: once in while condition second inside while loop thus checking for the same condition is redundant because while breaks automatically if the condition succeeds (a or b is equal or smaller than 0).
you passed an array without passing its size, you are lucky if you set the first element 1 the any second value is equal to the size of array eg:
m = 1; n = 10; then the size is ten which is correct.
what about:
m = 7; n = 10; // now is size 10? it's only 3
to correct it pass the size eg:
m = 4; n = 8;
int size = 8 - 4;
cout << Squared(m, n, M, size);
also:
for (int p = 0; p < b; p++)
{
for (int i = a ; i < b; i++)
{
q[p] = a;
}
}
you are assigning the same value a to all elements of array and iterating doing the same thing in the nested-loop!!! it's likely to write:
int x = 0; x = 0;
so the condition of result inside squared will never succeed because the same value is never equal to its square. 4 = 4 * 4 is never reached
here is what you search for:
#include <iostream>
using namespace std;
// I only make squared search for the result not inputing m and n lik e in yours
int squared (int m, int n, int* M)
{
int result;
for(int i(0); i < n; i++)
for(int j(0); j < n; j++)
for(int k(0); k < n; k++)
if( (M[i] == ( (M[j] * M[j]) + (M[k] * M[k]) )) && j != k) // here to avoid comparing with the same index
{
cout << M[i] << " = (" << M[j] << "*" << M[j] << ") + (" << M[k] << "*" << M[k] << ")" << endl;
result = ( (M[j] * M[j]) + (M[k] * M[k]) );
cout << result << endl;
return result; // if success we return result
}
return -1; // otherwise we return -1 as a sign of error (no square yields in negative value)
}
int main ()
{
int n, m, size;
do
{
cout <<"m: ";
cin >> m;
cout << "n: ";
cin >> n;
if(n <= 0 || m <= 0)
cout <<"You can't input an integer that is 0 or below: ";
// also it's very important to check whether n is greater than m or not because if m == n or m > n then size will be negative and as you know no array has a negative nor 0 size
if(m >= n)
cout << "n must be greater than m!" << endl;
}while (m <= 0 || n <= 0 || m >= n);
size = n - m; // getting size of array assuming m can be any value
int* M = new int[n - m]; // allocating dynamic array
// inputting array as you asked
for(int i(0), j = m; i < size; i++, j++)
M[i] = j;
// checking the values of array elements
for(int i = 0; i < size; i++)
cout << M[i] << ", " ;
cout << endl;
// getting the result
cout << squared(m, n, M) << endl;
// cleaning
delete[] M;
return 0;
}

Related

How to print out all the steps in Merge Sort?

I'm a 2nd year college student and we have this subject Data Structures and Algorithm and a newbie. My professor gives me task to code the merge sort algorithm but she lately added that it needs to display the partition (the image that I posted) in my code. This is the sample image that I want to have in my code after the "1st Partition". Thank you in advance I wish you all safe and sound!
and this is my code
#include <iostream>
using namespace std;
//Merge two sub arrays L and M into collection'
//(array, lower bound, mid bound, upper bound)
//(array, 0, 3, 7)
void merge(int collection[], int p, int q, int r, int series) {
// Create L <-- A[p..q] and M <-- A[q+1..r]
// n1 = 3 - 0 + 1
// n1 = 4
int n1 = q - p + 1;
// n2 = 7 - 3
// n2 = 4
int n2 = r - q;
// L[4], M[4]
int L[n1], M[n2];
//for (int i = 0; 0 < 4 ; i++)
for (int i = 0; i < n1; i++)
//L[0,1,2,3] = collection[0,1,2,3] = [3,10,21,47]
L[i] = collection[p + i];
//for (int j = 0; 0 < 4 ; j++)
for (int j = 0; j < n2; j++)
//M[0,1,2,3] = collection[4,5,6,7] = [4,15,38,59]
M[j] = collection[q + 1 + j];
// Maintain current index of sub-arrays and main array
int i, j, k;
i = 0;
j = 0;
k = p;
//If else statement to determine whether (ASCENDING) lowest to highest or (DESCENDING) highest to lowest
if(series == 1){
// Until we reach either end of either L or M, pick larger among
// elements L and M and place them in the correct position at A[p..r]
// (0 < 4 && 0 < 4)
while (i < n1 && j < n2) {
//if ( 3 <= 4 )
if (L[i] <= M[j]) {
//collection[0] = 3
collection[k] = L[i];
i++;
} else {
collection[k] = M[j];
j++;
}
k++;
}
}else{
while (i < n1 && j < n2) {
if (L[i] >= M[j]) {
collection[k] = L[i];
i++;
} else {
collection[k] = M[j];
j++;
}
k++;
}
}
// When we run out of elements in either L or M,
// pick up the remaining elements and put in A[p..r]
while (i < n1) {
collection[k] = L[i];
i++;
k++;
}
while (j < n2) {
collection[k] = M[j];
j++;
k++;
}
}
//------------------------MERGING-----------------------------
// Divide the array into two subarrays, sort them and merge them
//(array, lower bound, upper bound)
//(array, 0, 7)
void mergeSort(int collection[], int lb, int ub, int sequence) {
//if (lower bound < upper bound)
//if (0 < 7)
if (lb < ub) {
// m is the point where the array is divided into two subarrays
// m = 0 + (7 -0) / 2
// m = 0 + 7 / 2
// m = 3
int mid = lb + (ub - lb) / 2;
//Call mergeSort
//mergeSort(collection, 0, 3)
mergeSort(collection, lb, mid, sequence);
//mergeSort(collection, 3 + 1, 7)
mergeSort(collection, mid + 1, ub, sequence);
// Merge the sorted subarrays
//merge(collection, 0, 3, 7)
merge(collection, lb, mid, ub, sequence);
}
}
//----------------OUTPUT---------------------
// Print the array
void printArray(int collection[], int scale) {
for (int i = 0; i < scale; i++)
cout << collection[i] << " ";
cout << endl;
}
//---------------MAIN PROGRAM----------------
// Driver program
int main() {
int array_size;
int order;
cout << "Instructions. Enter array size with a minimum of 4 and maximum of 16" << endl;
cout << "Enter array size: ";
cin >> array_size;
cout << endl;
if (array_size <=3 || array_size >= 17){
cout << "Your array size is maybe below or above the array size limits. Please try again" << endl;
exit(0);
}
cout << "In what order do you want to sort your numbers? Press [1] ASCENDING, [2] DESCENDING" << endl;
cout << "Enter: ";
cin >> order;
cout << endl;
int collection[array_size];
cout << "Enter " << array_size << " numbers: ";
for (int u = 0; u < array_size; u++){
cin >> collection[u];
}
int scale = sizeof(collection) / sizeof(collection[0]);
cout << endl;
cout << "Before Sorting: \n";
printArray(collection, scale);
mergeSort(collection, 0, scale - 1, order);
cout << "1st Partition:";
//RIGHT HERE
cout << endl;
cout << "Sorted Array: \n";
printArray(collection, scale);
return 0;
}

How to create an array to scale from 0 until user input

I am trying to create a program that prints out an array based on user input. The array needs to start from 0 and scale to the number enter by user. So if user inputs 5 the the array values will be [0][1][2][3][4][5]. For some reason my code just prints out 0.
#include <iostream>
using namespace std;
int main() {
cout << "Enter the value of n: ";
int n;
cin >> n;
int *arr1 = new int[n];
for(int i = 0; i < n; i ++){
arr1[i] = 0;
}
cout << *arr1 << endl;
delete [] arr1;
return 0;
}
There are few bugs in your code.
You expect the output to be [0][1][2][3][4][5] when the n = 5. Therefore your output has (n + 1) elements. So your array should also have (n + 1) elements.
int *arr1 = new int[n + 1];
In your code you assign 0 to each element in your array. But you expect the array to contain 0, 1, 2, .., n
for(int i = 0; i < n + 1; i++){
arr1[i] = i;
}
In your code, you only print the first element. *arr1 is same as arr1[0]. So another for loop is required to print the each element in your array.
for(int i = 0; i < n + 1; i++){
cout << "[" << arr1[i] << "]" << endl;
}
Then you will get the output [0][1][2][3][4][5] when the n = 5

Generating all R-digit numbers among N digits in C++ (combinations, iterative)?

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.

previous row element of array also getting updated

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};

Forming Heap Using array

I am trying to form a heap using the following code ,But not sure why its not showing the correct output.
#include <iostream>
using namespace std;
int h[10], n;
void heapbottom()
{
int i, j;
for (i = n / 2; i >= 1; i--) {
int k = i;
int v = h[k];
bool heap = false;
while (!heap && 2 * k <= n) {
cout << "\n i value is :" << i;
j = 2 * k;
if (j < n) //there sre 2 children
{
if (h[j] < h[j + 1])
j++;
}
if (v >= h[j])
heap = true;
else {
h[k] = h[j];
k = j;
}
h[k] = v;
} //end of while
}
cout << "\n HEAP GENERATED \n";
for (int i = 0; i < n; i++)
cout << "\n ELEMENT IS:" << h[i];
}
int main()
{
cout << "\n Enter the maximum number of array elements \n";
cin >> n;
cout << "\n Enter the array to perform heap sort \n";
for (int i = 0; i < n; i++)
cin >> h[i];
heapbottom();
return 0;
}
If I change the outer loop to be
for (i = n / 2; i >= 0; i--)
I get 9 8 7 6 5 2 as a result, which I believe is a valid heap.