Exercise 2
Info

This is an in-class exercise. An exercise page like this one will contain a brief description but is intended to be supplemented by discussion during our meeting time. Complete the exercise to the best of your ability in the time given. Feel free to talk with other students as you work, and do not be afraid to ask questions if you get stuck. Aim to complete as much as possible during our meeting, but you need not hand it in. You are encouraged to work at home to complete what you do not get through today.

Learning Objectives

Objectives

This exercise should help you gain familiarity with

  • The basic structure of a C program
  • C integer variables
  • Basic text input and output in C
  • Arithmetic on integer values in C

Part 1

Start by going to the following website in a web browser: https://www.onlinegdb.com/online_c_compiler

This website is a simple online IDE for C programs. You will see a “hello, world” program in the text editor, in a source file called main.c.

Click the green “▶ Run” button just above the text editor. The program will be compiled, and then you will see the output Hello World in the console window below the text editor!

We’re using this online programming environment for this exercise in order to make sure that everyone can start working on C programs right away, even if they don’t yet have an account on the CS ugrad machines. All subsequent exercises (and assignments) will be done on the ugrad machines.

Part 2

To get started, change the program so that it looks like this:

#include <stdio.h>

int main(void) {
    int value;
    printf("enter an integer: ");
    scanf("%d", &value);
    printf("you entered: %d\n", value);
    return 0;
}

Click the green “▶ Run” button. The program should compile, and then the program will start running. You can use the console window (below the text editor) to interact with the program. Enter the value “42”, and press “Enter”. You should see the output you entered: 42 in the console window.

You have written a C program which reads user input, and executed it interactively. Congratulations!

Part 3

Your main task for this exercise is to write a program which

Here is an example run of the program, with bold text used to indicate the input entered by the user:

Enter two integers: 11 3
11 + 3 = 14
11 - 3 = 8
11 * 3 = 33
11 / 3 = 3
11 % 3 = 2

Note that when asked to read two values, the scanf function doesn’t care whether you enter both values on the same line, or on different lines. In the example session above, both values were entered on the same line.

One slightly tricky issue in producing the correct output is printing a literal % character using printf. In a printf format string, the % character usually is the start of a format specifier. However, you can have printf generate a literal % character by specifying two % characters in the format string. I.e., the code

printf("%%");

will print a single % character to the standard output.