Why my code is not printing the sorted array? - c

Why the code isn't printing anything? what this code is supposed to do is sorting the 2d array in that way:
the 2d array represents a {x,y}, then the code needs to sort it, the rows which contain x < 0 need to be first and the rows with x>=0 need to be next.
the swap function here is to swap between two rows. now when I try printing the sorted array, I get nothing in the output
#include <stdio.h>
void swap(int p1[], int p2[]);
int arrange(int p[][2], int n);
void swap(int p1[], int p2[]){
for(int i=0; i<2; i++){
int temp=p1[i];
p1[i]=p2[i];
p2[i]=temp;
}
}
int arrange(int p[][2], int n){
int idx=0;
for(int i=0; i<n; i++){
if(p[i][0] >= 0 && (i+1)<n)
if(p[i+1][0] <0) {
swap(&p[i][0],&p[i+1][0]);
idx++;
}
else if(p[i][0]<0)
idx++;
}
return 1;
}
int main()
{
int a[4][2]={{1,2},{6,7},{-10,5},{0,1}};
arrange(a[4][2], 4);
for(int i=0; i<4; i++){
printf("{%d, %d}, ", a[i][0], a[i][1] );
}
}

Why the code isn't printing anything?
Because it doesn't compile, since your compiler should give errors and a warning.
In order to fix the errors, change this:
arrange(a[4][2], 4);
to that:
arrange(a, 4);
Appendix:
Here is what warning GCC with Wall flag passed to it gave me:
prog.cc: In function 'int arrange(int (*)[2], int)':
prog.cc:17:7: warning: suggest explicit braces to avoid ambiguous 'else' [-Wdangling-else]
17 | if(p[i][0] >= 0 && (i+1)<n)
|
In order to fix that warning, I changed your code to:
if(p[i][0] >= 0 && (i+1)<n) {
if(p[i+1][0] <0) {
swap(&p[i][0],&p[i+1][0]);
idx++;
}
} else if(p[i][0]<0) {
idx++;
}

Related

Array - DS HackerRank in C

The code is running fine on my Dev C++ IDE, but it keeps failing on the HackerRank IDE.
Am I making some mistake?
Here's a link to the problem:
https://www.hackerrank.com/challenges/arrays-ds/problem?isFullScreen=true
The function I wrote is as follows, please explain to me where am I going wrong?
int* reverseArray(int a_count, int* a, int* result_count) {
int i, j;
for(i=0; i<a_count; i++) {
result_count[i] = a[i];
}
for(j=a_count-1; j>=0; j--) {
printf("%d ",result_count[j]);
}
return result_count;
}
Your answer is corrct ,you copy the elements of array 1 from end to start in array 2
if you want to reverse your array in the same array,you just use variable temporary to swap the elements like this :
#include<stdio.h>
void* reverseArray(int a_count, int* a) //you return an array (type complexe) so ,you should use void
{
int temp=0;
for(int i=0; i<a_count/2; i++)
{
temp= a[a_count-i-1];
a[a_count-i-1]=a[i];
a[i]=temp;
}
for(int i=0; i<a_count; i++)
{
printf("%d ",a[i]);
}
}
int main()
{
int t[5]={1,2,3,4,5};
reverseArray(5,t);
}

How to print a 2D array?

