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
Related
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;
I have a C++n insertion sort function template, and it works fine when I give the function an array of integers, but when I give the function an array of doubles, although the array is indeed sorted afterwards, for some reason it alters the numbers in the sorted array.
The code:
#include <iostream>
#include <stdlib.h>
using namespace std;
template <typename T>
void insertionSort(T ary[10], int size)
{
// Printing unsorted array
cout << "Array before sorting: [";
for (int i = 0; i < size; i++)
{
cout << ary[i] << ", ";
}
cout << "]" << endl;
// Beginning of sorting
int j, t;
for(int i = 1; i < size; i++)
{
for (int i = 0; i < size; i++)
{
j = i;
while(j > 0 && ary[j] < ary[j-1])
{
t = ary[j];
ary[j] = ary[j-1];
ary[j-1] = t;
j--;
}
}
}
// Printing sorted array
cout << "Array after sorting: [" ;
for (int i = 0; i < size; i++)
{
cout << ary[i] << ", ";
}
cout << "]\n" << endl;
}
int main()
{
cout << "*** INTEGER ARRAY INSERTION SORT ***" << endl;
int intAry[10] = {0};
for (int i = 0; i<= 9; i++)
{
intAry[i] = rand() % 100;
}
insertionSort(intAry, 10);
cout << "*** DOUBLE ARRAY INSERTION SORT ***" << endl;
double dAry[10] = {0};
for(int i = 0; i<=9; i++)
{
dAry[i] = (double)rand() / RAND_MAX * 100;
}
insertionSort(dAry, 10);
return 0;
}
The output:
You can see here that it changes the number in the array of doubles, like 14.1603 to 14.
Thank you for any help!
The problem is, you want to compare the double numbers, but when you're going through the loop, you use the int i and int j variables. Result is incorrect due to incompatible data type.
if you covert "double" the "int" data types, your problem will be solved.
Also you must change your array type to double.
My merge sort doesn't work correctly, it can sort the first values, but the last value "7" gets replaces with a "4".
I can't seem to figure out why.
I have already tried to adjust the n,q,p values to a 0-index array, but that doesn't help.
I have also tried to adjust the n1 and n2 values, but again with no luck
#include <iostream>
#include <limits>
using namespace std;
// p = start of array
// q = center of array
// r = end of array
int A[8] = {2,4,5,7,1,2,3,6};
int p = 1; //Start value of the array
int q = 4; //Middle value of the array
int r = 8; //End value of the array
int L[4]; //Making a new array with 4 slots
int R[4]; //Making a new array with 4 slots
int n1 = q-p+1; //Range of the left array
int n2 = r-q; //Range of the right array
int main(){
for (int i = 0; i < n1; i++){ //Putting the first 4 values in the
"left" array
L[i] = A[p+i-1];
}
for (int j = 0; j < n2; j++){ //Putting the last 4 values in the
"right" array
R[j] = A[q+j];
}
int m = 0;
int n = 0;
for (int z = 0; z < 8; z++){ //The sorting algorithm
if (L[m] <= R[n]){
A[z] = L[m];
m = m+1;
}
else{
A[z] = R[n];
n = n+1;
}
}
cout << "Left array: ["; //Printing out the arrays
for (int k = 0; k < 4; k++){
cout << L[k] << " ";
}
cout << "]"<< "\n";
cout << "Right array: [";
for (int k = 0; k < 4; k++){
cout << R[k] << " ";
}
cout << "]"<< "\n";
cout << "Sorted A: [";
for (int k = 0; k < 8; k++){
//cout << L[k] << '\n';
//cout << R[k] << '\n';
cout << A[k] << " ";
}
cout << "]"<< "\n";
return 0;
}
Gives the output:
Left array: [2 4 5 7 ]
Right array: [1 2 3 6 ]
Sorted A: [1 2 2 3 4 5 6 4 ]
Because you don't limit the index of L and R, In the last comparison, the R array overflows. n = 4 , R[4] is unexpected.
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.
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};