1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
/** * File: hello.c * Author: Risto Heinsar * Created: 01.09.2014 * Edited: 10.08.2023 * * Description: This is an extended "Hello, world!" sample * introducing you to variable declarations and * input and output commands */ #include <stdio.h> // includes the standard input-output library (printf, scanf) int main(void) // The program always starts from the main function { char userName[21]; // Declare variable for text, 20 + 1 characters int year, age; // Declare 2 variables for integers printf("Hello!\n"); // Print text to the terminal. \n - newline printf("What's Your name?\n"); scanf("%s", userName); // Reads input from user, %s - format for text // Stores it in the varibable userName // Printing text, places contents of userName variable to placeholder %s printf("Hello, %s. Nice to meet You!\n", userName); printf("When were You born?\n"); scanf("%d", &year); // To read integers, format specifier %d is used // Ampersand (&) must be placed before the variable name // whenever reading a number (e.g. integer) // Calculating the rough estimate of the age age = 2023 - year; // The calculation is always placed on the right of the // assignment operator (=). It will be evaluated. // The result is stored in the variable placed on the // left of the assignment operator. printf("%s, You are most likely %d years of age\n", userName, age); return 0; // The program finished successfully. 0 indicates success. } |
Some common errors when starting to code C
- Missing semicolon after a statement
- Mistyping the library name (studio instead of stdio)
- Forgetting to include newline characters
- Including a newline in the scanf format (“%d\n”) – typically you don’t want it there
- Missing & (ampersand) when reading a single integer, float or character
- Mixing upper and lower case characters – C is case sensitive
The program converted into UML