Basic elements of the C language
The C programming language is the foundation of modern programming and is known for its efficiency and closeness to the hardware. Its simple but powerful syntax lets programmers develop high-performance applications, operating systems and embedded systems. Understanding the basic elements of C, such as variables, operators and loops, is the key to moving on to more complex concepts and languages such as C++ and Java. This page gives basic information and practical examples that will help you master the core of the C language.
Elements of the C language
- Lexical symbols.
An indivisible sequence of characters Identifiers, constants, keywords, operators, separators
- White space characters:
Space, tab, vertical tab, new line and new page
- Comments.
Any text that is ignored by the compiler:
// komentar do kraja reda /* a comment over several lines */ - Statements.
These are sequences of lexical symbols. They can be declarative or executable.
- Programs.
These are sequences of statements that carry out complex data processing.
- Preprocessor directives.
These are instructions that can affect how a program is compiled. They are handled by the preprocessor, the part of the C compiler that prepares the text before the actual compilation
They start with the directive #
Identifiers
They are used to name all kinds of program elements: data, symbolic constants, data types defined by the programmer, subprograms. They can consist of letters, digits and underscores (_).
Examples of valid ones
a, b, x, alfa, ALFA, datum_rodjenja, cena, a1
Examples of invalid ones
12ab, x-z, int
Keywords of the C language
These are reserved words of the C language and cannot be used as identifiers.
auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for, goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while.
Section: Exercises for practical learning
1. Adding two numbers
Task: Write a program that reads two integers and prints their sum.
Code:
#include <stdio.h>
int main() {
int a, b, suma;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
suma = a + b;
printf("The sum of the numbers is: %d\n", suma);
return 0;
}
For more information about data types, see the lesson Data in C.
2. Checking parity
Task: Write a program that checks whether the entered number is even or odd.
Code:
#include <stdio.h>
int main() {
int broj;
printf("Enter a number: ");
scanf("%d", &broj);
if (broj % 2 == 0) {
printf("The number %d is even.\n", broj);
} else {
printf("The number %d is odd.\n", broj);
}
return 0;
}
3. A logical expression: is the number greater than 5
Task: Write a program that checks whether the entered number is greater than 5. Store the result of the comparison in the integer variable uslov (condition) (in C true = 1, false = 0).
Code:
#include <stdio.h>
int main() {
int a, x, uslov;
scanf("%d", &a);
x = 5;
uslov = a > x;
if (uslov) {
printf("The number %d is greater than 5\n", a);
} else {
printf("The number %d is not greater than 5\n", a);
}
return 0;
}
4. A prime number (more advanced)
Task: Write a program that checks whether a number is prime.
Code:
#include <stdio.h>
int main() {
int broj, prost = 1;
printf("Enter a number: ");
scanf("%d", &broj);
if (broj <= 1) {
prost = 0;
} else {
for (int i = 2; i <= broj / 2; i++) {
if (broj % i == 0) {
prost = 0;
break;
}
}
}
if (prost) {
printf("The number is prime.\n");
} else {
printf("The number is not prime.\n");
}
return 0;
}
Tips
After solving the tasks, experiment with different inputs to understand better how the program works.
An advanced challenge
Combine these elements and write a more complex program, such as a simple calculator that supports addition, subtraction, multiplication and division.
An explanation of more complex topics in C
1. Pointers
Pointers are one of the key elements of C and allow you to manipulate memory addresses, which makes them extremely powerful, but also complex to understand. The lesson on pointers covers:
- What pointers are: A short introduction to memory addresses and how pointers work.
- Declaring and initializing pointers: Examples of how to declare pointers and assign values to them.
- Operations with pointers: Using the operators * and &, and pointer arithmetic.
- Practical use: Pointers in functions (passing arguments by reference) and working with dynamic memory using functions such as malloc and free.
Example:
#include <stdio.h>
int main() {
int x = 10;
int *ptr = &x; // ptr stores the address of the variable x
printf("The value of the variable x: %d\n", x);
printf("The address of the variable x: %p\n", (void *)&x);
printf("The value ptr points to: %d\n", *ptr);
return 0;
}
For more information about pointers, see the lesson Pointers
2. Working with arrays
Arrays let you store several elements of the same type under one name, which makes them the basic building block of data structures. The lesson on arrays covers:
- Declaring and initializing arrays: Creating static and dynamic arrays.
- Working with arrays: Iterating through the elements with loops.
- Multidimensional arrays: The basics of working with matrices and their use in problems such as sorting algorithms and matrix multiplication.
- The link between arrays and pointers: An explanation of how arrays and pointers are connected in C.
Example:
#include <stdio.h>
int main() {
int niz[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, niz[i]);
}
return 0;
}
For more information about arrays, see Arrays in C/C++
3. Functions
Functions are the basic tool for organizing code in C. The lesson on functions covers:
- Declaring and defining functions: The difference between a prototype and the implementation of a function.
- Passing arguments: An explanation of the difference between passing by value and by reference.
- Recursive functions: Examples of recursion for solving problems such as factorial, the Fibonacci sequence or the Towers of Hanoi.
- A modular approach: Using functions to organize more complex programs.
Example:
#include <stdio.h>
int faktorijel(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * faktorijel(n - 1);
}
int main() {
int broj = 5;
printf("The factorial of %d is %d\n", broj, faktorijel(broj));
return 0;
}
For more information about functions, see Functions in C
Related articles
Strings in C
Tasks with data
String examples
Algorithms
Tests and test tasks (SR)
Check your knowledge
Open the quiz
Quiz: Elements of the C language
1. Which identifier is valid?
2. How do you write a comment to the end of the line?
3. Can int be the name of a variable?
4. What do preprocessor directives such as include start with?
Basic Elements of the C Language
Every C program is built from the same small set of building blocks: characters, tokens (keywords, identifiers, constants, operators, separators), comments, statements and blocks. Knowing their names and rules makes compiler messages much easier to understand.
Structure of a C program
The smallest complete program has a main function – the place where execution starts:
#include <stdio.h> /* library with printf and scanf */
int main(void) { /* execution starts here */
printf("Hello, world!\n");
return 0; /* 0 means: the program finished correctly */
}
| Part | Meaning |
|---|---|
#include <stdio.h> | preprocessor directive – includes declarations of input/output functions |
int main(void) | main function; int is the type of the value it returns |
{ ... } | block – a group of statements |
printf(...); | statement; every simple statement ends with a semicolon |
return 0; | ends main and reports success to the operating system |
Tokens: the words of the language
The compiler first splits the source code into tokens – the smallest meaningful units. There are five kinds:
| Kind | Examples |
|---|---|
| keywords | int, double, if, else, for, while, return, void |
| identifiers | sum, maxValue, count_2 – names chosen by the programmer |
| constants (literals) | 42, 3.14, 'A', "text" |
| operators | + - * / % = == < && ++ |
| separators | ; , ( ) { } [ ] |
In the statement sum = a + 5; the tokens are: sum, =, a, +, 5 and ;.
Rules for identifiers
- they may contain letters of the English alphabet, digits and the underscore
_; - they must not start with a digit (
2sumis wrong,sum2is fine); - a keyword cannot be used as a name (
int for;is an error); - C is case sensitive:
sum,SumandSUMare three different names.
Choose names that say what the variable holds: numberOfStudents is better than n2.
Whitespace and comments
Spaces, tabs and new lines (whitespace) separate tokens; the compiler ignores extra whitespace, so we use it to make code readable. Comments are text for people – the compiler skips them:
#include <stdio.h>
int main(void) {
// a one-line comment lasts until the end of the line
int a = 7, b = 5;
/* a multi-line comment
can span several lines */
printf("%d\n", a * b); /* a comment can follow code */
return 0;
}
Statements and blocks
A statement is an instruction for the computer: a declaration (int x;), an assignment (x = 5;), a function call (printf(...);) or a control statement (if, for, while). Curly braces join several statements into a block, which is treated as one statement:
#include <stdio.h>
int main(void) {
int x;
scanf("%d", &x);
if (x > 0) { /* block: two statements run together */
printf("positive\n");
printf("square: %d\n", x * x);
} else
printf("not positive\n"); /* a single statement needs no braces */
return 0;
}
- Forgetting the semicolon is the most common error; the compiler often reports it on the next line.
mainis written in lower case –Mainis a different name and the program will not link.- A comment started with
/*must be closed with*/, otherwise the rest of the file is a comment.
