Simple C Programs
Basic Example
Difficulty: EasyUsing the editor of your choice, write the following program (save it as base.c):
#include <stdio.h>
int main ()
{
printf ("Hello World !\n");
return 0;
}
In a terminal, type the following command:
gcc base.c
You should get no output (which means everything went fine); the compilation has generated
a program named a.out (the default name). You can now run the compiled program with the
command, which outputs:
Hello World !
From this first example, a few things are worth remembering. The usual workflow is:
- write the
Ccode in an editor - compile it (
gcc); if there are errors, go back to step 1 - run it (
./a.out)
Assignment Operations
Integer Operations
Difficulty: Easy- Given
unsigned int a = 0;. What is the value ofaif you decrement it? - Given
short a = 32766;. What is the value ofshort b = a + 3;? - Given
short b = 30000, c = 30000;. What is the value ofshort d = b * c;?
Sequences of Instructions
Difficulty: EasyGiven three integer variables x, y, z declared and initialized, write sequences of
instructions to:
- Display the maximum of
xandy - Display the absolute value of
z - Display whether the integer
xis even or odd - Display the maximum of
x,y,z
Given character variables c and d declared and initialized, write sequences of
instructions to:
- Determine which of
canddcomes first in the alphabet - Determine whether
cis a lowercase or uppercase letter - Convert
cto uppercase (without knowing in advance whether it is lowercase or uppercase) - Determine whether
cis a consonant or a vowel
Classic Boolean Expressions
Difficulty: RxTranslate each of the following expressions into C:
x=y=zx,y,zare all different from each otherx<y<=z- at least two equal numbers among
x,y,z - exactly two equal numbers among
x,y,z - at most two equal numbers among
x,y,z
Simple Problems
Difficulty: Rx- Given the birth dates of two people provided as day, month, year (where each value is an integer), determine which person is older (person 1 or person 2).
- Given an integer
irepresenting a duration in seconds, display the equivalent duration in the form $h:min$. Write the inverse: given three integer variablesh,m,s, determine the equivalent duration in seconds.
for Loops
Difficulty: Easy
Simple Loops
Write sequences of instructions to:
- Display the integers from 1 to 10 separated by spaces, then from 10 to 1.
- Sum the integers from 1 to 100 and display the result.
- Sum the even integers from 6 to 2048 and display the result.
- Display the list of multiples of 3 or 5 (or both) that are less than 60.
Power Computation
Difficulty: RxWrite an algorithm to compute x^n using only multiplications.
Problem
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. —source Project Euler