C program for bubble sort using a minimum of 4 functions.(input,output,compute,main)
No global variables allowed.
No printf or scanf in compute.
No printf or scanf in main
Input should not call compute.
compute should not call output.
I haven't really understood pointers and functions.
#include <stdio.h>
void input(int* size, int* arr[])
{
printf("Enter the size of the array: ");
scanf("%d",size);
printf("Enter the elements of the array\n");
for(int i = 0;i < *size; i++)
{
scanf("%d", arr[i]);
}
}
void swap(int *x,int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void bubble_sort(int arr[100],int size)
{
for(int i = 0;i < size - 1;i++)
{
for(int j = 0;j < size - 1 - i;j++)
{
if(arr[j] > arr[j+1])
{
swap(&arr[j],&arr[j+1]);
}
}
}
}
void output(int size,int* arr)
{
printf("Sorted array\n");
for(int i = 0;i < size;i++)
{
printf("%d",arr[i]);
}
}
int main()
{
int* input_values[50];
int size;
input(&size, input_values);
bubble_sort(size,*input_values);
output(size, *input_values);
return 0;
}
No errors but showing segmentation fault.How do I solve this?
So your problem is here :
scanf(" %d", arr[i]);
You have to change this to :
scanf(" %d", &arr[i]);
This is the main problem, but there are a lot of others.
Also you have to change the order of parameters in
bubble_sort(size,*input_values);
to
bubble_sort(input_values,size);
and
output(size, *input_values);
to
output(size, input_values);
Also in order this to work at all i have changed the
scanf("%d", &arr[i]);
to
scanf(" %d", &arr[i]);
Actually your code is full of mistakes like the usage of scanf and the usage of pointers and arrays, the following is a workable version of you code see and compare:
#include <stdio.h>
void input(int* size, int arr[])
{
char chr;
printf("Enter the size of the array: ");
scanf( "%d%c", size, &chr );
printf("Enter the elements of the array\n");
for(int i = 0;i < *size; i++)
{
scanf("%d%c", &arr[i], &chr);
}
}
void swap(int *x,int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void bubble_sort(int* size,int arr[])
{
for(int i = 0;i < *size - 1;i++)
{
for(int j = 0;j < *size - 1 - i;j++)
{
if(arr[j] > arr[j+1])
{
swap(&arr[j],&arr[j+1]);
}
}
}
}
void output(int* size,int arr[])
{
printf("Sorted array\n");
for(int i = 0;i < *size;i++)
{
printf("%d",arr[i]);
}
}
int main()
{
int input_values[50];
int s = 0;
int* size = &s;
input(size, input_values);
bubble_sort(size,input_values);
output(size, input_values);
return 0;
}
Related
Why do I get segmentation fault 11? I get it quite often, and I know this time it is about the function. If anyone can help, please do, the code is down below! I am trying to make a program, that WITH A FUNCTION, can rearrange an array in ascending order and then print it in main in reverse order.
#include "stdio.h"
void changxr(int *counter, int *arrsize, int *j, int *arr[]);
int main()
{
int a, i, j, counter;
int arrsize;
int arr[100];
printf("pick an arraysize: \n");
scanf("%d", &arrsize);
printf("type %d numbers \n", arrsize);
for (counter = 0; counter < arrsize; counter++)
{
scanf("%d", &arr[counter]);
}
for (int c = arrsize - 1; c >= 0; c--)
{
printf("%d ", arr[c]);
}
changxr(&counter, &arrsize, &j, &arr[&counter]);
for (counter = arrsize - 1; counter >= 0; counter--)
{
printf("%d ", arr[counter]);
}
}
void changxr(int *counter, int *arrsize, int *j, int *arr[])
{
int a;
for (*counter = 0; *counter < *arrsize; *counter++)
{
for (*j = *counter + 1; *j < *arrsize; *j++)
{
if (*arr[*counter] > *arr[*j])
{
a = *arr[*counter];
*arr[*counter] = *arr[*j];
*arr[*j] = a;
}
}
}
}
New code:
#include "stdio.h"
void changxr(int arrsize, int *arr[]);
int main()
{
int a, i, j, counter;
int arrsize;
int arr[100];
printf("pick an arraysize: \n");
scanf("%d", &arrsize);
printf("type %d numbers \n", arrsize);
for (counter = 0; counter < arrsize; counter++)
{
scanf("%d", &arr[counter]);
}
for (int c = arrsize - 1; c >= 0; c--)
{
printf("%d ", arr[c]);
}
changxr(arrsize, &arr[counter]);
for (counter = arrsize - 1; counter >= 0; counter--)
{
printf("%d ", arr[counter]);
}
}
void changxr(int arrsize, int *arr[])
{
int a, counter, j;
for (counter = 0; counter < arrsize; counter++)
{
for (j = counter + 1; j < arrsize; j++)
{
if (*arr[counter] > *arr[j])
{
a = *arr[counter];
*arr[counter] = *arr[j];
*arr[j] = a;
}
}
}
}
This is what I got from debugging:
"Program received signal SIGSEGV, Segmentation fault.
0x0000555555555355 in changxr (arrsize=3, arr=0x0) at main.c:33
33 for(j=counter+1; j<arrsize; j++) { if(*arr[counter]>*arr[j]){
(gdb) continue"
You do not need two levels of indirection (int *arr[], *arr[counter], *arr[j]). When arr is passed to a function, it will decay to a pointer-to-its-first-element, or more simply, an int *.
&arr[counter] is also an int *, but it is the address of the array element one past the elements you've initialized. This would start your sorting function in the incorrect place.
Your program segfaults because it attempts to use this value as an int ** (int *[]).
gcc -Wall highlights this clearly:
prog.c: In function ‘main’:
prog.c:24:22: warning: passing argument 2 of ‘changxr’ from incompatible pointer type [-Wincompatible-pointer-types]
24 | changxr(arrsize, &arr[counter]);
| ^~~~~~~~~~~~~
| |
| int *
prog.c:3:32: note: expected ‘int **’ but argument is of type ‘int *’
3 | void changxr(int arrsize, int *arr[]);
| ~~~~~^~~~~
Things to do:
Simply pass the array and the length of the array to your function.
Use a single level of indirection in your function definition, and when accessing the array.
Use a variable-length array.
Use an auxiliary function for printing.
Declare variables when you need them, in the correct scope.
You should also consider checking the return value of scanf is the expected number of successful conversions.
The refactored code:
#include <stdio.h>
void changxr(int *a, size_t length)
{
for (size_t i = 0; i < length; i++) {
for (size_t j = i + 1; j < length; j++) {
if (a[i] > a[j]) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
void print_reverse(int *a, size_t length)
{
printf("[ ");
while (length--)
printf("%d ", a[length]);
printf("]\n");
}
int main(void)
{
size_t size;
printf("Pick an array length: ");
if (1 != scanf("%zu", &size) || size == 0) {
fprintf(stderr, "Invalid length input.\n");
return 1;
}
int array[size];
printf("Enter %zu numbers:\n", size);
for (size_t i = 0; i < size; i++) {
if (1 != scanf("%d", array + i)) {
fprintf(stderr, "Invalid integer input.\n");
return 1;
}
}
printf("Array (in reverse): ");
print_reverse(array, size);
changxr(array, size);
printf("Array, Sorted (in reverse): ");
print_reverse(array, size);
}
I can't figure out how to print array elements from my function into the main program so if some can examine this code and help me fix it I would appreciate it. The program is supposed to take the length of the array from user input and then ask for its elements and print them out afterward.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int arrayN(int N) {
printf("Input array lenght: ");
scanf("%d",&N);
if(N>2) {
return N;
} else {
return 0;
}
}
int arrayelements(int array[], int array_length) {
int loop, i, N;
array_length = arrayN(N);
printf("Enter elements of the array: \n");
for(int i = 0; i < array_length; ++i) {
scanf("%d", &array[i]);
}
for(loop = 0; loop < array_length; loop++) {
printf("%d ", array[loop]);
}
}
int main() {
int N, array[], array_length;
int b = arrayelements(array[], array_length);
int a = arrayN(N);
printf("Array length is: %d \n", a);
printf("Elements of array are: %d \n", b);
return 0;
}
I reworked your example code. Hope it is what you want.
Focus lied on fixing the array declaration issues, memory allocation and
user input.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
int userinput_integer(const char *fmt, ...){
int N, rv = 0;
va_list va;
va_start(va, fmt);
vprintf(fmt, va);
while(1){
rv = scanf("%d", &N);
if (1 == rv) break;
printf("Input error! The input >>");
do{
rv = fgetc(stdin);
if (isprint(rv)) putchar(rv);
}while(rv != EOF && rv != '\n');
printf("<< is not a valid integer.\nPlease try again: ");
}
va_end(va);
return N;
}
int userinput_arraylength(void) {
int N;
N = userinput_integer("Input array lenght: ");
if(N>2) {
return N;
} else {
printf("Invalid length\n");
return 0;
}
}
int userinput_arrayelements(int *array, int N) {
printf("Enter elements of the array: \n");
for(int i = 0; i < N; ++i) {
array[i] = userinput_integer("%d: ", i);
}
return N;
}
void print_arrayelements(int *array, int N){
for(int i = 0; i < N; ++i) {
printf("%d ", array[i]);
}
}
int main() {
int N, *array;
N = userinput_arraylength();
array = malloc(N * sizeof(*array));
if (NULL == array){
printf("Allocation error!\n");
exit(-1);
}
N = userinput_arrayelements(array, N);
printf("Array length is: %d \n", N);
printf("Elements of array are:\n");
print_arrayelements(array, N);
free(array);
return 0;
}
Fistly, declaration of array is not correct.
It should be array[] = {0}
Secondly, you cannot call your array elements function before arrayN function, the size of array should be entered first
And in the array elements() there is no need to call the size function you can directly pass the size of array when calling the array elements ()
Here's the code:
#include <stdio.h>
#include<malloc.h>
int *getarray()
{
int size;
printf("Enter the size of the array : ");
scanf("%d",&size);
int *p= malloc(sizeof(size));
printf("\nEnter the elements in an array");
for(int i=0;i<size;i++)
{
scanf("%d",&p[i]);
}
return p;
}
int main()
{
int *ptr;
ptr=getarray();
int length=sizeof(*ptr);
printf("Elements that you have entered are : ");
for(int i=0;ptr[i]!='\0';i++)
{
printf("%d ", ptr[i]);
}
return 0;
}
This question already has answers here:
Manipulate multidimensional array in a function
(4 answers)
Closed 8 years ago.
Could anyone explain why this doesn't print correctly?
This is basic program with functions to read and print an array. All seems to be according to what I read...
I'm new and can't seem to make pointers work.
Thanks in advance!
#include <stdio.h>
#include <stdlib.h>
#define SIZE 2
void readArray(int *a);
void printArray(int *a);
int main (int argc, char *argv[])
{
int array[SIZE][SIZE];
readArray(&array[SIZE][SIZE]);
printf("Array [1][2] = %d.\n\n\n", array[1][2]);
printArray(&array[SIZE][SIZE]);
system ("PAUSE");
return 0;
}
void readArray(int *a)
{
int i, j;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
printf("Array [%d] [%d]: ", i, j + 1);
scanf("%d \n",&a);
}
}
}
void printArray(int *a)
{
int i, j;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
printf("Array [%d] [%d]: ", i, j + 1);
printf("%d \n",*a);
}
}
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,a[2][2];
printf("Enter array\n");
for(i=0;i<2;i++) //take condition i<2 because of your default size
{
for(j=0;j<2;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Printing array\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",*(*(a+i)+j));
}
printf("\n");
}
getch();
}
try this code
So a user can create his square matrix and enter the desired values. The thing is that the matrix is created via a function and it seems that when the function is done with its task and we return to the main function and I try to reprint the elements of the matrix,to check if everything is ok again after the first printing inside the function, the program crashes. Have in mind that I'm using pointers only and not []s. Also the size variable is going to be used in functions that check various properties of the matrix(sparse etc) so that's why I use it like this.
#include <stdio.h>
#include <stdlib.h>
int CreateArray(int **ptr);
int main()
{
int **ptr = NULL;
int size = 0;
int i,j;
size = CreateArray(ptr);
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
printf("%d",*(*(ptr+i)+j));
if(j == (size-1))
{
printf("\n");
}
}
}
system("PAUSE");
return 0;
}
int CreateArray(int **ptr)
{
int i=0;
int j=0;
int size = 0;
printf("Input the size of your square matrix\n");
scanf("%d", &size);
ptr = malloc(sizeof(int*)*size);
for(i=0; i< size; i++)
{
*(ptr + i) = malloc(sizeof(int)*size);
}
printf("Enter the values to be stored in your array\n");
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d", &*(*(ptr+i)+j));
}
}
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
printf("%d",*(*(ptr+i)+j));
if(j == (size-1))
{
printf("\n");
}
}
}
return size;
}
Your pointer is passed by value. If you want to modify from within the function, you need to pass its address. You then need to re-adjust all lines within CreateArray that accessed ptr to dereference it once more:
int main()
{
int **ptr = NULL;
int size = 0;
int i,j;
size = CreateArray(&ptr);
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
printf("%d ",*(*(ptr+i)+j));
if(j == (size-1))
{
printf("\n");
}
}
}
return 0;
}
int CreateArray(int ***ptr)
{
int i=0;
int j=0;
int size = 0;
printf("Input the size of your square matrix\n");
scanf("%d", &size);
*ptr = malloc(sizeof(int*)*size);
for(i=0; i< size; i++)
{
*((*ptr) + i) = (int*)malloc(sizeof(int)*size);
}
printf("Enter the values to be stored in your array\n");
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d", (*((*ptr)+i)+j));
}
}
return size;
}
I'm having a hard time changing up this program. The algorithm is correct already for generating the non-repeating lists. However, I want the list to be generated from a range of the user's integer. (1 to n)
Ex: user inputs 5 -> prints (1 2 3 4 5) then asks for 5 integers to generate the combination(s).
How would I change this so that the combinations are found from (1-n) instead of individually entering the integers n times? Any help would be greatly appreciated.
(Sorry if it's messy, I'm a student :P)
#include<stdio.h> stdio.h
#include<stdlib.h> stdlib.h
int a1[50], a2[50]; // arrays
int count=-1, range;
int w; // user defined variable
void main()
{
printf("Please enter a number. (1-10): ");
scanf("%d", &w);
int x,y; // comparing
printf("You have entered %d\n\n",w);
for(range=1; range<=w; range++){
printf("%d", range);
printf(" ");
} // end for "range"
printf("\n");
for(x=0; x<w; x++){
a1[x]=0;
y=x+1;
scanf("%d\n\n" ,&a2[y]);
}// end for
combo(w);
} // end main
combo(int z) // function with algorithm to find combonations
{
while (w<1 || w>10){
printf("\nThat number is not in range. Please try again. \n\n");
printf("Please enter a number. (1-10): ");
scanf("%d", &w);
} // end while
int x;
a1[z]=++count;
if(count==w){
for(x=0; x<w; x++)
printf("%2d",a2[a1[x]]);
printf(" ");
} // end if
for(x=0; x<w; x++)
if(a1[x]==0)
combo(x);
count--;
a1[z]=0;
} // end "combo"
#include <stdio.h>
#include <string.h>
void swap (int *X, int *Y)
{
int temp;
temp = *X;
*X = *Y;
*Y = temp;
}
void print_array(int *a, int n) {
int i;
printf("\t=> ");
for(i = 0; i < n; i++){
printf("%d, ", a[i]);
}
printf("\n");
}
void mixmatch (int *Arr, int i, int n)
{
int j;
int *A = Arr;
if (i == n)
print_array(A,n+1);
else
{
for (j = i; j <= n; j++)
{
swap((A+i), (A+j));
mixmatch(A, i+1, n);
swap((A+i), (A+j));
}
}
}
int main()
{
int A[10];
int k;
int i;
printf("Enter a number between (1-10):");
scanf("%d", &k);
for(i = 0; i < k && i < 10; i++) {
printf("%d, ",i);
A[i] = i;
}
printf("\n");
mixmatch(A, 0, k-1);
return 0;
}
This is how you can modify it to incorporate integers and arrays of them.