I have two functions. One that creates a multiplication table of a given number and the other function prints the array out. Below is my code:
Here's the error (Line 18):
expression must be a pointer to a complete object type
How do I fix this error and print the array? Also, I don't know how to print a new line after every row.
#include "multiplication.h"
#include <stdio.h>
int arr[][];
void mulitpication(int num){
/* initialize array and build*/
int arr[num][num];
for(int i=0; i<num;i++){
for(int j=0;j<num;j++){
arr[i][j]= (i+1)*(j+1);
}
}
}
void print(int arr[][]){
/* print the arr*/
int i;
for(i=0;i<sizeof(arr);i++){
for(int j=0;j<sizeof(arr);j++){
printf("%d ",arr[i][j])**(line 18)**;
}
}
}
If using C99 or later with VLA support, pass into the print function the dimensions needed.
// void print(int arr[][]){
void print(size_t rows, size_t cols, int arr[row][col]){
size_t r,c;
for (size_t r = 0; r < rows; r++) {
for (size_t c = 0; c < cols; c++) {
printf("%d ",arr[r][c]);
}
printf("\n");
}
}
You need to declare the array in main(), so it can be passed to both functions.
When an array is passed as a function parameter, it just passes a pointer. You need to pass the array dimensions, they can't be determined using sizeof.
To get each row of the table on a new line, put printf("\n"); after the loop that prints a row.
#include <stdio.h>
void multiplication(int num, arr[num][num]){
/* initialize array and build*/
for(int i=0; i<num;i++){
for(int j=0;j<num;j++){
arr[i][j]= (i+1)*(j+1);
}
}
}
void print(int num, int arr[num][num]){
/* print the arr*/
int i;
for(i=0;i<num;i++){
for(int j=0;j<num;j++){
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
int main(void) {
int size;
printf("How big is the multiplication table? ");
scanf("%d", &size);
int arr[size][size];
multiplication(size, arr);
print(size, arr);
return 0;
}

Trying to write a program to fill an array with random numbers in C

My issue is that I am getting segmentation fault (core dumped) each time I try, I have yet to clean up my code, but I am stumped.
I must enter the values in with the compiler e.g "./filename 0 100" whereby 0 is min and 100 is max.
It must then fill the array of 10 elements with random numbers (0-100). I am so close, just can't fathom the main function.
Also, how can I print the array {0,1,2,3} in format "[0,1,2,3]" including the commas, without it looking like "[0,1,2,3, ]"
#include <stdlib.h>
#include <stdio.h>
int getRandom(int min, int max);
void fillArray(int data[], int size, int min, int max);
void printArray(int data[], int size);
int main(int argc, char *argv[]) {
int a;
int b;
if (argc>=3){
a = atoi(argv[1]);
b = atoi(argv[2]);
int arr[10];
printf("\t An array with random values from 0 to 100 \n");
fillArray(arr,10 ,a, b);
printArray(arr, 10);
} else {
printf("Incorrect number of arguments - please call with assignment min max\n");
}
return 0;
}
int getRandom(int min, int max) {
int result = 0;
int low = 0;
int high = 0;
if (min<max) {
low = min;
high = max+1;
} else {
low = max + 1;
high = min;
}
result = (rand() % (high-low)) + low;
return result;
}
void fillArray(int data[], int size, int min, int max){
int i;
for(i=min ; i < max+1; i++){
data[i] = getRandom(min,max);
}
}
void printArray(int data[], int size){
int i;
printf("[");
for(i=0; i<size; i++){
printf("%d,", data[i]);
}
printf("]");
}
I agree with #Steve Friedl that the main problem with your program lies in the fillArray function. There i should run from 0 to size.
As for your second question, testing whether you're printing the last number helps to suppress the unwanted comma:
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
printf("%d", data[i]);
if (i < size - 1)
printf(",");
}
printf("]");
}
If you prefer a more compact solution (although with an optimizing compiler there's not really a difference), you could write it as:
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
printf("%d%c", data[i], i < size-1 ? ',' : ']');
}
}
Also, in your main function, you should include a and b in your printing:
printf("\t An array with random values from %d to %d \n", a, b);
I believe this is blowing things up for you:
void fillArray(int data[], int size, int min, int max){
int i;
for(i=min ; i < max+1; i++){ // <-- HERE
data[i] = getRandom(min,max);
}
}
The calling function allocates 10 items in the arr array, and that's passed as the size parameter, but you're not using that parameter to limit filling up the array. If the max value is 100, then it's trying to fill one hundred slots instead of just ten.
for (i = 0; i < size; i++)
data[i] = getRandom(min,max);
should fix at least this issue.
EDIT: The comma thing, I prefer to add commas before the items unless this is the first. In this case it doesn't matter much, but it's more general, especially for variable-length lists where you don't know you're at the end until you get there. Augmenting the helpful response from #JohanC :
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
if (i > 0) printf(",");
printf("%d", data[i]);
}
printf("]");
}

Boubble sorting with arrays with C

