While trying to learn more about arrays in C, I tried to write some code that did the following:
Read a stream of numbers from the
stdin
and store them in an arrayPrint the array in the order the numbers have been stored (i.e. print the original array)
Print the array in reversed order
Sort and print the array
Given an array, search whether an entered value is present in an array. If it is present, print the index otherwise print that the value doesn't exist.
It will be great if somebody could review it and let me know how to improve it.
#include <stdio.h>
#include <stdlib.h>
static void printArray(int array[],int startIndex,int endIndex){
if(startIndex < endIndex){
while(startIndex <= endIndex){
printf(" %i ",array[startIndex++]);
}
}else{
while(startIndex >= endIndex){
printf(" %i ",array[startIndex--]);
}
}
printf("\n");
}
static int cmpfunc(const void * a,const void * b)
{
if(*(int*)a > *(int*)b) return 1; else return -1;
}
static void sortedArray(int* originalArray){
qsort((void*)originalArray,(sizeof(originalArray)/sizeof(originalArray[0])),sizeof(originalArray[0]),cmpfunc);
return;
}
static int getIndex(int value,int array[],int size){
int i;
for(i = 0;i < size;i++){
if(array[i] == value){
return i;
}
}
return -1;
}
static void identifyTheIndices(int *arbitraryArray,int size){
char buf[10];
printf("Enter the value to search for..enter q to exit\n");
while(fgets(buf,sizeof buf,stdin) != NULL){
if(buf[0] == 'q'){
break;
}
char *end;
int value = (int) strtol(buf,&end,0);
if(end != buf){
int currentIndex = getIndex(value,arbitraryArray,size);
if(currentIndex > -1){
printf("Found the entered value %i at index %i\n",value,currentIndex);
}else{
printf("Entered value %i doesn't exist\n",value);
}
}
printf("Enter the value to search for..enter q to exit\n");
}
}
int main(int argc,char **argv)
{
int counter = 0;
if(argc > 1){
int originalArray[argc-1];
while(counter < (argc - 1)){
int currentValue = atoi(argv[counter+1]);
printf("Reading input value %i into array \n",currentValue);
originalArray[counter] = currentValue;
counter++;
}
int size = sizeof(originalArray)/sizeof(originalArray[0]);
printf("Printing out the original array\n");
printArray(originalArray,0,size - 1);
printf("Printing out the array in reverse\n");
printArray(originalArray,size - 1,0);
printf("Sorting the array in ascending order\n");
qsort((void*)originalArray,size,sizeof(originalArray[0]),cmpfunc);
printf("Printing out the sorted array\n");
printArray(originalArray,0,size-1);
int arr[] = { 47, 71, 5, 58, 95, 22, 61, 0, 47 };
identifyTheIndices(arr,sizeof(arr)/sizeof(arr[0]));
}
return 0;
}