Binary Searching in C (with Bubble sort) - c

I have written a code for Binary Search. It has a provision for bubble sorting of array too. The user can either specify the array elements individually or use an RNG for generate the array elements. Even if the array does get sorted properly, I am unable to get the correct index if there is a match and somehow getting a match even if the match doesn't exist. I get no errors or warnings while compiling the code. Please advice on where my code/logic is wrong.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
size_t binary_search(const int b[], int search, size_t low, size_t high);
int value = 0;
int main (void)
{
int selection=0,size=0,key=0; //Value will be used if the match doesn't exist in the array.
int temp=0,pass=0;
printf("\n\tThis program uses Binary Search Technique to find an element in an array.\n\n");
printf("\tThe user can either feed the individual array values or use the inbuilt Random Number Generator to initialise the array elements.\n");
printf("\tPress 1 for RNG fed array values.\n\tPress 2 for user fed array values.\n");
printf("\n\tSelection : ");
scanf("%d",&selection);
printf("\n\tPlease enter the size of the array : ");
scanf("%d",&size);
int a[size];
size_t i=0;
if (selection==1)
{
srand(time(NULL));
printf("\n\tThe random number generator will generate the values between 0 and 100");
for(i=0;i<size;i++)
a[i]=rand()%100;
}
else if (selection==2)
{
printf("\n\tPlease enter the array elements : \n");
for(i=0;i<size;i++)
{
printf("\tElement %d : ",i);
scanf("%d",&a[i]);
}
}
printf("\n\n\tThe array is : \n\n\t");
for(i=0;i<size;i++)
{
printf("%5d",a[i]);
if ((i+1)%20==0)
printf("\n\t");
}
for(pass=1;pass<i-1;pass++) //Bubble sort
{
for (i=0;i<size-1;i++)
{
if(a[i]>a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
printf("\n\n\tThe array after bubble sorting is : \n\n\t");
for(i=0;i<size;i++)
{
printf("%5d",a[i]);
if ((i+1)%20==0)
printf("\n\t");
}
printf("\n\n\tEnter the key value which is to be searched in the array : ");
scanf("%d",&key);
binary_search( a, key, 0, size-1);
if (value!=-1)
{
printf("\n\n\tKey found at a[%d].",value);
}
else
{
printf("\n\n\tNo match found.");
}
}
size_t binary_search(const int b[], int search, size_t low, size_t high)
{
int middle=0;
while (low<=high)
{
middle = (high+low)/2;
if (b[middle]==search)
return middle;
else if (search>b[middle])
{
low = middle+1;
}
else if (search<b[middle])
{
high = middle-1;
}
else
middle=-1;
}
return middle;
}
Edit :
I have made some changes to the code from which I am able to get the index if a match is found. However, I am still unable to get the msg when a match isn't found.
Output for when match doesnt exist 1 :
Please enter the size of the array : 20
The random number generator will generate the values between 0 and 100
The array is :
80 76 14 56 78 60 70 43 55 4 87 25 18 54 36 20 48 73 21 55
The array after bubble sorting is :
4 14 18 20 21 25 36 43 48 54 55 55 56 60 70 73 76 78 80 87
Enter the key value which is to be searched in the array : 90
Key found at a[19].
Process returned 0 (0x0) execution time : 4.759 s
Press any key to continue.
Output when match doesnt exist 2:
Please enter the size of the array : 20
The random number generator will generate the values between 0 and 100
The array is :
12 48 18 15 16 14 46 14 30 75 54 52 14 95 47 40 82 44 30 39
The array after bubble sorting is :
12 14 14 14 15 16 18 30 30 39 40 44 46 47 48 52 54 75 82 95
Enter the key value which is to be searched in the array : 5
For this case, the code doesnt end at all.

The global variable value is not handled correct.
You must make sure to set it inside binary_search both when you have a match (i.e. set it to matching index) and when you have no match (i.e. set it to a value indicating no-match). Your current code doesn't do that.
Apparently you want value to be -1 when you don't have a match so you need:
size_t binary_search(const int b[], int search, int low, int high)
{
int middle=0;
while (low<=high)
{
middle = (high+low)/2;
if (b[middle]==search)
{
value = middle; // Match - save matching index
return middle;
}
else if (search>b[middle])
{
low = middle+1;
}
else if (search<b[middle]) // this if-part is not needed btw
{
high = middle-1;
}
}
value = -1; // No match
return 0;
}
That said, I strongly recommend that you stop using a global variable for this. Instead use the functions return value like:
int binary_search(const int b[], int search, int low, int high)
{
int middle=0;
while (low<=high)
{
middle = (high+low)/2;
if (b[middle]==search)
{
return middle; // Match
}
else if (search>b[middle])
{
low = middle+1;
}
else if (search<b[middle]) // this if-part is not needed btw
{
high = middle-1;
}
}
return -1; // No match
}
(notice that the function returns an int now)
and use it like:
int match = binary_search( a, key, 0, size-1);
if (match >= 0)
{
printf("\n\n\tKey found at a[%d].", match);
}
else
{
printf("\n\n\tNo match found.");
}
Remember to delete the global variable value

I changed line 22 from int a[size]; to
int *a = malloc(sizeof(int) * size);
and each of scanf to scanf_s because I used visual studio to run it
It seems that the sort works fine except when we have zeros in the array
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
size_t binary_search(const int b[], int search, size_t low, size_t high);
int value = 0;
int main(void)
{
int selection = 0, size = 1, key = 0; //Value will be used if the match doesn't exist in the array.
int temp = 0, pass = 0;
printf("\n\tThis program uses Binary Search Technique to find an element in an array.\n\n");
printf("\tThe user can either feed the individual array values or use the inbuilt Random Number Generator to initialise the array elements.\n");
printf("\tPress 1 for RNG fed array values.\n\tPress 2 for user fed array values.\n");
printf("\n\tSelection : ");
scanf_s("%d", &selection, sizeof(int));
printf("\n\tPlease enter the size of the array : ");
scanf_s("%d", &size, sizeof(int));
int *a = malloc(sizeof(int) * size);
size_t i = 0;
if (selection == 1)
{
srand(time(NULL));
printf("\n\tThe random number generator will generate the values between 0 and 100");
for (i = 0; i < size; i++)
a[i] = rand() % 100;
}
else if (selection == 2)
{
printf("\n\tPlease enter the array elements : \n");
for (i = 0; i < size; i++)
{
printf("\tElement %d : ", i);
scanf_s("%d", &a[i], sizeof(int));
}
}
printf("\n\n\tThe array is : \n\n\t");
for (i = 0; i < size; i++)
{
printf("%5d", a[i]);
if ((i + 1) % 20 == 0)
printf("\n\t");
}
for (pass = 1; pass < i - 1; pass++) //Bubble sort
{
for (i = 0; i < size - 1; i++)
{
if (a[i] > a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
}
printf("\n\n\tThe array after bubble sorting is : \n\n\t");
for (i = 0; i < size; i++)
{
printf("%5d", a[i]);
if ((i + 1) % 20 == 0)
printf("\n\t");
}
printf("\n\n\tEnter the key value which is to be searched in the array : ");
scanf_s("%d", &key, sizeof(int));
binary_search(a, key, 0, size - 1);
if (value != -1)
{
printf("\n\n\tKey found at a[%d].", value);
}
else
{
printf("\n\n\tNo match found.");
}
}
size_t binary_search(const int b[], int search, size_t low, size_t high)
{
int middle = 0;
while (low <= high)
{
middle = (high + low) / 2;
if (b[middle] == search)
return middle;
else if (search > b[middle])
{
low = middle + 1;
}
else if (search < b[middle])
{
high = middle - 1;
}
}
value = middle;
return 0;
}

Related

Printing out each time 2 more elements of an array

How can I print out each line two more elements of an array...?
I can't get it done.
I have this short code, but this part is missing...
#include <stdio.h>
#include <stdlib.h>
char *toChar(int numbers[]);
int main(){
// FILE *fp;
int num;
printf("Number of rows: ");
scanf("%d", &num);
int val[num], value=num;
for(int i=0; i<num; i++){
val[i]=value;
value+=value;
printf("%d ", val[i]);
...
printf("\n");
}
}
return 0;
}
I would like to achieve this... for input = 4.
4 8
12 16 20 24
28 32 36 40 44 48
52 56 60 64 68 72 76 80
And for input 3, expected output is:
3 6
9 12 15 18
21 24 27 30 33 36
Note that the printed value should increase by the same amount as there should be rows (num).
I would make a list of all you need:
You need num rows
You need the number of columns to increase by 2 every row
You need the printed value to increase by num for each output
With that list, make two loops.
One that iterates over the rows
One that iterates over the columns:
#include <stdio.h>
int main() {
printf("Number of rows: ");
int num;
if (scanf("%d", &num) != 1) return 1;
// row starts at 0 and ends at num-1
// columns start with 2 and increases by 2 for every row
for (int row = 0, columns = 2, value = num; row < num; ++row, columns += 2) {
// and value increases by `num` every time it's been printed:
for (int c = 0; c < columns; ++c, value += num) {
printf("%d ", value);
}
putchar('\n');
}
}
Demo
Decided to take a stab at this using java. I feel like recursion here was a bit easier than trying to wrap my head around two for loops.
class Main {
public static void main(String[] args) {
printTwoMore(0, 1, 1, 4);
}
public static void printTwoMore(int prevTimesToPrint, int multiple, int currentRow, int maxRow) {
if (currentRow > maxRow) {
return;
}
int timesToPrint = 2 + prevTimesToPrint;
for (int i = 0; i < timesToPrint; i++) {
System.out.print(4 * multiple + " ");
multiple++;
}
System.out.println("");
currentRow++;
printTwoMore(timesToPrint, multiple, currentRow, maxRow);
}
}

Find minimum number of wires to connect the bulbs code

I have written this C code to find a minimum number of wires required to switch on all the bulbs.
The problem is that there is x number of computers, some of which are On and some are Off and the distance between these bulb from the first bulb is given. The computer can be switched ON by connecting it to its nearby ON the bulb.
So the inputs are as follows:
X = 6 (number of bulbs)
1 0 1 1 0 1(1 means the bulb is ON and 0 means the bulb is OFF)
2 4 8 36 37 40 (distance between one bulb from the first bulb)
and the output will be:
3 (Reason: 4 - 2 = 2, 37 - 36 = 1, 2 + 1 = 3)
#include <stdio.h>
int main(){
int n,pre,post,sum = 0;
scanf("%d",&n);
int arr[n],dist[n];
for(int i =0;i<n;i++){
scanf("%d ",&arr[i]);
}
for(int i =0;i<n;i++){
scanf("%d ",&dist[i]);
}
for(int i =0;i<6;i++){
if(arr[i] == 0){
pre = dist[i]-dist[i-1];
post = dist[i+1]-dist[i];
if(pre>post){
sum +=post;
}
else{
sum+=pre;
}
}
}
printf("\n %d",sum);
}
It keeps on taking the inputs. Please tell me what is the error in this code?
Thanks in advance.
Edited: I missed that scanf("%d",n) by mistake. It was there in my original code and the problem still persists.
As Sandrin mentioned, n is not defined.
Assuming your input file is:
6
1 0 1 1 0 1
2 4 8 36 37 40
You need to add code to set n:
scanf("%d ",&n);
And, you need to insert this before the definitions of your matrix
Here's the refactored code:
#include <stdio.h>
int
main(void)
{
int n, pre, post, sum = 0;
#if 1
scanf("%d ",&n);
#endif
int arr[n], dist[n];
for (int i = 0; i < n; i++)
scanf("%d ", &arr[i]);
for (int i = 0; i < n; i++)
scanf("%d ", &dist[i]);
for (int i = 0; i < 6; i++) {
if (arr[i] == 0) {
pre = dist[i] - dist[i - 1];
post = dist[i + 1] - dist[i];
if (pre > post) {
sum += post;
}
else {
sum += pre;
}
}
}
printf("\n %d", sum);
return 0;
}
Putting a side technical errors (e.g. n not initialized), the algorithms assumes that all problems can be solved by single pass. This is not true for cases like:
1 0 0 0 0 1
0 1 3 4 6 7
Where the code will choose to connect bulbs [0,1], [2,3], and [4,5], based on pre/post distances. However, bulbs 2 and 3 will remain disconnected.
A better algorithm will attempt to find, for each sequence of off bulbs, which is the most expensive connection, and avoid it.
I have come up with this solution for my code and I have tried to consider all the test cases. If you find any test case that won't run feel free to tell.
#include <stdio.h>
#include <stdlib.h>
int main(int ac, char **av){
int n,pre,post,sum = 0;
scanf("%d",&n);
int *input,*distance;
input = malloc(n * sizeof(int));
for (int i=0; i < n; i++)
{
scanf("%d", &input[i]);
}
distance = malloc(n * sizeof(int));
for (int i=0; i < n; i++)
{
scanf("%d", &distance[i]);
}
for(int i =0;i<6;i++){
if(input[i] == 0){
pre = distance[i]-distance[i-1];
if(input[i+1]==1){
post = distance[i+1]-distance[i];
input[i] =1;
if(pre>post){
sum +=post;
}
else{
sum+=pre;
}
}
else{
sum = sum+pre;
}
printf("%d.....%d....%d\n",pre,post,sum); //Debugging
}
}
printf("\n %d",sum);
free(input);
free(distance);
}

Why I am getting this output?

#include <stdio.h>
#define MAX_SIZE 1000 // Maximum array size
int main() {
int arr[MAX_SIZE], size, i;
int max1, max2;
scanf("%d", &size);
max1 = max2 = -99999;
/* Input array elements */
for (i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
/*
* Check for first largest and second
*/
for (i = 0; i < size; i++) {
if (arr[i] > max1) {
max2 = max1;
max1 = arr[i];
} else
if (arr[i] > max2 && arr[i] < max1) {
max2 = arr[i];
}
}
printf("%d", max2);
return 0;
}
when I used test case 20 10 40 4 100 output is correct 40,
but when I use 1 2 3 4 5 then output is max2 = -99999.
Can anyone please explain to me why I am not getting this? I traced but did not get why?
In your program, the first input is the size of the array. So, your inputs should actually be 5 20 10 40 4 100 and 5 1 2 3 4 5 (note the extra 5 in front) so they have the correct size. Your first input is correct because it read in 20 as the size and tried to read in 20 numbers, and there weren't enough numbers so it just read in 0 for the rest, and 40 was still the second-largest. For your second input, it read in 1 as the size, so there was no second-largest number, so it printed out -99999.
The output is somewhat consistent with the input, assuming the input comes from a text file:
the first number read is the number of entries to handle.
for the first case, size is read as 20 and the program tries to read 20 numbers into arr[0] through arr[19]. As you do not test the return value of scanf(), you do not detect the invalid or missing input past the last one in the file 100. scanf() fails and leaves arr[i] unchanged from index 4 on. arr is unintiialized, so the contents is undefined and so is the behavior of the program. It so happens that there are no numbers in arr[4] through arr[19] that are larger than 40. So the second largest number is printed as 40.
for the second case, size is read as 1 and only a single number is read into arr[0], the remaining input being ignored. The loop sets max1 = 2 and max2 = max1, whose initial value is -99999. Hence the output.
You should provide 5 20 10 40 4 100 and 5 1 2 3 4 5 as input to get the expected behavior consistently.
You should also be more defensive with user input and report unexpected cases:
#include <limits.h>
#include <stdio.h>
#define MAX_SIZE 1000 // Maximum array size
int main() {
int arr[MAX_SIZE], size, i;
int max1, max2, has_max;
if (scanf("%d", &size) != 1) {
printf("missing count of numbers\n");
return 1;
}
if (size < 0 || size > MAX_SIZE) {
printf("invalid count of numbers: %i\n", size);
return 1;
}
/* Input array elements */
for (i = 0; i < size; i++) {
if (scanf("%d", &arr[i]) != 1) {
printf("invalid input: got %i numbers instead of %i\n", i, size);
size = i;
break;
}
}
/*
* Check for first largest and second
*/
max1 = max2 = INT_MIN;
has_max = 0;
for (i = 0; i < size; i++) {
if (arr[i] > max1) {
max2 = max1;
max1 = arr[i];
has_max++;
} else
if (arr[i] > max2 && arr[i] < max1) {
max2 = arr[i];
has_max++;
}
}
if (has_max < 2) {
printf("no second highest value\n");
} else {
printf("%d\n", max2);
}
return 0;
}
Note the method to track if there are at least 2 different values in the array. Try and see if this improvement is sufficient for all cases...

How to find number of pairs which have maximum difference in their values among all other pairs?

I calculated difference between each pair and then stored the maximum difference pertaining to that element in the same array at that location only , for instance array is 1 2 3 , so a[0]=2 , a[1]=1 , since difference of 1 is maximum with 3 and difference of 2 is maximum with 3 , Now whatever manipulations I do I perform with the array size reduced by 1 , so Now I calculate the maximum difference value and place it in 0th index and after that I run a loop till the size of reduced array and count the no of times this maximum value appears , but this approach takes too long , can someone suggest some simple logic .Input is of the form
No of test cases is for e.g 2
no of elements in first array
maximum no of pairs in 1st array
no of elements in 2nd array
maximum no of elements in 2nd array
#include <stdio.h>
#include<math.h>
int max=0;
int main()
{
int test_no, n1,n2,i,j,a,b,count1=1,count2=1;
scanf("%d",&test_no);
printf("\n");
scanf("%d",&n1);
printf("\n");
int arr1[n1];
for(i=0;i<n1;i++)
{
scanf("%d ",&arr1[i]);
}
for(i=0;i<n1-1;i++)
{
for(j=i+1;j<=n1-1;j++)
{
a=abs(arr1[i]-arr1[j]);
if(max<=a)
max=a;
}
arr1[i]=max;
max=0;
}
int temp;
max=arr1[0];
for(i=1;i<n1-1;i++)
{
if(max<arr1[i])
{
temp=max;
max=arr1[i];
arr1[i]=temp;
arr1[0]=max;
}
}
for(i=1;i<n1-1;i++)
{
if(arr1[i]==arr1[0])
{
count1++;
}
}
printf("\n");
scanf("%d",&n2);
int arr2[n2];
max=0;
for(i=0;i<n2;i++)
{
scanf("%d ",&arr2[i]);
}
for(i=0;i<n2-1;i++)
{
for(j=i+1;j<=n2-1;j++)
{
a=abs(arr2[i]-arr2[j]);
if(max<=a)
max=a;
}
arr2[i]=max;
max=0;
}
temp=0;
max=arr2[0];
for(i=1;i<n2-1;i++)
{
if(max<arr2[i])
{
temp=max;
max=arr2[i];
arr2[i]=temp;
arr2[0]=max;
}
}
for(i=1;i<n2-1;i++)
{
if(arr2[i]==arr2[0])
{
count2++;
}
}
printf("%d \n",count1);
printf("%d",count2);
return 0;
}
Sort the array (this takes n log n time).
The maximum difference is now obviously the value of the last element minus that of the first.
To get that same difference, you need the same first element and the same end element*, so that you only need to count how many elements are equal to the first (say 4), how many elements are equal to the last (say 3), and take the lesser of the two values (here 3).
size_t i;
for (i = 1; i < arrayLength/2; i++) {
if ((sortedArray[i] != sortedArray[0])
||
(sortedArray[n-1-i] != sortedArray[n-1])) {
break;
}
}
// i is now the number you need.
To sort an array in C you also have a ready-made library function.
Or you can do this in O(N) time, by simply scanning the array:
int minVal = INT_MIN;
int maxVal = INT_MAX;
int cntMin = 0;
int cntMax = 0;
for (i = 0; i < n; i++) {
if (arr[i] < minVal) {
minVal = arr[i];
}
if (arr[i] > maxVal) {
maxVal = arr[i];
}
if (arr[i] == minVal) { cntMin++; }
if (arr[i] == maxVal) { cntMax++; }
}
if (minVal == maxVal) {
return n/2;
}
return min(cntMin, cntMax);
Example:
0 0 0 0 1 2 3 4 5 6 6 6
Maximum difference is 6 and is to be found 3 times.
0 1 2 3 4 5 6 6 6
Maximum difference is still 6, and is to be found once only.
If you want to count all possible pairs (e.g. in [ 01, 02, 61, 62, 63 ] you want to have (01,61) ... (02, 63) ), even if your note about removing elements seems to indicate otherwise, then instead of returning the minimum of cntMin and cntMax, just return their product. If they are equal, return N*(N-1) ).
--
(*) to get the same difference with two different numbers, one of them has to be either less than the minimum, or more than the maximum, of the initial range, which is contradictory. E.g. to get 6 other than from 6 and 0, you would need 7 and 1, or 5 and -1. But 7 is more than 6, and -1 is less than 0. So your array's maximum difference once it includes either 7 or -1 is no longer 6.
All you need to do is count how many times the smallest and the largest number are present in the array. When you have done that the number of pairs is found by a simple multiplications.
This can be done like:
#include <stdio.h>
#include <limits.h>
#define N 7
int main(void) {
int arr[N] = {1, 2, 1, 4, 1, 5, 5};
int max = INT_MIN;
int min = INT_MAX;
int i;
int countmax = 0;
int countmin = 0;
for (i=0; i < N; ++i)
{
if (arr[i] > max)
{
// Found new max value --> reset counter to 1
countmax = 1;
max = arr[i];
}
else if (arr[i] == max)
{
// Found same max value --> increment counter
countmax++;
}
if (arr[i] < min)
{
countmin = 1;
min = arr[i];
}
else if (arr[i] == min)
{
countmin++;
}
}
if (max == min)
{
// Special case: All elements are the same
printf("%d pairs with difference 0 found\n", N*(N-1)/2);
else
{
printf("%d pairs with difference %d found\n", countmin * countmax, abs(max-min));
}
return 0;
}
Output:
6 pairs with difference 4 found

Function that can count how many numbers in array A fall in the range from low to high.

I'm completing a problem set for an introductory computer science class and I'm a bit confused as to what I'm supposed to be doing with this program. The question is: In one file there is a list of of scores for some participants in an athletic competition. The list is organized in the order in which the participants registered for the competition, not in order of score. A separate file contains a set of ranges. Your job is to write a program that can read the data in these two files and print a table showing how many of the participants fell into each of the given ranges.
The question is copied word for word, but I have a few questions about this question. if you could leave a comment stating your opinion about the following, that would be nice:
1) Okay, so I've written some code in order to read the numbers from the first data file, place the numbers in the array A and return a count of the number of numbers read or N, whichever is smaller. Which follows as:
#include <stdio.h>
int readNumbers(FILE* input, int A[], int N)
{
int n;
n = 0;
while (n < N&&!feof(input))
{
fscanf_s(input, "%f", &A[n]);
n++;
}
return n;
}
int count(const int A[], int N, int low, int high){
}
2) My confusion lies in using this second function to count how many numbers in array A fall in the range from low to high, inclusive. The parameter N tells you how many numbers are in the array. And use these two functions to construct and print a table of how many participants are in each of the categories given in the second file.
Now that I try to talk myself through it, I am now even more confused. Maybe I'm just making the question more difficult. Any tips will help. Thanks
to count how many numbers in array A fall in the range from low to high, inclusive.
That count() could be implemented like this
int count(const int A[], int N, int low, int high){
int i, cnt;
for (i = cnt = 0; i < N; i++) {
if (low <= A[i] && A[i] <= high)
cnt++;
}
return cnt;
}
use these two functions to construct and print a table of how many participants are in each of the categories given in the second file.
You could achieve this by using a simple loop
for (i = 0; i < number_of_categories; i++) {
printf("%d - %d : %d\n", low[i], high[i],
count(A, N, low[i], high[i]));
}
Suppose you already put all those categories information to low[] and high[].
Not sure what the input files are supposed to look like, I guessed one number per line.
Scores file:
0
1
2
3
4
5
6
7
8
9
10
19
29
39
49
59
69
79
89
99
99
99
99
99
99
99
100
Ranges File:
0
10
11
20
21
30
31
40
41
50
51
60
61
70
71
80
81
90
91
100
Source:
#include <stdio.h>
#include <stdlib.h>
int readNumbers(FILE* input, int A[], int N)
{
int n = 0;
while (n < N && !feof(input))
{
fscanf_s(input, "%d", &A[n]);
n++;
}
return n;
}
int count(const int A[], int N, int low, int high) {
int i = 0, numbers_in_range = 0;
for (i = 0; i < N; i++) numbers_in_range += (A[i] >= low && A[i] <= high) ? 1 : 0;
return numbers_in_range;
}
inline int exiting(char* reason)
{
if(reason != 0) printf("%s\n", reason);
printf("Usage: rangechecker \"scoresfilename\" \"rangesfilename\"\n");
printf("exiting...\n");
exit (-1);
}
int main(int argc, char** argv) {
int* scores = 0;
int* ranges = 0;
int num_scores = 0, num_ranges = 0;
FILE* scoresfptr;
FILE* rangesfptr;
switch (argc) {
case 1:
case 2:
exiting(0);
break;
case 3:
//verify files exist and open them
if((scoresfptr = fopen(argv[1], "r")) == NULL || (rangesfptr = fopen(argv[2], "r")) == NULL)
{
exiting("One of the files does not exist or cannot be opened.");
}
break;
default:
exiting(0);
break;
}
//kind of dumb, but because N is a passed value you kinda gotta
//know N ahead of the call to readnumber or count
//that, or I am just tired.
int ch = 0;
//assuming instructions are correct, a list, 1 number per line
//will fail if extra newlines in file
do {
ch = fgetc(scoresfptr);
if (ch == '\n')
num_scores++;
} while(ch != EOF);
//now we have N, can call readnumbers. Put file pointer back at start of file.
rewind(scoresfptr);
//Can also now allocate memory for A[].
scores = (int*)calloc(num_scores, sizeof(int));
//check return value to see if anything was read in
if(readNumbers(scoresfptr, scores, num_scores) > 0) {
//musta been something in the file
//get the ranges
ch = 0;
//assuming instructions are correct, a list, 1 number per line
do {
ch = fgetc(rangesfptr);
if (ch == '\n')
num_ranges++;
} while(ch != EOF);
//now we have N, can call readnumbers. Put file pointer back at start of file.
rewind(rangesfptr);
//Can also now allocate memory for A[].
ranges = (int*)calloc(num_ranges, sizeof(int));
//check return value to see if anything was read in
if(readNumbers(rangesfptr, ranges, num_ranges) > 0) {
//now we can call count
//print header column
printf("ranges\tscores in range\n");
for (int i = 0, j = 0; i < num_ranges/2; i++, j += 2)
{
printf("%d-%d:\t%d\n", *(ranges + j),
*(ranges + j + 1),
count(scores, num_scores, *(ranges + j),
*(ranges + j + 1)));
}
}
else {
exiting("Ranges File empty.");
}
}
else {
exiting("Scores File empty.");
}
free(scores);
free(ranges);
fclose(scoresfptr);
fclose(rangesfptr);
return(0);
}
Output:
ranges scores in range
0-10: 11
11-20: 1
21-30: 1
31-40: 1
41-50: 1
51-60: 1
61-70: 1
71-80: 1
81-90: 1
91-100: 8

Resources