How to create an array to scale from 0 until user input - c++

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

Related

C++: Console outputting weird numbers when printing array [duplicate]

This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
What happens when I print an uninitialized variable in C++? [duplicate]
(4 answers)
Closed 4 months ago.
I'm beginning to learn about C++. I've been putting it off for a long time and I decided to start learning it.
Currently, I'm having trouble finding the issue with my program. My program is supposed to take integers from the input, insert it into an array, and then sort it. Everything is working correctly-- even the sorting... most of the time...
Sometimes the sorting works as intended. Sometimes it spits the numbers out in random orders. Sometimes it output really weird negative and positive integers that are very close to the upper and minimum bounds that integers can go. After hours of trying to figure out something about this, I just can't figure it out. I've been thinking that it has something with the pointers for the array? But I'm unsure because I barely know how pointers work.
I've tried setting the array to hard-coded values and sorting with different algorithms, none of which helped whatsoever.
#include <iostream>
/*Sorting program*/
using namespace std;
int* sortArray(int* array, int size) {
for (int i = 0; i < size; i++) {
int lowest;
for (int k = i; k < size; k++) {
if (array[k] < array[i] && array[k] < array[lowest]) {
cout << array[k] << " is less than " << array[i] << endl;
lowest = k;
}
}
int temp = array[lowest];
array[lowest] = array[i];
array[i] = temp;
}
return array;
}
int main() {
int low, high, target, size;
cout << "Enter size of array : ";
cin >> size;
int *array = new int[size];
for (int i = 0; i < size; i++) {
cout << "Enter array[" << i << "] : " << endl;
int entry;
cin >> entry;
array[i] = entry;
}
/* */
array = sortArray(array, size);
for (int i = 0; i < size; i++) {
cout << "array[" << i << "] = " << array[i] << endl;
}
return 1;
}
Output
>>OutputFile.exe
Enter size of array : 4
Enter array[0] :
3
Enter array[1] :
4
Enter array[2] :
7
Enter array[3] :
4
array[0] = 2059292487
array[1] = 3
array[2] = 4
array[3] = 7
Output (program ran again, nothing changed)
>>OutputFile.exe
Enter size of array : 8
Enter array[0] :
3
Enter array[1] :
4
Enter array[2] :
8
Enter array[3] :
1
Enter array[4] :
88
Enter array[5] :
4
Enter array[6] :
5
Enter array[7] :
6
array[0] = 1
array[1] = 3
array[2] = 4
array[3] = 4
array[4] = 5
array[5] = 6
array[6] = 8
array[7] = 88
In your sorting algorithm,
if (array[k] < array[i] && array[k] < array[lowest]) {
cout << array[k] << " is less than " << array[i] << "\n";
lowest = k;
}
Changes to lowest index to k every time that k < i.
This means that even if the array has smaller values in k, the last value in the list that happened to be smaller than i will be swapped with i.
This is why your list is being answered back strangely.
To fix it, you need to have the smallest value of the list (or part being checked) change each iteration of the loop.
int *sortArray(int *array, int size) {
int lowest_index; //initialized variable(s)
//bubble-sort algorithm from front to back, smallest to largest
for (int i = 0; i < size-1; i++) { //go through entire array (except the first since it is being compared as the "smallest" for the moment)
int lowest_index = i; //initialize as something within the [part of the] array [being analyzed], they may all be equal.
for (int j = i+1; j < size; j++) { //go through each remaining element of the array
if (array[j] < array[lowest_index]) { //comparison to smallest found element
cout << array[j] << " is less than " << array[i] << "\n";
lowest_index /*for this loop*/ = j;
}
}
//swap front item (i) with smallest found in previous loop
int temp = array[lowest_index];
array[lowest_index] = array[i];
array[i] = temp;
}
return array;
}
So, the good news is that you're learning the language itself just fine; keep at it!
I assume as selection sort algorithm.
/*Sorting program*/
using namespace std;
int *sortArray(int *array, int size) {
for (int i = 0; i < size; i++) {
int lowest = i;
for (int k = i; k < size; k++) {
if (array[k] < array[i] && array[k] < array[lowest]) {
cout << array[k] << " is less than " << array[i] << endl;
lowest = k;
}
}
int temp = array[lowest];
array[lowest] = array[i];
array[i] = temp;
}
return array;
}
int main() {
int low, high, target, size;
cout << "Enter size of array : ";
cin >> size;
int *array = new int[size];
for (int i = 0; i < size; i++) {
cout << "Enter array[" << i << "] : " << endl;
int entry;
cin >> entry;
array[i] = entry;
}
/* */
array = sortArray(array, size);
for (int i = 0; i < size; i++) {
cout << "array[" << i << "] = " << array[i] << endl;
}
return 1;
}
int lowest = i;

Array Sum with Pointers i have a problem in the sum

