Array - DS HackerRank in C - arrays

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);
}

Related

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;
}

Function for printing 2D arrays of uknown size in C

I'm new to C programming and I've run into a problem when creating 2D array printing function. When I try to execute the code below I get:
points.c:13: error: unknown array element size
As I've checked there are very similar codes online, which are supposed to work. I've tried to initialize function as
int print2DArray( int arrayLen, int elementLen, int array[arrayLen][elementLen])
but it raises:
points.c:3: error: 'arrayLen' undeclared
Could somebody tell me what's wrong with this code and how to fix it? I also don't understand why very similar function for 1D arrays works just fine. It has to be in pure C.
#include <stdio.h>
//supposed to print 2D array:
int print2DArray(int array[][], int arrayLen, int elementLen)
{
int i;
int j;
for (i = 0; i < arrayLen; i++)
{
for (j=0; j < elementLen; j++)
{
printf("%5d", array[i][j]);
}
printf("\n");
}
}
//prints 1D array:
int printArray( int array[], int arrayLen)
{
int i;
for (i = 0; i < arrayLen; i++)
{
printf("%d", array[i]);
}
}
--- edit ---
I undestand most of you pointed out that the function has to be called like that:
#include <stdio.h>
int print2DArray( int arrayLen, int elementLen, int array[arrayLen][elementLen])
{
int i;
int j;
for (i = 0; i < arrayLen; i++)
{
for (j=0; j < elementLen; j++)
{
printf("%5d", array[i][j]);
}
printf("\n");
}
}
This raises an error:
points.c:3: error: 'arrayLen' undeclared
I'm using tcc for windows and according to documentation it is supposed to support C99 VLA.
It appears OP's compiler (or the mode it is used) does not support variable length array (VLA) as a function parameter.
Below is a non-VLA approach.
void print2DArrayX(int arrayLen, int elementLen, const int *array) {
int i;
int j;
for (i = 0; i < arrayLen; i++) {
for (j = 0; j < elementLen; j++) {
printf("%5d", array[i*elementLen + j]);
}
printf("\n");
}
}
Call with address of first int, not the 2D array
#define ARRAY_LEN 3
#define ELEMENT_LEN 4
int array[ARRAY_LEN][ELEMENT_LEN] = { 0 };
...
print2DArrayX(ARRAY_LEN, ELEMENT_LEN, array[0]);
Ok, so thanks for all the answers - they were very helpful. I've just tried to use gcc in linux and as you've pointed out this approach works fine:
int print2DArray( int arrayLen, int elementLen, int array[arrayLen][elementLen])
I guess tcc (tiny c compiler, windows version 0.9.27) doesn't support VLA after all. A bit strange since documentation says it does.
How about you try this solution.
#include <stdio.h>
int print2DArray(int* array, int arrayLen, int elementLen)
{
int i;
int j;
for (i = 0; i < arrayLen; i++)
{
for (j=0; j < elementLen; j++)
{
printf("%5d ", *(array+j+elementLen*i));
}
printf("\n");
}
}
int main(){
int arr[2][6] = { {9,258,9,96,-8,5},
{1,1212,-3,45,27,-6}
};
print2DArray(*arr,2,6);
return 0;
}
Unless you are using a C99 compiler,
int print2DArray( int arrayLen, int elementLen, int array[arrayLen][elementLen])
is not possible.
Even if you are using C99 compiler, your code has a problem. You need to pass one of the dimension first.
int print2DArray(int arrayLen, int elementLen, int arr[][elementLen]);
So,
int print2DArray(int arrayLen, int elementLen, int arr[][elementLen])
{
// Your code
int i;
int j;
for (i = 0; i < arrayLen; i++)
{
for (j=0; j < elementLen; j++)
{
printf("%5d", array[i][j]);
}
printf("\n");
}
return 0;
}
This can be used as
int main(void)
{
int i32Array[3][3] = {{-15, 4, 36}, {45, 55, 12}, {-89, 568, -44568}};
int m = 3, n = 3;
// I am not sure why 'print2DArray' would return an int
// (or anything at all for that matter).
// If you can establish a case for it,
// modify the function and the value it is supposed to return,
// And catch it below.
print2DArray(m, n, i32Array);
return 0;
}
I am not sure how you are calling print2DArray function. Unless you post that piece of code, it is difficult to resolve your problem. Confirm that you are calling the function correctly as shown above.

Why my code is not printing the sorted array?

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++;
}

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.

C passing 2D array to function, printing results

I am trying to print a 2D array by passing it to a function, but I got weird results. Here is my code.
#include <stdio.h>
int main()
{
int b[2][3] = {{1,2,3},{4,5,6}};
printArray(b);
return 0;
}
void printArray(int (*ptr)[3])
{
int i, j;
for(i = 0; i < 2; i++)
{
for(j = 0; j < 3; j++)
{
printf("%d\t", *((*ptr+i)+j));
}
printf("\n");
}
}
However, the output is
1 2 3
2 3 4
I think it is something to do with my 'j' variable but I can't seem to pinpoint it. Please help.
You need to apply the addition operator before using the dereference operator. You need to use parenthesis as the dereference operator(*) has higher precedence than the addition operator(+).
So, this
printf("%d\t", *((*ptr+i)+j));
should be
printf("%d\t", *((*(ptr+i))+j));
or better
printf("%d\t", ptr[i][j]);
Also, you need to move the function printArray before main or provide a function prototype before main like:
void printArray(int (*ptr)[3]);
You need to multiply i by 3 before adding j ...
printf("%d\t", *((*ptr+(i*3))+j));
Abandoning indexes in favor of pointers, assuming matrix is stored by rows (whic is normally the case):
#include <stdio.h>
void printArray(int *);
int main()
{
int b[2][3] = {{1,2,3},{4,5,6}};
printArray((int*)b);
return 0;
}
void printArray(int *ptr)
{
int i, j;
for(i = 0; i < 2; i++)
{
for(j = 0; j < 3; j++)
{
printf("%d\t", *ptr++);
}
printf("\n");
}
}
Outputs:
1 2 3
4 5 6
printArray can take nb_column nb_line param and deal with all sort of 2D array
#include <stdio.h>
static void printArray(int *ptr, int nb_columns, int nb_lines)
{
int i, j;
for(i = 0; i < nb_lines; i++)
{
for(j = 0; j < nb_columns; j++)
{
printf("%d\t", *(ptr++));
}
printf("\n");
}
}
int main()
{
int b[2][3] = {{1,2,3},{4,5,6}};
printArray((int *)b, 3, 2);
return 0;
}

Resources