Reputation: 11
I'm new in C programming language, and I try to practice my skills in this language.
I'm coding an exercise about a matrix, where the user inputs the number of the column that wants to sort and print the column sorted (I'm using the bubble sort), but the program doesn't show me the answer.
This is my implementation of the problem.-
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
void bubble(int *array);
void print(int *array);
int main(){
/*Este programa toma una columna y la ordena*/
int fil=4, col=4;
int matrix[fil][col];
for(int i=0;i<fil;i++){
for(int j=0;j<col;j++){
matrix[i][j]=rand()%10+1;
}
}
for(int i=0;i<fil;i++){
for(int j=0;j<col;j++){
printf("%d\t",matrix[i][j]);
}
printf("\n");
}
int a, aux[col];
printf("\nColumna a ordenar: ");
scanf("%d",&a);
for(int i=0;i<fil;i++){
for(int j=0;j<col;j++){
if(j==a){
aux[j]=matrix[0][j];
}
bubble(aux);
}
}
getche();
}
void bubble(int *array){
int length= sizeof(array)/sizeof(array[0]);
int aux;
for(int i=length-2;i>=0;i--){
for(int j=0;j<=i;j++){
if(array[j]>array[j+1]){
aux=array[j];
array[j]=array[j+1];
array[j+1]=aux;
print(array);
}
}
}
}
void print(int *array){
int length= sizeof(array)/sizeof(array[0]);
for(int i=0;i<length;i++){
printf("%d",array[i]);
}
}
And, which book or tutorial should i follow to master the c language (C)?
Upvotes: 1
Views: 579
Reputation: 909
As for which book, I can recommend nothing other than Kernighan and Ritchie's "The C Programming Language".
Upvotes: 0
Reputation: 15002
First : using
int length= sizeof(array)/sizeof(array[0]);
cannot give you the number of elements of an array. Indeed, sizeof(array)
will give you the size in memory of the pointer.
In C/C++, you must pass the number of elements of your arrays as an argument for the function using it. So your functions should be like :
void bubble(int *array, int size);
void print(int *array, int size);
Second : your loop
for(int i=0;i<fil;i++){
for(int j=0;j<col;j++){
if(j==a){
aux[j]=matrix[0][j];
}
bubble(aux);
}
}
is unlikely to fill the aux
array properly. Maybe something like :
int a, aux[fil];
printf("\nColumna a ordenar: ");
scanf("%d",&a);
for(int i=0;i<fil;i++){
aux[i] = matrix[i][a];
}
bubble(aux, fil);
print(aux, fil);
rather than this double loop ?
Upvotes: 2
Reputation: 608
Look at the third "for" loop in your main().
for(int i=0;i<fil;i++){
for(int j=0;j<col;j++){
if(j==a){
aux[j]=matrix[0][j]; //Should be aux[i]=matrix[i][j] here, or you're actually putting everything in aux[a], since j==a.
}
bubble(aux);
}
}
Also, you should define aux as aux[fil]. Since fil==col, it's ok here. But aux is intended to be used to store a column instead of a row, so if your fil isn't eqaul to col, there would be problems.
You can write it like this:
int aux[fil];
for(int i=0;i<fil;i++)
aux[i]=matrix[i][a];
bubble(aux);
Upvotes: 0