bubble sorting and getchar in c - c++

I am working with microsoft visual studio 2012 and trying to make a bubble sort. Here is my code:
#include "stdafx.h"
#include "String.h"
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int array[100], n, c, d, swap;
printf("enter numbers of elements\n");
scanf_s("%d",&n);
printf("enter %d integers\n", n);
for (c = 0; c < n; c++){
scanf_s("%d", array);
}
for (c = 0; c < (n - 1); c++)
{
for (d = 0; d < n - c - 1; d++)
{
if (array[d]>array[d + 1]){
swap = array[d];
array[d] = array[d + 1];
array[d + 1] = swap;
}
}
}
printf("sorted list in ascending order:\n");
for (c = 0; c < n; c++){
printf("%d\n", &array[c]);
}
getchar();
return 0;
}
First of all I can't make console stay for a key entry. getchar() seems like not working but i don't have any error. Plus when I see console for a second, I can say that numbers are listed like "-310892". I don't know why.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main(void)
{
int array[100],n,c,d,flag,swap;
printf("Enter the no. of elements\n");
scanf("%d",&n);
for(c=0;c<n;c++)
{
scanf("%d",&array[c]); // here you have to add & for assigning a address to variable in memory
}
for(c=0;c<(n-1);c++)
{
flag=0;
for(d=0;d<n-c-1;d++)
{
if(array[d]>array[d+1])
{
swap=array[d];
array[d]=array[d+1];
array[d+1]=swap;
flag=1;
}
}
if(flag==0)
break;
}
printf("sorted elements in ascending order:\n");
for(c=0;c<n;c++)
{
printf("%d\t",array[c]);// you want to print the element not its address so no need of &
}
getch();
return 0;}
Please note i'm adding additional variable "flag" which helps to increase the efficiency of your program because the loop will break when your elements are done sorting but in your program the loop might be doing some extra iteration.

I fixed the typos that others mentioned and added system("pause"). Worked fine for me on VS 2010. Haven't got access to VS 2012 to test it. Here's your code:
#include <string.h>
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("enter numbers of elements\n");
scanf("%d",&n);
printf("enter %d integers\n", n);
for (c = 0; c < n; c++){
scanf("%d", &array[c]);
}
for (c = 0; c < (n - 1); c++)
{
for (d = 0; d < n - c - 1; d++)
{
if (array[d]>array[d + 1]){
swap = array[d];
array[d] = array[d + 1];
array[d + 1] = swap;
}
}
}
printf("sorted list in ascending order:\n");
for (c = 0; c < n; c++){
printf("%d\n", array[c]);
}
system("pause"); // <---- Added this!!!
return 0;
}
Hope it works fine for you too.

Concerning your bubble sort implementation:
your scanf_s in the first for loop always reads the number into the first position of the array.
your printf in the last for loop expects an integer but you supply an address.
To prevent the console from disappearing, you could replace getchar() by system("pause"), although this is not portable.
Correcting these things, the bubble sort works for me:
#include "stdafx.h"
#include "String.h"
#include <iostream>
using namespace std;
#include <string.h>
int main() {
int array[100], n, c, d, swap;
printf("enter numbers of elements\n");
scanf_s("%d",&n);
printf("enter %d integers\n", n);
for (c = 0; c < n; c++) {
scanf_s("%d", &array[c]);
}
for (c = 0; c < (n - 1); c++) {
for (d = 0; d < n - c - 1; d++) {
if (array[d] > array[d + 1]) {
swap = array[d];
array[d] = array[d + 1];
array[d + 1] = swap;
}
}
}
printf("sorted list in ascending order:\n");
for (c = 0; c < n; c++){
printf("%d\n", array[c]);
}
system("pause");
return 0;
}

Related

Getting error on submission for Kattis "OddGnome" problem. I am getting the right output locally, what is wrong with my code? C++

