COMP1721 - Higher Computing 1B

Higher Computing 1B - Week 2 Laboratory Exercises

Exercise 2


/*
 * Variation of the "Hello, World" program
 * Asks for your name and then greets you.
  */

#include 

int main(void) {
	char name[16];  /* string to hold name */

	printf("What's your name? ");
	scanf("%15s", name);
	printf("Hi there, %s!\n", name);
	return 0;
}

Exercise 3


/*
 * Read two numbers, add them and print the sum
 */

#include <stdio.h>

int main(void) {
	int n, m; /* lower and upper bounds */
	int sum;  /* accumulated sum */
	int i;    /* loop iteration variable */

	/*
	 * Get the numbers
	 */
	printf("Enter first number: ");
	scanf("%d", &n);
	printf("Enter second number: ");
	scanf("%d", &m);

	/*
	 * Compute sum of [n..m]
	 * (also, display inputs for user to check)
	 */
	sum = 0;
	i = n;
	while (i <= m) {
		sum = sum + i;
		i = i + 1;
	}
	
	/*
 	 * Print results
	 */
	printf("Sum[%d..%d] = %d\n", n, m, sum);

	return 0;
}


Andrew Taylor (andrewt@cse.unsw.edu.au)
Higher Computing 1B, Computer Science & Engineering, UNSW