String sorted in ascending order get garbled - c

I'm studing c programming language and want to sort string in ascending order. This is c code:
/* string sorted in ascending order */
#include <stdio.h>
#include <string.h>
void sort(char *name[],int n);
int main()
{
char *name[]={"Zai","Demo","CS","Apple"};
int i,n=4;
sort(name,n); // call sort function
for(i=0;i<n;i++)
{
printf("%s\n",name[i]);
}
}
void sort(char *name[],int n)
{
char *temp;
int i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n;j++)
{
if(strcmp(name[j],name[j+1])>0)
{
temp=name[j];
name[j]=name[j+1];
name[j+1]=temp;
}
}
}
}
I use the command:
gcc -o string_sort string_sort.c
./string_sort
But it can't work.This is error:
what should I do?

for(j=0;j<n;j++) has to be for(j=0;j<n-1;j++) because otherwise name[j+1]; will be out of range. With this change, it works. Also, j=0; isn't neccesary.

for(j=0;j<n;j++)
This line is crossing the bounds of the array. It should be:
for(j=0;j<n-1;j++)
As in the loop name[j+1]; will cross the bounds when j will be just 1 less then n.

#include <stdio.h>
#include <string.h>
void sort(char *name[],int n);
int main()
{
char *name[]={"Zai","Demo","CS","Apple"};
int i,n=4;
sort(name,n); // call sort function
for(i=0;i<n;i++)
{
printf("%s\n",name[i]);
}
}
void sort(char *name[],int n)
{
char *temp;
int i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++) //change at this line
{
if(strcmp(name[j],name[j+1])>0)
{
temp=name[j];
name[j]=name[j+1];
name[j+1]=temp;
}
}
}
}

Related

Passing a 2d array with pointers and accessing it gives segmentation fault

im trying to pass a 2D array from main to a function and trying to print it letter by letter
but it keeps giving me segmentation fault
note: the question im trying to solve as mentioned a function with parameter { ArrPrintMatrix(char *(p)[7]) }
so help me by keeping the above thing in mind
#include<stdio.h>
ArrPrintMatrix(char **p,int n) {
int i,j;
for(i=0;i<n;i++) {
for(j=0;j<10;j++) {
printf("%c ",p[i][j]);
}
}
}
main() {
int i;
char c[2][10];
puts("enter two strings");
for(i=0;i<2;i++)
scanf("%s",c[i]);
ArrPrintMatrix((char **) c,2);
}
You should use char p[2][10] not char** p
The following code could work:
#include <stdio.h>
void ArrPrintMatrix(char p[2][10], int n) {
int i;
for (i = 0; i < n; ++i)
printf("%s\n",p[i]);
}
int main() {
int i;
char c[2][10];
puts("enter two strings");
for(i=0;i<2;i++)
scanf("%s",c[i]);
ArrPrintMatrix(c,2);
return 0;
}
you need to change the type of the p var in the print function, and you should also set the array to zero so if the strings that are printing are less than 10 chars with terminator- garbage values are not displayed.
void ArrPrintMatrix(char p[][10],int n) {
int i,j;
for(i=0;i<n;i++) {
for(j=0;j<10;j++) {
printf("%c ",p[i][j]);
}
}
}
int main() {
int i;
char c[2][10]= {0};
puts("enter two strings");
for(i=0;i<2;i++)
scanf("%s",c[i]);
ArrPrintMatrix( c,2);
return 0;
}

Unable to shuffle cards randomly

