Week 2 Code Examples
#include<stdio.h>
// this is a constant that sets MIN_AGE to 18
#define MIN_AGE 18
int main(void) {
int age;
printf("Enter your age: ");
scanf("%d", &age);
// check is age is valid
if (age <= 0) {
printf("That is invalid!\n");
} else {
// we know for a fact everythign here is a positive age!
// age is 1 or higher
// are you greater than 0 but less than 18
if(age < MIN_AGE) {
printf("You are too young (but valid!)! Get out\n");
} else {
printf("You are legal! Enjoy\n");
}
}
return 0;
}
#include<stdio.h>
int main(void) {
int number_of_lines = 5;
int i = 0;
while (i < number_of_lines) {
printf("hey!\n");
i = i + 1;
}
}
#include<stdio.h>
int main(void) {
int finished = 0;
while (!finished) {
printf("hey! Keep printing?\n");
printf("(enter 1 if finished): ");
scanf("%d", &finished);
}
printf("Program finishing up\n");
}
// A while inside a while (tick tock)
// Demonstrating how you can put a while inside a while to print out a
// grid of numbers
// Week 2, Lecture 4
/* Problem: Print out a grid of numbers that looks like this:
1 2 3 4 5
*/
#include <stdio.h>
int main(void) {
// 1. Initialise a loop control variable
// int count = 1;
int i = 0;
int j = 1;
int size;
printf("What is the size of the square you want to print? ");
scanf("%d", &size);
// 2. Test the condition of the size
while (i < size) {
j = 1;
while (j <= size) {
printf("%d ", j);
j++;
}
printf("\n");
//
//3. Update the loop control variable
// count++; // count = count + 1;
i++;
}
return 0;
}
// A while inside a while (tick tock)
// Demonstrating how you can put a while inside a while to print out a
// pyramid of numbers
// Week 2, Lecture 4
/* Problem: Print out a grid of numbers that looks like this:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
*/
#include <stdio.h>
#define SIZE 5
int main(void) {
int i = 1;
while (i <= SIZE) {
int j = 1;
while (j <= i) {
printf("%d ", j);
j++;
}
printf("\n");
i++;
}
return 0;
}
// This program will demonstrate a simple while loop
// Week 2 Lecture 4
#include <stdio.h>
int main(void) {
// 1. Initiliase the loop counter before the loop (before the loop!)
int counter = 0;
// 2. Test for the condition in the loop (the loop itself)
while (counter < 10) {
printf("Loop number %d - here we go!\n", counter);
// 3. Update the loop counter (inside the loop!)
counter++; // counter = counter + 1;
}
// What will the counter be when I exit out of the loop? COUNTER = 10
return 0;
}