This week's lab deals with sorting. In the first part, you will use the standard library function qsort to sort an array of integers. In the second part, we will sort strings instead of integers.
Learn how to use the qsort function
Learn how to write a comparison auxiliary function for qsort.
Lecture 19 and 20 on sorting
Manual page for standard library string functions
qsort manual page
The following exercises are about pointers in C and should help prepare you for future lab activities MP2 and the Final Exam.
In this prelab, you'll demonstrate your knowledge regarding,
Scope of identifiers
Global variables
Pointers, & and * operators
Write the output when the following program executes.
#include <stdio.h>
int i = -12; /* global variable */
int function2(int x)
{
int i = -10; /* another variable named i */
printf(" %i \n", i);
return x * i;
}
void main(void)
{
printf(" %i \n", function2(i));
printf(" %i\n", i);
}
Write the output of the following code. You may have to compile and run this program.
#include <stdio.h>
void main(void)
{
int x;
int * ptr; /* ptr is a "pointer" variable. Assign only computer memory addresses to ptr !!! */
x = 20;
printf("x is %i\n", x);
ptr = &x; /* ptr now points to x , &x means... address of x */
*ptr = 50; /* * operator (dereferencing operator), *ptr means ... the thing ptr points to (which is x in this example)*/
printf("x is %i\n", x);
-x;
printf("*ptr = %i \n", *ptr); /* so using *ptr is like using x */
--(*ptr); /* has same effect as --x */
printf("x = %i\n",x);
}
Write the output when the following program executes. See lecture 19&20 slide #21.
#include <stdio.h>
void main(void)
{
char str[] = "crown";
char * ptrA = "royal"; /* note that ptrA is a pointer, it won't hold data of type char, it holds addresses */
char * ptrB = str; /* the name of an array holds the address of the first byte of an array */
/* so an array name is a pointer (its value can't be changed however) */
printf(" %s ", str);
printf(" %s ", ptrA);
printf(" %s \n", ptrB);
printf("%c %c \n", ptrA[2], *ptrB); /* if the name of an array is a pointer conversely a pointer can be used */
/* an array name */
}
Write the output of the following program.
#include <stdio.h>
void swap1(int a,int b)
{
int temp = b;
b = a;
a = temp;
}
void swap2(int *a,int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void swap3(int * x)
{
int temp = x[0];
x[0] = x[1];
x[1] = temp;
}
void main(void)
{
int a = 5, b = 10;
int c[2];
printf("%i %i\n",a,b);
swap1(a,b);
printf("%i %i\n",a,b);
swap2(&a,&b);
printf("%i %i\n",a,b);
c[0] = a - b; c[1] = b + a;
/* 'c' is the name of an array therefore c is a constant pointer */
/* see lecture 19&20 slide #18 */
swap3(c);
printf("%i %i\n",c[0],c[1]);
}
Write the output of the following code. It might help to draw a picture of memory. Remember, if p2 is a pointer then p2[0] means *(p2 + 0).
#include <stdio.h>
void main(void)
{
int x[2]={2,1};
int *p1, *p2;
int a = 30, b = 10;
printf("%i %i \n",x[0],x[1]);
p1 = x;
printf("%i %i \n",p1[0],p1[1]);
p2 = &p1[1];
printf("%i \n",p2[0]);
*p1 = a * b;
*p2 = b / a;
printf("%i %i \n",p1[0],p1[1]);
printf("%i \n",p2[0]);
}
In this part, we're going to generate an array of 10 integers at
random. First we display the list of 10 integers. Then we will ask
the user if they want to have the integers sorted in ascending or
descending order. We will use the function named qsort
found in the standard library (#include <stdlib.h>) to sort
integers.
To see a demo of the program you will download the file
named sort(see instructions below).
To run this program:
Type the following commands at the Unix prompt:
cd
mkdir lab11
cd
lab11
cp ~cs101ta/public_html/labs/lab11/sort . (Remember to include the period in the end)
Make the program executable. Type:
chmod
u+x sort
./sort
Our program will have four functions: main , menu , compAsc ,
compDesc .
In main we will need to call
the qsort function. qsort
takes four parameters, in this particular order :
qsort(name of the array to be sorted, number of elements in the array, size in number of bytes of each element of the array, comparison function name)
The name of the array to be sorted. In our program in lab11, nums is the name of the array.
The number of elements in the array. In our case, the number of elements in the array is 10 but we will use the constant ARRAY_SIZE which is defined as having the value 10.
The size, in bytes, of each element in the array. Since each element of the array is an integer we will use sizeof(int) (which equals 4 on our lab machines since an integer takes 4 bytes of memory). If our array was of datatype double then we would have used sizeof(double) which is 8 on our lab machine since a variable of datatype double takes 8 bytes of memory.
A function name. You will have to write the auxiliary functions named compAsc and compDesc. The compAsc or compDesc function each has two parameters, both are pointers to an array element. The function compAsc should return a positive integer (say 1) if the thing that the first parameter points to(the element of the array) is greater than the the thing the second pointer points to (another element of the array). The function compAsc should return a negative integer if the thing the first pointer points to is smaller than the thing the second pointer points to. And compAsc should return 0 if they're equal.
You will need to code four functions: main, menu, compAsc and
compDesc.
menu function
The menu function has
no input arguments and it returns an integer. So its code looks
like:
int menu(void)
{
}
Here is the algorithm
for the menu function in pseudo-code:
print the following menu (copy and paste into a printf)
Enter
your choice of sorting:
1) sort in ascending order (1 2 3 4)
2)
sort in descending order (4 3 2 1)
Enter your choice:
read the value the user types (either 1 or 2) into an integer variable named choice declared in the menu function
return choice
compAsc function
We will give you the code for
the compAsc function:
int compAsc( int * ptr1 , int *
ptr2)
{
return *ptr1 - *ptr2 ;
}
compDesc
function
The code for the compDesc function is almost
identical to the code for the compAsc function except that it returns
an integer value of the opposite sign. Copy and paste the code for
the compAsc function and change its name to compDesc and make the
necessary changes.
main function
Here
is the algorithm for main in pseudo-code:
Generate an array of random integers
Call the menu function, assigning the value it returns to an integer variable named response
Print the array (unsorted)
Use a switch statement on the variable named response declared in main. In case 1: call the qsort function using compAsc. In case 2: call the qsort function using compDesc
Print the sorted array
Use
gedit to create lab11.c
gedit
lab11.c
You need to include some header files and define some constants. The beginning of your program should look like this:
#include <stdio.h> #include <stdlib.h> #include <time.h> #define ARRAY_SIZE 10 #define MAX_NUM 20
Write code for the menu function (see pseudo-code above).
Write code for the compAsc and compDesc functions (see pseudo-code above).
Now we shall give some details on how to write our main function. Within the main function, create an integer array, and call it nums. It should have ARRAY_SIZE elements.
Next write a for loop to initialize every element of nums to a random number from 1 to MAX_NUM. Use i as your loop counter (don't forget to declare it!). Your loop should look like this:
srand(time(NULL));
/* Replace this comment with the beginning of your loop... */
nums[i] = (rand() % MAX_NUM) + 1;
/* Replace this comment with the end of your loop... */
Next, write another loop to print all the numbers. The numbers should be separated by a space. After the loop, print a "\n\n" to make a blank line.
Now it's time to check your program up to this point. Save, compile, and run your program. When you run your program, you should see a list of 10 positive integers that looks something like this: (the values won't be the same since we are generating the values randomly)
11 15 8 4 17 16 13 10 9 10
If everything looks good (ask your lab TA
if you can't fix any compile or run-time errors), we next add the
switch statement to main (see pseudo-code above)
Finally, you should write a loop to have your program print out the sorted values. You can copy and paste the loop you have written previously.
At the Unix prompt type:
gcc
lab11.c -o lab11
./lab11
Note: If you see any warnings about the fourth argument of qsort, you may safely ignore them.
For example, you may get something like
the following as output from your program:
11 15 8 4 17 16 13 10 9 10
Enter your choice of sorting:
1) sort in
ascending order (1 2 3 4)
2) sort in descending order (4 3 2
1)
Enter your choice: 1
4 8 9 10 10 11 13 15 16 17
Answer question #1, and #2 on the answer sheet.
Next, we're going to try sorting some strings instead of integers. To save you some effort, we provide you with an almost completed program to begin with.
Copy the files named sortwords.c and hoax.txt from the directory ~cs101ta/public_html/labs/lab11 into your lab11 directory.
Open the file
sortwords.c with gedit and fill in the blanks.
gedit
sortwords.c
Compile the program with the command:
gcc
sortwords.c -o sortwords
At the Unix prompt type:
./sortwords
< hoax.txt
Answer question #3, and #4 on the answer sheet.
That's all folks!