I am trying to input 10 numbers and then call the function(sorting) to sort them in ascending order. After sorting it, the main program will also call the function getAvg to average the numbers in the array. However, after putting 10 values into the array. There are some random numbers displayed before my output.
What am I doing wrong?
#include<iostream>
#include<stdio.h>
using namespace std;
void sorting(int array[]) {
int t;
int x=0;
for (x=0; x<10; x++)
{
for (int y=0; y<9; y++)
{
if(array[y]>array[y+1])
{
t=array[y];
array[y]=array[y+1];
array[y+1]=t;
}
}
}
}
double getAvg(int array[]) {
double sum=0;
double avg=0;
for (int j=0;j<10;j++){
sum=sum+array[j];
}
avg=sum/10;
return avg;
}
int main()
{
int input=0;
int array[10];
double avg=0;
printf("%s","Enter the 10 temperatures \n");
for(int i=0;i<10;i++){
scanf("%i",&input);
array[i]=input;
}
sorting(array);
avg = getAvg(array);
for (int k=0;k<=10;k++){
cout<<array[k-1]<<" ";
}
printf("%s %.2lf %s","The average is ",avg, ".");
}
I think the error is in this code:
for (int k=0;k<=10;k++){
cout<<array[k-1]<<" ";
}
Notice that on the first iteration of the loop, you'll have k=0, so this tries to print out array index -1. This results in undefined behavior - technically speaking, anything can happen - and in your case it's reading garbage data from before the start of the array.
To fix this, change the loop bounds so that they properly range over the array:
for (int k=0; k < 10;k++){
cout<<array[k]<<" ";
}
My guess is that you realized that you were reading too far and tried to fix this by subtracting one from the array index, which just introduced a new bug. Hopefully this corrects this!
for (int k=0;k<=10;k++){
cout<<array[k-1]<<" ";
}
You are showing from -1 to 9, which means 11 values. The 1st value (array[-1]) was not initialized.
You need to change the k<=10 by k<10 and print array[k] instead of array[k-1]:
for (int k=0;k<10;k++){
cout<<array[k]<<" ";
}
The problem is that you are printing the elements at positions -1 through 9 of your array. There is no position -1.
Related
With this code I was trying to calculate unique ways to reach a certain sum by adding array elements with a dynamic programming approach, the program works correctly but takes more time than expected so I checked if it is storing calculated values in the my vector, but it not storing any values at all.
#include <iostream>
#include <vector>
using namespace std;
// recursive function to include/excluded every element in the sum.
long long solve(int N,int sum, int* coins, long long mysum, vector<vector<long long >> &my, long long j){
if (mysum == sum){
return 1;
}if (mysum>sum){
return 0;
}
if (my[mysum][j]!=-1){
return my[mysum][j];
}
long long ways = 0;
while (j<N){
ways+= solve (N,sum,coins,mysum+coins[j],my, j);
j++;
}
//Line in question
return my[mysum][j] = ways;
}
int main() {
// code here.
int N=3;
int coins[] = {1,2,3};
int sum =4;
int check = INT_MIN;
vector<vector<long long int>> my(sum+1,vector<long long int>(N+1,-1));
cout<< solve (N,sum,coins,0,my,0)<< " ";
// traversing to check if the memoizing vector stored the return values
for (int x=0; x<sum+1; x++){
for (int y=0; y<N; y++){
if (my[x][y]!=-1){
check = 0;
}
}
}
cout<< check;
return 0;
}
output: 4 -2147483648
It does store the values, your checking code is not correct.
Try this version in your check
for (int y=0; y<N+1; y++){ // N+1 not N
So, the problem is that j is incrementing because of the for loop. The function fills my[newsum][j] only after the for loop's scope is over. By that time j==N and only my[newsum][N] is filled, the preceding values of j are left empty. This can be solved by make another variable equal to j that isn't incremented.
I Am Trying To Find Partition Of Array ,On Condition By Checking Variable x ,when less then x they will be on one side or else on another. but my code need some correction.
HERE am not able to find the error , i will be thankful to you if you help me.
Code is:-
#include<iostream>
using namespace std;
int partition(int arr[],int n,int x){
for(int i=0;i<n;){
if(arr[i]<x){
i++;
}
else if(arr[i]==x){
int temp=arr[i];
arr[i]=arr[n];
arr[n]=temp;
i--;
}
else if(arr[i]>x){
int temp=arr[i];
for(int j=i;j<n;j++){
arr[j]=arr[j+1];
}
arr[n]=temp;
i--;
}
}
return 0;
}
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
int x;
cin>>x;
partition(arr,n,x);
for(int i=0;i<n;i++){
cout<<arr[i]<<"\t";
}
return 0;
}
Input >> array={2,10,15,1,3,15} ,x=10
Expected << {2,1,3,10,15,15}
Output I get << nothing .
The code isn't giving any output because, first, the "cin" and "cout" are in upper case which is syntactically incorrect, secondly, the variable j is in different case in loop statement and body inside the second else-if clause in the partition function, same goes for the "I" in the first for loop in the main() function. Sort this out and you should be good to go.
First in C++ the size of an array must be a compile-time constant. So for example, consider the following examples:
int n = 10;
int arr[n]; //INCORRECT
The correct way to write the above would be:
const int n = 10;
int arr[n]; //CORRECT
Similarly, in your code,
int n;
cin>>n;
int arr[n]; //INCORRECT because n is not a constant expression
Second, in your code, when you wrote:
arr[n] = temp; Undefined behavior
you're going out of bounds and so you have undefined behavior.
Solution
You can use std::stable_partition and std::vector to solve your problem as shown below:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
int n;
std::cout <<"Enter n:"<<std::endl;
std::cin >> n;
std::vector<int> arr(n); //create a vector of size n instead of an array
std::cout<<"Enter elements: "<<std::endl;
//iterate and take input from user
for(int &elem: arr){
std::cin >> elem ;
}
int x;
std::cout << "Enter x: "<<std::endl;
std::cin>>x;
//use std::partition
std::stable_partition(arr.begin(), arr.end(), [x](int i){return (i < x);});
std::cout<<"This is the partitioned vector: "<<std::endl;
for(int i=0;i<n;i++)
{
std::cout<<arr[i]<<"\t";
}
return 0;
}
Output
The output of the above program is as follows:
Enter n:
6
Enter elements:
2
10
15
1
3
15
Enter x:
10
This is the partitioned vector:
2 1 3 10 15 15
which can be seen here.
I am testing the ability to use functions to input values in 2 arrays and also to perform addition of the values. I wish to input the different values in the 2 arrays using a function inputArray(A1, A2, size) using a For loop.
I also used a function sumArray(A1, A2, size) to perform the addition of the 2 values in the arrays.
But the issue is with the input function as when i am running the program to input different values in the 2 arrays, the first array is also been attributed the value of the second array.
void inputArray(int Array1[], int Array2[], int n)
{
for(int i=0; i<n; i++)
{
cout<<"Array 1:"<<endl;
cin>>Array1[i];
cout<<" Array 2: "<<endl;
cin>>Array2[i];
cout<<endl;
//test
cout<<"\n\t A1[0]= "<<Array1[0]<<endl;
cout<<"\n\t A2[0]="<<Array2[0]<<endl;
}
}
I tried to use 2 different functions to input the values and this worked.But then again when i used a FOR loop for the Addition function sum = sumArray(A1, A2, size), both arrays A1 and A2 were being attributed the value of the second array.
int sumArray(int Array1[], int Array2[], int n)
{
int sum= 0;
for(int i=0; i<n; i++)
{
sum+= ( Array1[i] + Array2[i] );
cout<<"The total sum so far for values till position "<<i<<" is "<<sum<<endl;
}
//to monitor if the program is performing well with the addition
//test
cout<<"\n\t A1[0]= "<<Array1[0]<<endl;
cout<<"\n\t A2[1]="<<Array2[2]<<endl;
return sum;
}
#include<iostream>
using namespace std;
void inputArray(int Array1[], int Array2[], int n)
{
for(int i=0; i<n; i++)
{
cout<<"Array 1:"<<endl;
cin>>Array1[i];
cout<<" Array 2: "<<endl;
cin>>Array2[i];
cout<<endl;
//test
cout<<"\n\t A1[0]= "<<Array1[0]<<endl;
cout<<"\n\t A2[0]="<<Array2[0]<<endl;
}
}
//To sum all the values in the 2 arrays//not asked in the question
int sumArray(int Array1[], int Array2[], int n)
{
int sum= 0;
for(int i=0; i<n; i++)
{
sum+= ( Array1[i] + Array2[i] );
cout<<"The total sum so far for values till position "<<i<<" is "<<sum<<endl;
}
//to monitor if the program is performing well with the addition
//test
cout<<"\n\t A1[0]= "<<Array1[0]<<endl;
cout<<"\n\t A2[1]="<<Array2[2]<<endl;
return sum;
}
int main()
{
int size;
int A1[size];
int A2[size];
size= 3;
cout<<"Input "<<size<<" values in the first and second array: "<<endl;
inputArray( A1, A2, size); //do not write square bracket when calling a function
int sum = sumArray(A1, A2, size);
cout<<"The sum of the total values is : "<<sum<<endl;
//test
cout<<"\n\t A1[0]= "<<A1[0]<<endl;
cout<<"\n\t A2[1]="<<A2[2]<<endl;
return 0;
}
Here you use a non-initialised variable for the size of the two arrays.
int size;
int A1[size];
int A2[size];
This is in C++ wrong in more than one way.
You need to define C-like arrays with a constant size.
Safer would be to use C++ containers, e.g. std::vector for anything without predictable size.
Even in C, where VLAs are possible, creating them like you did and LATER reading in a new value for size will not change anything, especially not the size of the arrays.
Also, but that is already inside undefined behaviour and purely speculative,
if the compiler understands that as A1 and A2of size 0, then the start of both arrays is the same and writing to one writes also to the other - AND be totally forbidden because it will access beyond any arrays size.
To demonstrate that, try
int A1[5];
int A2[5];
I am trying to solve the program of array rotation. I am getting segmentation error in the code. Can someone please tell where is the problem in this code?
this is the question
Given an unsorted array arr[] of size N, rotate it by D elements (clockwise).
The first line of the input contains T denoting the number of testcases. First line of each test case contains two space separated elements, N denoting the size of the array and an integer D denoting the number size of the rotation. Subsequent line will be the N space separated array elements.
and i have solved it with the following code.
#include <iostream>
using namespace std;
int* rotate(int ar[],int n, int m)
{static int temp[100];
for(int i =0;i<m;i++)
{
temp[i]=ar[i];
}
for(int j =m;j<n;j++)
{
ar[j-m]=ar[j];
}
int x=0;
for(int k =n-m;k<n;k++)
{
ar[k]=temp[x];
x++;
}
return ar;
}
int main() {
//code
int t, n , m;
cin>>t;
while(t>0)
{
cin>>n>>m;
int arr[n];
int * ptr;
for(int i = 0 ;i<n;i++)
{
cin>>arr[i];
}
ptr=rotate(arr,n,m);
for(int j=0;j<n;j++)
cout<<ptr[j]<<" ";
cout<<endl;
t--;
}
return 0;
}
If m > n then it crashes in the first for() loop in rotate as you index past the end of arr.
If m < 0 it crashes in the 2nd loop as it index before arr.
There are probably more cases.
#include<iostream>
using namespace std;
int main()
{
int s;
cin>>s;
int t=3;
int maxValue,imax[t],maxIndex,arr[s];
for(int i=0; i<s; i++){
cin>>arr[i];
}
maxValue=arr[0];
for(int i=0;i<s;i++){
if(arr[i]>maxValue){
maxValue=arr[i];
imax[0] = i;
}
}
maxValue=arr[0];
for(int i=0;i<s;i++){
if (i == imax[0]) { continue; }
if(arr[i]>maxValue){
maxValue=arr[i];
imax[1] = i;
}
}
maxValue=arr[0];
for(int i=0;i<s;i++){
if (i == imax[0]) { continue; }
if (i == imax[1]) { continue; }
if(arr[i]>maxValue){
maxValue=arr[i];
imax[2] = i;
}
}
cout<<"First biggest number:"<<arr[imax[0]]<<"\n";
cout<<"Second biggest number:"<<arr[imax[1]]<<"\n";
cout<<"Third biggest number:"<<arr[imax[2]];
return 0;
}
This program must return tree numbers which is biggest in this arraybut , i do not know why when I introduce as example five numbers (121,34,56,67,545) and the compiler was return 545 and then crash.
Thank you in advance for the answer.
The problem is that before iterating the loop, you first set the maxValue to be the first element in the array. The imax only gets updated whenever there is at least one element greater than the current maxValue. However, if the first element is somehow the maxValue you are looking for, then the imax never gets set, which would be uninitialized causing segmentation fault at the end.
In your code, after finding the largest element 545, the second largest element was never found, since 121 is the first element in the array. Hence after printing out 545, imax[1] is uninitialized and the program crashes.
You use uninitialized array values in lines
cout<<"First biggest number:"<<arr[imax[0]]<<"\n";
cout<<"Second biggest number:"<<arr[imax[1]]<<"\n";
cout<<"Third biggest number:"<<arr[imax[2]];
If there are less than 3 different numbers in input, some imax array elements will not be initialized. Also if input array is empty, imax will not be initialized at all.
Therefore in expression arr[imax[1]] you read element of arr with index, which was not initialized and can be some very big number. It can be fixed if you declare iarr as
int imax[t] = {};
This will zero-initialize all elements of array and will prevent crashing.
Your program also doesn't check number of elements in input array, so if there are less than three input numbers arr[2] will also print uninitialized value.
Here's proper solution using STL algorithms and std::vector. It works with any number of t - you can easily change it to print largest 10 numbers. It is also memory efficient - it does not need to store whole input array so you can process large inputs with it.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
int s;
std::cin >> s;
unsigned t = 3;
std::vector<int> max_numbers;
max_numbers.reserve(t + 1);
for (int i = 0; i < s; ++i) {
int number;
if (std::cin >> number) { //Check basic input errors
max_numbers.push_back(number); // Add number to top-3 list
// Sort elements in descending order
std::sort(max_numbers.begin(), max_numbers.end(), std::greater<int>());
// Remove duplicates
max_numbers.erase(std::unique(max_numbers.begin(), max_numbers.end()),
max_numbers.end());
// Remove excess elements
if (max_numbers.size() > t) {
max_numbers.resize(t);
}
}
}
std::cout << "Biggest " << t << " numbers are" << std::endl;
for (int i : max_numbers) {
std::cout << i << std::endl;
}
}