I have this code. and I have a problem with it. When I run it for these numbers "1,1,1,1,1" it answers me right but when I use these numbers "2,1,3,2,2" or any other numbers it answers me wrong. What is the problem?
#include <iostream>
using namespace std;
int main() {
int size = 5;
int array1[size];
int i, j, *p;
int sum = 0;
p = &array1[j];
for (int i = 0; i < size; i++) {
cout << "give next number";
cin >> array1[i];
cout << "\n";
}
cout << "the array is:"
<< "\n";
for (int j = 0; j < size; j++) {
cout << array1[j] << "\n";
sum = sum + *p;
}
cout << "the sum of array elements is: " << sum;
return 0;
}
So you have one problem
p = &array1[j];
What you are doing is taking the address of jth element of an array. In you case j is uninitialized which leads to UB since j might contain any variable.
To fix this you can initialize j to 0 (j = 0). Or to just get an address of first element in array you can do following:
p = array;
Than comes your loop, which is summit value at address of arr[j] which is UB as I stated above.
cout << "the array is:" << "\n";
for (j = 0; j < size; j++) {
cout << array1[j] << "\n";
sum = sum + *(p + j);
}
Your problem here was that you were adding array1[0] all the time. (That is if you initialized j to 0).
Other things to note is that you are re declaring i and j
int i, j, *p;
...
for (int i = 0; ...)
...
for (int j = 0; ...)
You could do just
for (i = 0; ...)
...
for (j = 0; ...)
to set already declared variables to 0.
Here is entire program:
#include <iostream>
int main() {
int size = 5;
int array1[size];
int i, j, *p;
int sum = 0;
// p = &array1[j]; // UB j not initialized but used
/* solution 1
j = 0;
p = &array1[j]
*/
// solution 2 which is same as solution 1
p = array1; // gets address of array[0]
for (i = 0; i < size; i++) { // no need for `int` in front of i
// i is already declared above
// my preference is to declare i here
// and remove declaration above
std::cout << "give next number";
std::cin >> array1[i];
std::cout << "\n";
}
std::cout << "the array is:"
<< "\n";
for (j = 0; j < size; j++) { // same as above
std::cout << array1[j] << "\n";
sum = sum + *(p + j);
}
std::cout << "the sum of array elements is: " << sum;
return 0;
}
input:
give next number5
give next number4
give next number3
give next number2
give next number1
output
the array is:
5
4
3
2
1
the sum of array elements is: 15

I cannot display the index containing the highest value of integer. but i can display the highest value of integer in the array

I cannot display the index containing the highest value of integer. but i can display the highest value of integer in the array.
Here's my code:
#include <iostream>
#include<stdlib.h>
using namespace std;
int main () {
int a[10], highest,temp = 0;
do{
cout<<"Enter 10 Numbers: ";
cin>>a[temp];
temp++;
}while(temp !=10);
for(int j = 0; j <10; j++){
if(a[0]<a[j]){
highest = j;
}
}
for(int x = 0; x <10; x++){
if(a[0]<a[x]){
a[0] = a[x];
}
}
cout<<"The highest number is "<<a[0] <<" at index "<<highest<<endl;
system("pause");
return 0;
}
For starters do not use magic numbers as for example the number 10 in your program. Use named constants instead.
Also declare variables in the minimum scope where they are used.
This loop
for(int j = 0; j <10; j++){
if(a[0]<a[j]){
highest = j;
}
does not make sense because it searches the last element in the array that is greater than the element a[0]. It is not the same as searching the index of the greatest element.
Also as the variable highest is not initialized then in general the program has undefined behavior.
Instead of two loops you can use one loop that finds the index of the greatest element.
Here is a demonstrative program that shows how it can be done.
#include <iostream>
int main()
{
const size_t N = 10;
int a[N];
std::cout << "Enter " << N << " umbers: ";
for ( size_t i = 0; i < N; i++ ) std::cin >> a[i];
size_t max = 0;
for ( size_t i = 1; i < N; i++ )
{
if ( a[max] < a[i] ) max = i;
}
std::cout << "The highest number is " << a[max]
<< " at index " << max << std::endl;
return 0;
}
Its output might look like
Enter 10 umbers: 7 2 3 0 9 1 8 6 4 5
The highest number is 9 at index 4
Take into account that there is standard algorithm std::max_element declared in the header <algorithm> that finds the maximum element in a sequence and returns iterator/pointer to it.
For example
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
const size_t N = 10;
int a[N];
std::cout << "Enter " << N << " umbers: ";
for ( size_t i = 0; i < N; i++ ) std::cin >> a[i];
int *max_value = std::max_element( a, a + N );
std::cout << "The highest number is " << *max_value
<< " at index " << std::distance( a, max_value ) << std::endl;
return 0;
}
The program output might look as shown above
Enter 10 umbers: 7 2 3 0 9 1 8 6 4 5
The highest number is 9 at index 4
The first part of your code detects the highest index of an element that is larger than the first element, not of the element that has the highest value of all:
for(int j = 0; j <10; j++){
if(a[0]<a[j]){
highest = j;
}
}
This is because you always compare to a[0] (which does not change), rather than to the highest value reached so far.
The second loop for finding the highest value itself, in contrast, works because you change a[0] to the "local" maximum found so far.
for(int x = 0; x <10; x++){
if(a[0]<a[x]){
a[0] = a[x]; // remembers the maximum found so far for further comparisons
}
}
You could easily combine both as follows. Note (as a minor thing) that it is sufficient to start from 1:
int indexOfMax = 0;
for(int x = 1; x <10; x++){
if(a[0]<a[x]){
a[0] = a[x]; // remembers the maximum found so far for further comparisons
indexOfMax = x; // stores the index of this element.
}
}
As long as you are storing the highest value in a[0] you need to swap it with the new greater values if found after each iteration a bit of some code in your program should look like:
for(int j = 0; j <10; j++){
if(a[0]<a[j]){
int tmp = a[0];
a[0] = a[j];
a[j] = tmp;
highest = j;
}
}
A simple, readable example looks like:
int a[10], highest = -1, highestIndex = -1;
for(int i(0); i < 10; i++){
cout<<"a[" << i << "]: ";
cin >> a[i];
}
for(int i = 0; i < 10; i++){
if(a[i] > highest){
highest = a[i];
highestIndex = i;
}
}
cout << "The highest number is " << highest << " at index " << highestIndex << endl;
Please don't ask for a while-do loop you can handle it.

Program crashes when I try to input values

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

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