what if i swap an element with -1 index of array - c++

// ques-move all negative ele to one side
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
int arr[n];
for(int i=0;i<n;i++){
cin >> arr[i];
}
int j=-1;
int pivot = 0;
for(int i=0;i<n;i++){
if(arr[i]<pivot){
swap(arr[i],arr[j])
i++;
}
}
return 0;
}`
if we swap 1st index with -1 th index if it is negative then what will happen will a garbage value take place at arr[1]

Accessing an array outside of its bounds of 0 to n-1 is undefined behavior. The most likely outcome is a garbage value, but literally anything could happen - your program could crash, you could erase your entire disk drive, or demons could fly from your nose.

Related

Counting elements in an array greater than next element C++

Why is it giving wrong count
In this question we have to find out how many elements are greater than the next element of an array
#include
using namespace std;
int main() {
//number of testcases
int t;
cin>>t;
while(t--){
//taking number of elements in an array
int n,count;
cin>>n;
//taking array
int a[n];
count=0;
for(int i=1;i<=n;i++){
cin>>a[n];
}
//checking array
for(int j=1;j<=n-1;j++){
if(a[j]>a[j+1])
{
count++;
}
}
cout<<count<<endl;
}
return 0;
}
Input
5
1 2 3 4 1
Expected Output
1
Output through above code
2
There are several problems with your code:
Problem 1
You're going out of bounds of the array a which leads to undefined behavior, when you wrote
cin >> a[n]; //undefined behavior
Note that indexing of arrays starts from 0 instead of 1 in C++.
Problem 2
In standard C++, the size of an array must be a compile-time constant. This mean the following is incorrect in your code:
int n;
cin>>n;
int a[n]; //NOT STANDARD C++ BECAUSE n IS NOT A CONSTANT EXPRESSION
Better would be to use std::vector instead of built in array.
int n = 0;
std::cin >> n;
std::vector<int> a(n); //this creates a vector of size n
//take input from user
for(int& element: a)
{
std::cin >> element;
}
int count = 0;
for(int i = 0; i< n - 1; ++i)
{
if(a[i] > a[i+1])
{
++count;
}
}

Partition of Array by Element given X

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 want to print array in reverse order, I tried to code for the same as shown in the attached picture but I am not understanding why is 0 being shown?

this is the code which I tried
int main(){
int n;
cout<<"Type the number of elements\n";
cin>>n;
cout<<"Type the integars";
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<"This is the reversed array ";
for(int i=n;i>=0;i--){
cout<<arr[i]<<" ";
}
return 0;
}
this is the output pls explain why is 0 coming where did I go wrong?
The problem is that your reversed array starts at n, and arr[n] is invalid, because the array starts at 0.
for (int i = n - 1; i >= 0; i--) {
cout << arr[i] << " ";
}
Your array is of size 5, but you're accessing 6 elements instead 5. That is, you are accessing elements 5...0 (6 in total) when the array only has 4...0 (5 in total) elements.
Start the 2nd for loop with n-1 and that should solve your issue. That is, (for(int i=n-1;i>=0;i--)) instead of (for(int i=n;i>=0;i--))
Solution: To print use i = n - 1
int main(){
int n;
cout<<"Type the number of elements\n";
cin>>n;
cout<<"Type the integars";
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<"This is the reversed array ";
for(int i=n-1;i>=0;i--){
cout<<arr[i]<<" ";
}
return 0;
}
Arrays begin counting at zero through to n (n being the target size value), so you need to ignore the zero value and start printing after zero has been iterated through.
Something like:
counter = target -1
When printing the reverse of array make sure you remember the position of elements is always one less.
So you have to start with n-1. '0' is getting printed because it is the garbage value at that position it could have been any number or value.
int main(){
int n;
cout<<"Type the number of elements\n";
cin>>n;
cout<<"Type the integars";
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<"This is the reversed array ";
// When printing the reverse of array make sure you remember the position of elements is always one less.
// So you have to start with n-1. '0' is getting printed because it is the garbage value at that position it could have been any number or value.
for(int i=n-1;i>=0;i--){
cout<<arr[i]<<" ";
}
return 0;
}

Why is IDEone showing runtime error even after getting the output?

What is wrong with my program ?
It works fine on my PC but in IDEone it gives the correct output but shows runtime error. Please help.
#include<bits/stdc++.h>
using namespace std;
struct student
{
int vote;
};
int main()
{
int t;
cin>>t;
while(t--)
{
int count=0;
int n;
cin>>n;
vector <int> a(n);
student s[n];
int k;
cin>>k;
for(int i=1;i<=n;i++)
{
s[i].vote=0;
}
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
int temp=0;
for(int i=1;i<=n;i++)
{
if(a[i] != i)
{
temp=a[i];
s[temp].vote++;
}
}
for(int i=1;i<=n;i++)
{
if(s[i].vote==k)
{
count++;
}
}
printf("%d\n",count);
}
return 0;
}
This is the error shown in IDEone :-
Error in `./prog': free(): invalid next size (fast): 0x085cca10
student s[n];
This declares an array called s. It contains n values. The values are s[0] through s[n-1] (you can count them all on your fingers, if you'd like, using a small number of n, such as 5).
for(int i=1;i<=n;i++)
{
s[i].vote=0;
}
This attempts to initialize values s[1] through s[n]. The only problem is that s[n] doesn't exist. The last value in the array is s[n-1]. This code will corrupt memory on the stack, resulting in undefined behavior.
The same bug also occurs with the a array.
The index values for both vector and array are zero based and goes up to n - 1. So
for(int i = 0; i != n; ++i)
would be better.
Now you write one element too far, which free finds out later when the data after the memory block is invalid.

Random number displayed before my sorting

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.