#include <stdio.h>
int main(){
int n, g, i;
scanf("%d\n", &n);
while(n--) {
int l = -1;
int c = 1;
scanf("%d", &g);
while(g--) {
scanf("%d", &i);
if (l == -1) l = i;
else if (i - 1 != l) break;
else l++;
c++;
}
fflush(stdin);
printf("%d\n", c);
}
}
I get all the outputs correctly, so I have no idea what could be wrong. On the other hand, Kattis accepts this code below that I found on GitHub, and the outputs are exactly the same as in my code. If anyone can explain to me what is wrong or why Kattis rejects my code I would appreciate it.
#include <bits/stdc++.h>
using namespace std;
int main()
{
//Initialize n and g, take in n
int n, g;
cin >> n;
//Iterate n times
while (n--)
{
//Take in g, initialize empty vector of size g
cin >> g;
vector<int> gnomes(g);
//Take in all the gnomes
for (int i = 0; i < g; i++) cin >> gnomes[i];
//Iterate through without the beginning or end since king won't be there
for (int i = 1; i < g-1; i++)
{
//Must break the order, and if you remove it the gnomes around it should be in order
if (gnomes[i] < gnomes[i-1] || gnomes[i] > gnomes[i+1] && gnomes[i-1] < gnomes[i+1])
{
//Output the 1 based index, so add 1
cout << i+1 << endl;
//And exit to the next group
break;
}
}
}
}
First of all, if you're using C++, use C++, not C!
As pointed out, fflush(stdin) is undefined behavior. Instead, you can use std::getline to chew up the rest of the line.
Other than that, your logic looks fine, even though it's a different approach than the overkill C++ solution. There's no need to check i + 1 or use a vector, as you seem to have deduced.
I suggest using clearer naming and whitespace conventions, though.
Here's a C solution, using scanf to read the rest of the line:
#include <stdio.h>
int main() {
int n;
scanf("%d\n", &n);
for (int i = 0; i < n; i++) {
int previous = -1;
int g;
scanf("%d", &g);
for (int j = 0; j < g; j++) {
int current;
scanf("%d", &current);
if (previous >= 0 && previous + 1 != current) {
printf("%d\n", ++j);
for (; j < g; j++) {
scanf("%d", &current);
}
break;
}
previous = current;
}
}
}
Here's a C++ solution that uses bits/stdc++.h and using namespace std;, which are common idioms in competitive programming but should never be used in any application code.
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int g;
cin >> g;
int previous = -1;
for (int j = 0; j < g; j++) {
int current;
cin >> current;
if (previous >= 0 && previous + 1 != current) {
cout << (1 + j) << "\n";
string s;
getline(cin, s);
break;
}
previous = current;
}
}
}

My program is exiting with return value 3221225620

I have written a cpp code for array rotation and the file handling part is a bit tricky for me.
The code itself is correct but even though the files are in the same directory as the code it is not working for some reason
#include <math.h>
#include <algorithm>
#include <bits/stdc++.h>
#include <iostream>
#include <fstream>
using namespace std;
int ar[100];
// #define crap ios_base::sync_with_stdio(false);cin.tie(NULL);
int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
void leftRotate(int arr[], int d, int n)
{
d = d % n;
int g_c_d = gcd(d, n);
for (int i = 0; i < g_c_d; i++) {
int temp = arr[i];
int j = i;
while (1) {
int k = j + d;
if (k >= n)
k = k - n;
if (k == i)
break;
arr[j] = arr[k];
j = k;
}
arr[j] = temp;
}
}
//int *func(int m)
//{
// int *p;
// p=new int[m];
// return (p);
//}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
// crap;
int n,d;
cin>>n>>d;
// ar=func(n);
// cout<<sizeof(ar);
for (int i=0;i<n;i++)
{
cin>>ar[i];
}
leftRotate(ar, d, n);
for (int i = 0; i < n; i++)
cout << ar[i] << " ";
return 0;
}
The code itself is working and returning correct output in the terminal but I cant seem to find the issue here
I have tried without file handling and it was giving a return value 3221225620 at the terminal
sample input is:
5 2
1 2 3 4 5
here shows a possible error:
3221225620 (0xC0000094): Zero Division Error
means that a divisor in your code could sometime be zero.
as for your code(line 20: d = d % n;), when your n is 0, the output will show return value 3221225620
so please check your data in "input.txt"

finding sum of numbers in a char array