#include <stdio.h>
int main(){
void sorting(){
int a[4];
a[0]=1;
a[1]=6;
a[2]=15;
a[3]=3;
a[4]=19;
int size = 4;
int t =1;
if (size ==0) return; // ie if you reach to the end stop
int i;
for (i=0;i<size-1;i++){
if(a[i+1] >a[i]) { //if the +1 element is bigger than before it do the swap
int j;
j= a[i+1];
a[i+1]=a[i]; //swap
a[i] = j; //swap
}
}
sorting(*a,size - 1);//recursion
void print_int() {
int i; // Loop counter
for (i = 0; i < 4; i++) {
printf("%d\n", a[i]);
}}
}
It compiles ok but when I try to run the file nothing appears? My intentions were to create an array sort them then display them.
Also, the code where the recursion happened "sorting(*a,size - 1);//"
if I tried to replace *a with a[] an error will happen. Why is that?
the error is "error expected expression before ']' token"!
thank you.
int a[4];
But you access a[4]=19; index 4 that is out of bound. You can access highest index 3.
I think function void sorting() should be defined outside main .Nested functions are GNU extensions in GCC.
Your code has to many problems. Here is a working Array sort:
#include <stdio.h>
void bubble_sort(int *array, int length){
int i,j, k, temp;
for (i = 0 ; i < length-1; i++){
for (k = 0 ; k < length-i-1; k++){
if (array[k] > array[k+1]){
temp = array[k];
array[k] = array[k+1];
array[k+1] = temp;
}
}
}
printf("The sorted Array List:\n\n");
for ( j = 0 ; j < length ; j++ ){
printf("%d ", array[j]);
}
}
int main(void){
int array[] = {1,6,15,3,19};
int length = sizeof array / sizeof array[0];
bubble_sort(array, length);
printf("\n");
return 0;
}
You should read about functions declarations and definitions.
About arrays you should know that if you declare:
int array[4];
Your working array is from 0 to 3 and not from 0 to 4.
Take a look at the following:
int main(void){
int array[] = {1,6,15,3,19};
int size = 5;
int i;
for(i=0;i<size;i++){
printf("%d ",array[i]);
}
return 0;
}
I have size=5 and not size=4- like you tried. You should be careful about number of Array elements.
Aside from all the problems spotted by others, you must repeatedly execute the for loop until no more exchanges are made, which is the standad way of bubbling. As you use recursion, it is of course nonsense to declare the array to be sorted (and its size) inside the function called recursively.

Recursive function for array integers

I have a function that takes an array a[] and its length n. I must calculate the sum of the numbers inside the array. I wrote this recursive function:
int somma(int a[], int n)
{
if (n == 0) { return 0; }
else {return a[n] + somma(a, n-1);}
}
And I call it in my main() in this way:
int main() {
int array[5], ris;
printf("Type the numbers of the array: \n");
for(int i=0; i<4; i++)
{
scanf("%d", &array[i]);
}
printf("\nThe sum is: %d.", somma(array,4));
getch();
return 0;
}
If the array contains array = [2; 4; 7; 5] the printf must show 18 (2+4+7+5). By the way the function returns me 88, can you help me?
I am using wxDevC++.
You are only reading the first four values in the array. array[4] contains garbage value
for(int i=0; i<5; i++) //change to 5
{
scanf("%d", &array[i]);
}
Your somma function is also wrong. It will always add 0 for arr[0].
if (n == -1) { return 0; } //change to this
You may try this:-
for(int i=0; i<=4; i++)
{
scanf("%d", &array[i]);
}
Also correct your somma
if (n == -1)
{
return 0;
}
If an array has n elements, then the last element has index n-1. Correct your somma function like this:
int somma(int a[], int n) {
if (n <= 0) {
return 0;
}
return a[n-1] + somma(a, n-1);
}
Additionally, there are two (minor) issues with your code:
Variable declaration inside for head in for(int i=0; i<4; i++) is not allowed by C89, only C99 and C++. Probably DevC++ compiles it because the file is treated as C++, but you should know that it won't compile on GCC, unless you use the -std=c99 switch.
getch is Windows-specific. On POSIX systems, use getchar instead.

Resources