I am doing a project that shuffle 10 cards (12) time randomly but it didn't work with my code.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void show(int[],int);
void shuffle(int[],int,int);
int main (void)
{
int karten[]={1,2,3,4,5,6,7,8,9,10};
int n = sizeof(karten)/sizeof(int);
//printf("%d",n);
int s=12;
srand(time(NULL));
printf("Karten vor dem Mischen: \n");
show(karten,n);
shuffle(karten,n,s);
printf("Karten nach dem Mischen:\n");
show(karten,n);
return 0;
}
void show(int karten[],int n)
{
for(int i=0;i<n;i++)
{
printf("%d,",karten[i]);
}
printf("\n");
}
void shuffle(int karten[],int n,int s)
{
int i=0;
int d=0;
int v[]={(int)malloc(sizeof(karten))};
for(int z=0;z<=s;z++)
{
i=rand()%10;
d=rand()%10;
//printf("%d-->%d\n",i,d);
v[i]=karten[i];
v[d]=karten[d];
karten[d]=v[i];
karten[i]=v[d];
}
printf("Es wurden %d Vertauschungen gemacht\n",s);
free(v);
}
The error is
(((process returned 255)))
and the program crashed.
void shuffle(int karten[],int n,int s) is equivalent to
void shuffle(int *karten,int n,int s)
so int v[]={(int)malloc(sizeof(karten))}; allocates just the size of karten
which is a pointer to an int, so 4 bytes(on most systems).
Because of that You are trying to access unallocated memory.
sizeof(karten) don't give you the length of the array, see sizeof array clarification. Just rewrite the code like this (don't need another array):
void shuffle(int karten[],int n,int s)
{
int i=0, vi;
int d=0, vd;
for(int z=0;z<=s;z++)
{
i=rand()%10;
d=rand()%10;
vi=karten[i];
vd=karten[d];
karten[d]=vi;
karten[i]=vd;
}
printf("Es wurden %d Vertauschungen gemacht\n",s);
}

Random Selection -i'th order statistic

The random selection program below doesn't find the i'th order statistic. The following program follows the algorithm provided in Cormen's Introduction to Algorithm. Thanks in advance for finding the bug.
#include<stdio.h>
#include<stdlib.h>
int random(int a,int b) //generates random numbers [a,b]
{
return a+(rand()%(b-a+1));
}
void swap(int *a,int *b) //swwaps the elements
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int partition(int a[],int p,int r) //partitioning similar to that of quicksort
{
int i=p-1,j,x=a[r];
for(j=p;j<r;j++)
{
if(a[i]<x)
{
i++;
swap(&a[i],&a[j]);
}
}
swap(&a[i+1],&a[r]);
return i+1;
}
int random_partition(int a[],int p,int r) //random index generation whose element gets swapped with the last element of the array
{
int q=random(p,r);
swap(&a[q],&a[r]);
return partition(a,p,r);
}
int random_selection(int a[],int p,int r,int index) //finds the i'th order statistic
{
if(p==r)
return a[p];
if(p<r)
{
int mid,k;
mid=random_partition(a,p,r);
k=mid-p+1;
if(k==index)
return a[mid];
if(index<k)
return random_selection(a,p,mid-1,index);
if(index>k)
return random_selection(a,mid+1,r,index);
}
}
main()
{
int a[50],i,size,index;
printf("enter the size of the array\n");
scanf("%d",&size);
printf("enter the array elements\n"); //takes array elements input
for(i=1;i<=size;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<=size;i++) //prints the index of each element
{
printf("%d\n",random_selection(a,1,size,i));
}
}
Do you need a srand() in your main()? Just like these threads
Recommended way to initialize srand?
and How does srand relate to rand function?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i, n;
time_t t;
n = 5;
/* Intializes random number generator */
srand((unsigned) time(&t));
/* Print 5 random numbers from 0 to 50 */
for( i = 0 ; i < n ; i++ )
{
printf("%d\n", rand() % 50);
}
return(0);
}

Selection sort on array in C

