// Jumbler
// A demo program showing the use of
// pointers and functions

// Marc Chee (cs1511@cse.unsw.edu.au) June 2020

#include <stdio.h>

#define MAX_INPUT_SIZE 100

int read_inputs(int nums[MAX_INPUT_SIZE]);
void print_nums(int nums[MAX_INPUT_SIZE], int print_quantity);
void swap_nums(int *a, int *b);
void jumble(int nums[MAX_INPUT_SIZE], int num_nums);

int main(void) {
    int numbers[MAX_INPUT_SIZE] = {0};
    int input_size = read_inputs(numbers);
    jumble(numbers, input_size);
    print_nums(numbers, input_size);
}

// Reads a number from standard input
// Then reads that many input integers from 
// standard input and inserts them in order 
// into the array nums.
// Returns the actual number of ints scanned into the array
int read_inputs(int nums[MAX_INPUT_SIZE]) {
    int input_count = 0;
    printf("How many numbers? ");
    scanf("%d", &input_count);
    int i = 0;
    while (i < input_count && i < MAX_INPUT_SIZE) { // have processed i inputs
        scanf("%d", &nums[i]);
        i++;
    } // i == the actual number of inputs scanned
    return i;    
}

// prints out the first print_quantity integers from the
// array nums
void print_nums(int nums[MAX_INPUT_SIZE], int print_quantity) {
    int i = 0;
    while (i < MAX_INPUT_SIZE && i < print_quantity) { // have printed i numbers
        printf("%d ", nums[i]);
        i++;
    }
    printf("\n");
}

// Swap the values of the integers
// that the pointers a and b aim at
void swap_nums(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

// use swap_nums repeatedly to change the order
// of the numbers in nums
void jumble(int nums[MAX_INPUT_SIZE], int num_nums) {
    int i = 0;
    while (i < MAX_INPUT_SIZE && i < num_nums) {
        // find another index in the array,
        // does not have a particular reason
        // it's actually a kind of random other index
        int j = (i * 2) % num_nums;
        swap_nums(&nums[i], &nums[j]);
        i++;
    }
}






Resource created Monday 29 June 2020, 03:50:41 PM.

file: jumbler.c


Back to top

COMP1511 20T2 (Programming Fundamentals) is powered by WebCMS3
CRICOS Provider No. 00098G