I'm trying to find the sum of the numbers in a char array.
My code works for most cases. Example : a=dasn344wee22ee, the output is:366 - which is good
But when my char is,for example : andre54e5 the output should be 59, but the program displays: 108.
Can anybody tell me what the issue is?
#include <iostream>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
using namespace std;
int getnr(char a[], int i, int j)
{
int counter = 0;
char sir[1000];
for (int x = i; x<j; x++)
{
sir[counter] = a[x];
counter++;
}
return atoi(sir);
}
int main()
{
char a[1000];
int s = 0, inceput, finals;
cin.getline(a, 255);
for (int i = 0; i<strlen(a); i++)
{
if (isdigit(a[i]) )
{
if (i == strlen(a) - 1)
{
s += getnr(a, i, strlen(a));
}
for (int j = i + 1; j<strlen(a); j++)
{
if (!isdigit(a[j]) || j == strlen(a) - 1)
{
s += getnr(a, i, j + 1);
i = j;
break;
}
}
}
}
cout << s;
return 0;
}
In your function int getnr(char a[], int i, int j), you forgot to null-terminate string sir, such that atoi(sir) might yield a garbage value (actually the behaviour is undefined). The following should help:
int getnr(char a[], int i, int j)` {
...
sir[counter] = '\0';
return atoi(sir);
}
The problem is that getnr() doesn't add a null terminator to the sir array, so you're getting undefined behavior when you call atoi(sir).
int getnr(char a[], int i, int j)
{
int counter = 0;
char sir[1000];
for (int x = i; x<j; x++)
{
sir[counter] = a[x];
counter++;
}
sir[counter] = '\0';
return atoi(sir);
}
The issue is within this part of code:
if (i == strlen(a) - 1)
{
s += getnr(a, i, strlen(a));
}
Specifically, if your last number is a single digit (which it is), it will always return junk.
So, I would change to only convert the single char of the char array as a digit and at it to the int s.
Edit:
For some reason when doing s+= a[i], I return junk.
But, doing the following, does the trick:
if (i == strlen(a) - 1)
{
string x;
x[0] = a[i];
int l = stoi(x);
s += l;
}
I know that there's a much more effective way, but I'm not sure why s+= a[i] itself returns false numbers.

Outputting differences in arrays

I have to make a code where the user inputs altitude readings and the code is supposed to output total climb, total descent, and net change. This is what I have below. I can't figure out how to code to have it output what I want it to.
#include <iostream>
using namespace std;
int main()
{
int array[2010], n, c, d, swap; //the array
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c=0; c < n; c++)
scanf("%d", &array[c]);
for (c=0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n"); //lists in order
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
// Returns minimum difference between any pair
int findMinDiff(int arr[2010], int n); //supposed to find differce
{
// Initialize difference as infinite
int diff = INT_MAX;
// Find the min diff by comparing difference
// of all possible pairs in given array
for (int d=0; d<n-1; d++)
for (int j=d+1; j<n; j++)
if (abs(array[d] - array[d--]) < diff)
diff = abs(array[d] - array[d--]);
cout<<"Total Climb "<<diff<<endl;
}
system("pause");
return 0;
}
I don't see why you are sorting the array. Sorting the array may cause problems in calculating the "total climb" and "total descent".
My understanding is that this assignment is about calculating the difference between two numbers and processing that difference.
void Process_Data(int array[2010], unsigned int quantity_of_climbs)
{
int total_climb = 0;
int total_descent = 0;
int minimum_change = INT_MAX;
for (int i = 0; i < quantity_of_climbs - 1; ++i)
{
const int height_change = array[i] - array[i+1];
if (height_change > 0) // A "climb"
{
total_climb += height_change;
}
if (height_change < 0) // A "descent"
{
total_descent = (-1) * height_change; // Change from negative to positive.
}
const int abs_height_change = abs(height_change);
if (abs_height_change < minimum_change)
{
minimum_change = abs_height_change;
}
}
// Display results
}

My merge sort algorithm is taking too long for large file input?

well it's not exactly a merge sort, the algorithm counts the number on inversions in an array using merge sort (basically I just added one simple line)
it takes 2.415 seconds to read and merge sort 100,000 distinct integers from a text file while others who solved the same problem (on coursera.com) said it took them less than 0.5 seconds
here's my code, what went wrong? file reading maybe? thanks
#include <bits/stdc++.h>
using namespace std;
int a,b,i,j,n,x,k;
int t[100000]={0};
long long int s=0;
void merge(int a, int mid, int b)
{
i=a;
j=mid+1;
k=a;
int v[100000]={0};
while(i<=mid && j<= b)
{
if (t[i]<t[j])
{v[k]=t[i];
i++;
}
else
{v[k]=t[j];
j++;
s+=mid-i+1; //this line here counts the inversions
}
k++;
}
while(i<=mid)
{v[k]=t[i];
i++; k++;}
while(j<=b)
{v[k]=t[j];
j++; k++;}
for (i=a;i<k;i++)
t[i]=v[i];
}
void mergeSort(int a, int b)
{
if(a<b)
{
int mid=(a+b)/2;
mergeSort(a,mid);
mergeSort(mid+1,b);
merge(a,mid,b);
}
}
int main(){
ifstream fin("C:\\Users\\ASUS\\Desktop\\coursera.txt");
n=100000;
for(i=0;i<n;i++)
fin>>t[i];
mergeSort(0,n-1);
cout<<endl<<s;
}
One issue I could see is that in merge function, you allocate too much space, and the copy back also take quite O(N), which make the total copy time O(N * N) instead of O(N*Log(N)). Simple change to merge function could be like:
void merge(int a, int mid, int b)
{
i = a;
j = mid + 1;
k = 0;
int* v = new int[b - a + 1];
while (i <= mid && j <= b)
{
if (t[i]<t[j])
{
v[k] = t[i];
i++;
}
else
{
v[k] = t[j];
j++;
s += mid - i + 1; //this line here counts the inversions
}
k++;
}
while (i <= mid)
{
v[k] = t[i];
i++; k++;
}
while (j <= b)
{
v[k] = t[j];
j++; k++;
}
for (i = 0; i<k; i++)
t[a+i] = v[i];
delete[] v;
v = NULL;
}