I'm trying to create a simple(?) selection sort program in C that selects the largest integer of an integer array and places it in the location a[n-1], places the second largest number in a[n-2], etc until the smallest number is placed in a[0]. I've run through the below code on paper and it seems like it should work, but when I compile it I'm getting faulty results. Am I missing something obvious?
/* The program implements selection sort*/
#include <stdio.h>
#include "simpio.h"
#define n 5
void GetArray(int a[]);
void SelectionSort(int a[]);
int FindMax(int a[], int high);
void swap(int a[], int p1, int p2);
void PrintArray(int a[]);
main()
{
int a[n];
GetArray(a);
SelectionSort(a);
PrintArray(a);
getchar();
}
void GetArray(int a[])
{
int i;
for(i=0;i<n;i++)
{
printf("Enter integer# %d", i+1);
a[i]=GetInteger();
}
}
void SelectionSort(int a[])
{
int i, max;
for(i=0;i<n;i++)
{
max=FindMax(a,i);
swap(a,max,(n-1-i));
}
}
int FindMax(int a[], int high)
{
int i, index;
index=high;
for(i=high;i<n;i++)
{
if(a[i]>a[index])
index=i;
}
return index;
}
void swap(int a[], int p1, int p2)
{
int temp;
temp=a[p2];
a[p2]=a[p1];
a[p1]=temp;
}
void PrintArray(int a[])
{
int i;
for(i=0;i<n;i++)
printf("a[%d]=%d\n", i, a[i]);
}
Change these method to:
void SelectionSort(int a[])
{
int i, max;
for(i=0;i<n;i++)
{
max=FindMax(a,n-i-1);
swap(a,max,n-i-1);
}
}
int FindMax(int a[], int high)
{
int i, index;
index=high;
for(i=0;i<high;i++)
{
if(a[i]>a[index])
index=i;
}
return index;
}
I actually tested my answer and it works.
Selection sort is process of comparing minimum element from the list and placing from the least index.
Now consider below code snippet.
public void selectionSort(int[] elements) {
for(int i=0;i<elements.length;i++) {
int minPosition = i;
for(int j=i+1;j<elements.length;j++) {
if(elements[minPosition]>elements[j])
minPosition = j;
}
int temp = elements[i];
elements[i] = elements[minPosition];
elements[minPosition] = temp;
}
}
Thanks for reading, let me know feedback to improve from myside
Shouldn't:
max=FindMax(a,i);
swap(a,max,(n-1-i));
Be:
max=FindMax(a,i);
swap(a,max,i);
otherwise, next time through the loop, you'll find the same max value in the top position in the array.
A very basic implementation of selection sort
#include<stdio.h>
main()
{
int i,j,n=7,a[]={1,2,5,3,8,9,5},key;
for(j=1;j<n;j++)
{
key=a[j]; //a[j] is the new element to be added to the sorted
//sequence
i=j-1;
while(i>=0 && key<a[i]) //traverse through the sorted sequence
{a[i+1]=a[i];i--;} //until the place of key is found
a[i+1]=key;
}
for (j=0;j<n;j++)
printf("%d",a[j]);
}
#include<stdio.h>
#include<conio.h>
int removex(int arr[],int small,int n)
{
int i=0;
for(;i<n;i++)
if(arr[i]==small) //searching that no to delete
break;
for(;i<n-1;i++)
arr[i]=arr[i+1]; //delete by overloading no
return n-1;
}
void selectSort(int arr[],int sort[],int n)
{
int j=0,k=0,small;
while(n!=0)
{
small=arr[0];
for(j=0;j<n;j++)
if(arr[j]<small)
small=arr[j]; //finding smallest no
sort[k++]=small;
n=removex(arr,small,n); //removing that from list as we included that no into sorted list
}
}
void main()
{
int arr[10],arr2[10],i,n;
clrscr();
printf("Enter how many elements");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
selectSort(arr,arr2,n);
printf("sorted list is\n");
for(i=0;i<n;i++)
printf("%d\n",arr2[i]);
getch();
}

