I want to try to create a C program which lets the user determine the array size of global variables (to make my program more dynamic). But there's a catch because you can't use scanf
outside the scope. Can you guys help me with this?
I've tried using scanf
outside the scope and it's not possible.
This is the code that works (the user can't determine the array size of the global variables):
#include <stdio.h>
int arr[100];
int tempArr[100];
void merge(int left, int middle, int right){
int leftIndex, rightIndex, index;
for(leftIndex = left, rightIndex = middle + 1, index = left;leftIndex<=middle && rightIndex<=right;index++){<br>
if(arr[leftIndex]<arr[rightIndex]){
tempArr[index] = arr[leftIndex++];
}else{
tempArr[index] = arr[rightIndex++];
}
}
while(leftIndex<=middle){
tempArr[index++]=arr[leftIndex++];
}
while(rightIndex<=right){
tempArr[index++]=arr[rightIndex++];
}
for(int j = left; j<=right; j++){
arr[j]=tempArr[j];
}
}
void sort(int left, int right){
int middle =0;
if(left<right){
middle=(left+right)/2;
sort(left, middle);
sort(middle+1, right);
merge(left,middle,right);
}
}
int binarySearch(int arr[], int left, int right, int search){
int middle = 0;
if(left<right){
middle = (left+right)/2;
if(arr[middle]==search){
return middle;
}else if(arr[middle]>search){
return binarySearch(arr,left,middle,search);
}else{
return binarySearch(arr,middle+1,right,search);
}
}
return -1;
}
int main(){
int search;
int index = 0;
int arraySize = 0;
scanf("%d", &arraySize); getchar();
for(int i=0;i<arraySize; i++){
int number;
scanf("%d", &number); getchar();
arr[index] = number;
index++;
}
printf("Before sorting\n");
int size=sizeof(arr)/sizeof(arr[0])-1;
for(int i =0;i<=arraySize;i++){
if(arr[i]!=0){
printf("%d %d\n",arr[i],i);
}
}
sort(0, arraySize-1);
printf("\nAfter sorting\n");
for(int i =0;i<=arraySize;i++){
if(arr[i]!=0){
printf("%d %d\n",arr[i],i);
}
}
printf("\nSearch a number: ");
scanf("%d",&search);
int result = 0;
result = binarySearch(arr,0,arraySize,search);
printf("Result: %d",result);
return 0;
}
And I tried these few lines below and they didn't work. I'm not sure if there is another way I can think of.
#include <stdio.h>
int slot;
scanf("%d",&slot);
int arr[slot];
int tempArr[slot];