Print 2d array by calling a function print_array with argument the 2d array

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define length 100
void print_array();
int main()
{
int m,n,i,j;
int A[length][length];
printf("Give dimensions of array (up to 100x100):\ni:\n");
scanf("%d",&i);
printf("j:\n");
scanf("%d",&j);
srand(time(NULL));
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
A[m][n]=rand()%45+1;
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
print_array(i,j,A);
return 0;
}
void print_array(int i,int j,int A[][j])
{
printf("\n");
int m,n;
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
}
Hello. I am trying to print a 2d array by calling a function print but when I run the program I get:
For the first printf() the correct values:
A[0,0]=25
A[0,1]=19
A[0,2]=13
A[1,0]=4
A[1,1]=17
A[1,2]=43
A[2,0]=7
A[2,1]=37
A[2,2]=20
But when with the 2nd printf() within the function call of print_array I get:
A[0,0]=25
A[0,1]=19
A[0,2]=13
A[1,0]=0
A[1,1]=0
A[1,2]=0
A[2,0]=0
A[2,1]=0
A[2,2]=0
Seems like I miss something with pointers... Thanks.
This is C99, right?
The problem is that you're confusing the array size.
The main program has int A[length][length], but then you call the function with a dynamic size for the final dimension, A[][j]. If j != length, then the function will index the array incorrectly.
I would recommend representing the array in the function call as a bare pointer to the first element, and doing the indexing manually:
void print_array(const int *A, size_t width, size_t height)
{
for(size_t i = 0; i < height; ++i)
{
for(size_t j = 0; j < width; ++j)
printf("A[%zu][%zu] = %d\n", i, j, A[i * width + j]);
}
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <time.h>
#define length 100
void print_array(int i,int j,int A[length][length]);
int main()
{
int m,n,i,j;
int A[length][length];
printf("Give dimensions of array (up to 100x100):\ni:\n");
scanf("%d",&i);
printf("j:\n");
scanf("%d",&j);
srand(time(NULL));
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
A[m][n]=rand()%45+1;
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
print_array(i,j,A);
return 0;
}
void print_array(int i,int j,int A[length][length])
{
printf("\n");
int m,n;
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
}
Apart from the above, you need to do some input validation for the dimension (i and j). They should not exceed the length. If it exceeds the length then you will run into problems.
void print_array(int i,int j,int A[][j])
should be
void print_array(int i,int j,int A[][length])
When you tell the compiler that the actual array has different dimensions than what you earlier specified, it accesses the wrong elements. A is always 100x100, you just don't fill all of it.
You need to define the size of the array int A[][] in the function signature. Use this function instead :
void print_array(int i,int j,int A[length][length])
{
printf("\n");
int m,n;
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
}
First you should forward declare your function with the correct prototype
void print_array(int n,int m, int A[n][m]);
And then use it with the correct dimensions
print_array(length, length, A);
Other than that:
use size_t for sizes instead of int
usual naming conventions have i and j as indices and n and m
as sizes. Sticking to such conventions makes code easier to read for others.
You've declared A as int A[length][length], But in the print_array function you've declare it as A[][j] which means in your function A have a different number of colones which leads to this error.
change this line
void print_array(int i,int j,int A[][j])
with this one
void print_array(int i,int j,int A[][length])
http://www.cplusplus.com/doc/tutorial/arrays/
array and matrix printing functions are little similar but tricky..
but i have worked on it and found out some thing and i think it will be useful for all
here is a simple C code for Function for printing matrix
#include<stdio.h>
void printmatrix(int l,int x,int y,int *p_arr);
void putvalue(int l,int x,int y,int *r_arr);
/* ******** Function to insert some random value in to a Matrix ************ */
void putvalue(int l,int x,int y,int *r_arr)
{
int i,j;
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
r_arr[(l*i)+j]=i+j+10;
}
}
}
/* *********Function to Print any Matrix ********** */
void printmatrix(int l,int x, int y,int *p_arr)
{
int i,j;
printf("\n");
for(i=0;i<x;i++)
{
printf("\n");
for(j=0;j<y;j++)
{
printf(" %d",p_arr[(l*i)+j]);
}
}
}
/* ****** Main ****** */
void main()
{
int i,j,l;
int Big_arr[80][100],Small_arr[20][40];
// ****** I have taken two different size arrays *****
int x,y;
clrscr();
printf("\n Enter x and y values under 20X40:"); // Because of screen size of Output
scanf("%d %d",&x,&y);
if((x!=0)&&(y!=0))
{
printf("\n %dX%d",x,y);
l=sizeof(Big_arr[0])/sizeof(Big_arr[0][0]); // **** l is the length of a single row of matrix
putvalue(l,x,y,(int*)Big_arr);
printf("\n Printing Big_arr");
printmatrix(l,x,y,(int*)Big_arr);
l=sizeof(Small_arr[0])/sizeof(Small_arr[0][0]);
putvalue(l,x,y,(int*)Small_arr);
printf("\n Printing Small_arr");
printmatrix(l,x,y,(int*)Small_arr);
}
else
printf("\n ***** Enter valied x and y values *****");
getch();
}
hope u like it.

Resources