Stractured Programming
Stractured Programming
Structured
programming emphasizes clear organization, modular design, and logical flow in writing
code. Here are some practical topics you can explore:
Remember to practice hands-on coding, work on small projects, and gradually build your
skills. Structured programming principles apply not only to specific languages but also to
good coding practices in general. Happy coding! �����
C programming
1. Introduction to C:
o C is a general-purpose programming language created by Dennis Ritchie at
Bell Laboratories in 1972.
o Despite its age, C remains popular due to its fundamental role in computer
science and strong association with UNIX.
o Start by understanding the basics of C, including syntax, data types, and
control structures.
1
o Explore the C Introduction on W3Schools for a solid foundation .
2. C Tutorial:
o Learn C step by step with W3Schools’ comprehensive C Tutorial.
o Topics covered include variables, operators, loops, functions, arrays, pointers,
and more.
o Practice writing C code using the “Try it Yourself” editor provided in each
chapter.
3. Structures (structs):
o Structures (also called structs) allow you to group related variables into one
place.
o Unlike arrays, a structure can contain different data types (int, float, char, etc.).
o Explore how to create and use structures in C with the C Structures
Tutorial2.
4. Object-Oriented Programming (OOP) in C:
o Although C is not a pure OOP language, you can apply OOP principles using
structs and functions.
o Learn about encapsulation, abstraction, and modular design.
o Practice creating reusable code using OOP concepts.
5. Practice and Projects:
o Apply what you’ve learned by working on small projects.
o Write programs that solve real-world problems or simulate specific scenarios.
o Explore algorithms, data structures, and practical applications.
Remember to practice coding regularly, experiment with different concepts, and gradually
build your skills. Structured programming principles apply not only to C but also to good
coding practices in general. Happy coding! �����.
C pogramming(w3schools)
Creating Pointers
You learned from the previous chapter, that we can get the memory
address of a variable with the reference operator &:
Example
int myAge = 43; // an int variable
Try it Yourself »
The address of the variable you are working with is assigned to the pointer:
Example
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the name ptr, that
stores the address of myAge
Try it Yourself »
Example explained
Create a pointer variable with the name ptr, that points to an int variable
(myAge). Note that the type of the pointer has to match the type of the
variable you're working with (int in our example).
Use the & operator to store the memory address of the myAge variable, and
assign it to the pointer.
Dereference
In the example above, we used the pointer variable to get the memory
address of a variable (used together with the & reference operator).
You can also get the value of the variable the pointer points to, by using
the * operator (the dereference operator):
Example
int myAge = 43; // Variable declaration
int* ptr = &myAge; // Pointer declaration
// Reference: Output the memory address of myAge with the pointer
(0x7ffe5367e044)
printf("%p\n", ptr);
Try it Yourself »
Note that the * sign can be confusing here, as it does two different things in
our code:
int* myNum;
int *myNum;
Notes on Pointers
Pointers are one of the things that make C stand out from other
programming languages, like Python and Java.
They are important in C, because they allow us to manipulate the data in the
computer's memory. This can reduce the code and improve the performance.
If you are familiar with data structures like lists, trees and graphs, you
should know that pointers are especially useful for implementing those. And
sometimes you even have to use pointers, for example when working
with files.
C Exercises
Test Yourself With Exercises
Exercise:
Create a pointer variable called ptr, that points to the int variable myAge:
Submit Answer »
❮ PreviousNext ❮
Example
int myNumbers[4] = {25, 50, 75, 100};
You learned from the arrays chapter that you can loop through the array
elements with a for loop:
Example
int myNumbers[4] = {25, 50, 75, 100};
int i;
for (i = 0; i < 4; i++) {
printf("%d\n", myNumbers[i]);
}
Result:
25
50
75
100
Try it Yourself »
Instead of printing the value of each array element, let's print the memory
address of each array element:
Example
int myNumbers[4] = {25, 50, 75, 100};
int i;
Result:
0x7ffe70f9d8f0
0x7ffe70f9d8f4
0x7ffe70f9d8f8
0x7ffe70f9d8fc
Try it Yourself »
Note that the last number of each of the elements' memory address is
different, with an addition of 4.
Example
// Create an int variable
int myInt;
Result:
4
Try it Yourself »
So from the "memory address example" above, you can see that the
compiler reserves 4 bytes of memory for each array element, which means
that the entire array takes up 16 bytes (4 * 4) of memory storage:
Example
int myNumbers[4] = {25, 50, 75, 100};
Result:
16
Try it Yourself »
Confused? Let's try to understand this better, and use our "memory address
example" above again.
The memory address of the first element is the same as the name of the
array:
Example
int myNumbers[4] = {25, 50, 75, 100};
Result:
0x7ffe70f9d8f0
0x7ffe70f9d8f0
Try it Yourself »
This basically means that we can work with arrays through pointers!
Example
int myNumbers[4] = {25, 50, 75, 100};
Result:
25
Try it Yourself »
To access the rest of the elements in myNumbers, you can increment the
pointer/array (+1, +2, etc):
Example
int myNumbers[4] = {25, 50, 75, 100};
// and so on..
Result:
50
75
Try it Yourself »
Example
int myNumbers[4] = {25, 50, 75, 100};
int *ptr = myNumbers;
int i;
Result:
25
50
75
100
Try it Yourself »
Example
int myNumbers[4] = {25, 50, 75, 100};
Result:
13
17
Try it Yourself »
This way of working with arrays might seem a bit excessive. Especially with
simple arrays like in the examples above. However, for large arrays, it can
be much more efficient to access and manipulate arrays with pointers.
And since strings are actually arrays, you can also use pointers to
access strings.
For now, it's great that you know how this works. But like we specified in the
previous chapter; pointers must be handled with care, since it is possible
to overwrite other data stored in memory.
❮ PreviousNext ❮
W3schools Pathfinder
Track your progress - it's free!
Log inSign Up
C Functions
❮ PreviousNext ❮
Functions are used to perform certain actions, and they are important for
reusing code: Define the code once, and use it many times.
Predefined Functions
So it turns out you already know what a function is. You have been using it
the whole time while studying this tutorial!
Example
int main() {
printf("Hello World!");
return 0;
}
Try it Yourself »
Create a Function
To create (often referred to as declare) your own function, specify the name
of the function, followed by parentheses () and curly brackets {}:
Syntax
void myFunction() {
// code to be executed
}
Example Explained
myFunction() is the name of the function
void means that the function does not have a return value. You will
learn more about return values later in the next chapter
Inside the function (the body), add code that defines what the function
should do
Call a Function
Declared functions are not executed immediately. They are "saved for later
use", and will be executed when they are called.
Example
Inside main, call myFunction():
// Create a function
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the function
return 0;
}
Try it Yourself »
Example
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
Try it Yourself »
C Exercises
Test Yourself With Exercises
Exercise:
Create a method named myFunction and call it inside main().
void {
printf("I just got executed!");
}
int main() {
return 0;
}
Submit Answer »
❮ PreviousNext ❮
W3schools Pathfinder
Log inSign Up
C Function Parameters
❮ PreviousNext ❮
Parameters are specified after the function name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma:
Syntax
returnType functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
The following function that takes a string of characters with name as parameter. When the
function is called, we pass along a name, which is used inside the function to print "Hello" and
the name of each person.
Example
void myFunction(char name[]) {
printf("Hello %s\n", name);
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Hello Liam
// Hello Jenny
// Hello Anja
Try it Yourself »
When a parameter is passed to the function, it is called an argument. So, from the example
above: name is a parameter, while Liam, Jenny and Anja are arguments.
Multiple Parameters
Inside the function, you can add as many parameters as you want:
Example
void myFunction(char name[], int age) {
printf("Hello %s. You are %d years old.\n", name, age);
}
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
// Hello Liam. You are 3 years old.
// Hello Jenny. You are 14 years old.
// Hello Anja. You are 30 years old.
Try it Yourself »
Note that when you are working with multiple parameters, the function call must have the same
number of arguments as there are parameters, and the arguments must be passed in the same
order.
Example
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
printf("%d\n", myNumbers[i]);
}
}
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}
Try it Yourself »
Example Explained
The function (myFunction) takes an array as its parameter (int myNumbers[5]), and loops
through the array elements with the for loop.
When the function is called inside main(), we pass along the myNumbers array, which outputs
the array elements.
Note that when you call the function, you only need to use the name of the array when passing it
as an argument myFunction(myNumbers). However, the full declaration of the array is
needed in the function parameter (int myNumbers[5]).
Return Values
The void keyword, used in the previous examples, indicates that the function should not return a
value. If you want the function to return a value, you can use a data type (such as int or float,
etc.) instead of void, and use the return keyword inside the function:
Example
int myFunction(int x) {
return 5 + x;
}
int main() {
printf("Result is: %d", myFunction(3));
return 0;
}
// Outputs 8 (5 + 3)
Try it Yourself »
Example
int myFunction(int x, int y) {
return x + y;
}
int main() {
printf("Result is: %d", myFunction(5, 3));
return 0;
}
// Outputs 8 (5 + 3)
Try it Yourself »
Example
int myFunction(int x, int y) {
return x + y;
}
int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
// Outputs 8 (5 + 3)
Try it Yourself »
Real-Life Example
To demonstrate a practical example of using functions, let's create a program that converts a
value from fahrenheit to celsius:
Example
// Function to convert Fahrenheit to Celsius
float toCelsius(float fahrenheit) {
return (5.0 / 9.0) * (fahrenheit - 32.0);
}
int main() {
// Set a fahrenheit value
float f_value = 98.8;
return 0;
}
Try it Yourself »
❮ PreviousNext ❮
W3schools Pathfinder
Track your progress - it's free!
Log inSign Up
ADVERTISEMENT
C Function Declaration and
Definition
❮ PreviousNext ❮
Example
// Create a function
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the function
return 0;
}
Try it Yourself »
Declaration: the function's name, return type, and parameters (if any)
Definition: the body of the function (code to be executed)
For code optimization, it is recommended to separate the declaration and the definition of the
function.
You will often see C programs that have function declaration above main(), and function
definition below main(). This will make the code better organized and easier to read:
Example
// Function declaration
void myFunction();
// Function definition
void myFunction() {
printf("I just got executed!");
}
Try it Yourself »
Another Example
If we use the example from the previous chapter regarding function parameters and return values:
Example
int myFunction(int x, int y) {
return x + y;
}
int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
// Outputs 8 (5 + 3)
Try it Yourself »
Example
// Function declaration
int myFunction(int, int);
// Function definition
int myFunction(int x, int y) {
return x + y;
}
Try it Yourself »
❮ PreviousNext ❮
W3schools Pathfinder
Log inSign Up
ADVERTISEMENT
C Recursion
❮ PreviousNext ❮
Recursion
Recursion is the technique of making a function call itself. This technique provides a way to
break complicated problems down into simple problems which are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out how it works is to
experiment with it.
Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is more complicated.
In the following example, recursion is used to add a range of numbers together by breaking it
down into the simple task of adding two numbers:
Example
int sum(int k);
int main() {
int result = sum(10);
printf("%d", result);
return 0;
}
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
Try it Yourself »
Example Explained
When the sum() function is called, it adds parameter k to the sum of all numbers smaller
than k and returns the result. When k becomes 0, the function just returns 0. When running, the
program follows these steps:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
Since the function does not call itself when k is 0, the program stops there and returns the result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a
function which never terminates, or one that uses excess amounts of memory or processor power.
However, when written correctly, recursion can be a very efficient and mathematically-elegant
approach to programming.
❮ PreviousNext ❮
W3schools Pathfinder
Log inSign Up
ADVERTISEMENT
C Math Functions
❮ PreviousNext ❮
Math Functions
There is also a list of math functions available, that allows you to perform mathematical tasks on
numbers.
To use them, you must include the math.h header file in your program:
#include <math.h>
Square Root
To find the square root of a number, use the sqrt() function:
Example
printf("%f", sqrt(16));
Try it Yourself »
Round a Number
The ceil() function rounds a number upwards to its nearest integer, and the floor() method
rounds a number downwards to its nearest integer, and returns the result:
Example
printf("%f", ceil(1.4));
printf("%f", floor(1.4));
Try it Yourself »
Power
The pow() function returns the value of x to the power of y (xy):
Example
printf("%f", pow(4, 3));
Try it Yourself »
Function Description
❮ PreviousNext ❮
W3schools Pathfinder
Log inSign Up
ADVERTISEMENT
C Files
❮ PreviousNext ❮
File Handling
In C, you can create, open, read, and write to files by declaring a pointer of type FILE, and use
the fopen() function:
FILE *fptr
fptr = fopen(filename, mode);
FILE is basically a data type, and we need to create a pointer variable to work with it (fptr). For
now, this line is not important. It's just something you need when working with files.
To actually open a file, use the fopen() function, which takes two parameters:
Parameter Description
filename The name of the actual file you want to open (or create), like filename.txt
mode A single character, which represents what you want to do with the file (read, write
or append):
w - Writes to a file
a - Appends new data to a file
r - Reads from a file
Create a File
To create a file, you can use the w mode inside the fopen() function.
The w mode is used to write to a file. However, if the file does not exist, it will create one for
you:
Example
FILE *fptr;
// Create a file
fptr = fopen("filename.txt", "w");
Note: The file is created in the same directory as your other C files, if nothing else is specified.
Tip: If you want to create the file in a specific folder, just provide an absolute path:
This will close the file when we are done with it.
In the next chapters, you will learn how to write content to a file and read from it.
❮ PreviousNext ❮
W3schools Pathfinder
ADVERTISEMENT
C Write To Files
❮ PreviousNext ❮
Write To a File
Let's use the w mode from the previous chapter again, and write something to the file we just
created.
The w mode means that the file is opened for writing. To insert content to it, you can use
the fprintf() function and add the pointer variable (fptr in our example) and some text:
Example
FILE *fptr;
As a result, when we open the file on our computer, it looks like this:
Run example »
Note: If you write to a file that already exists, the old content is deleted, and the new content is
inserted. This is important to know, as you might accidentally erase existing content.
For example:
Example
fprintf(fptr, "Hello World!");
As a result, when we open the file on our computer, it says "Hello World!" instead of "Some
text":
Run example »
As a result, when we open the file on our computer, it looks like this:
Run example »
Note: Just like with the w mode; if the file does not exist, the a mode will create a new file with
the "appended" content.
❮ PreviousNext ❮
W3schools Pathfinder
Log inSign Up
ADVERTISEMENT
C Read Files
❮ PreviousNext ❮
Read a File
In the previous chapter, we wrote to a file using w and a modes inside
the fopen() function.
Example
FILE *fptr;
It requires a little bit of work to read a file in C. Hang in there! We will guide
you step-by-step.
Next, we need to create a string that should be big enough to store the
content of the file.
For example, let's create a string that can store up to 100 characters:
Example
FILE *fptr;
Example
fgets(myString, 100, fptr);
1. The first parameter specifies where to store the file content, which will
be in the myString array we just created.
2. The second parameter specifies the maximum size of data to read,
which should match the size of myString (100).
3. The third parameter requires a file pointer that is used to read the file
(fptr in our example).
Now, we can print the string, which will output the content of the file:
Example
FILE *fptr;
Hello World!
Run example »
Note: The fgets function only reads the first line of the file. If you
remember, there were two lines of text in filename.txt.
To read every line of the file, you can use a while loop:
Example
FILE *fptr;
Hello World!
Hi everybody!
Run example »
Good Practice
If you try to open a file for reading that does not exist, the fopen() function
will return NULL.
Tip: As a good practice, we can use an if statement to test for NULL, and
print some text instead (when the file does not exist):
Example
FILE *fptr;
Run example »
With this in mind, we can create a more sustainable code if we use our "read
a file" example above again:
Example
If the file exist, read the content and print it. If the file does not exist, print a
message:
FILE *fptr;
Hello World!
Hi everybody!
Run example »
❮ PreviousNext ❮
W3schools Pathfinder
C Structures (structs)
❮ PreviousNext ❮
Structures
Structures (also called structs) are a way to group several related variables into one place. Each
variable in the structure is known as a member of the structure.
Unlike an array, a structure can contain many different data types (int, float, char, etc.).
Create a Structure
You can create a structure by using the struct keyword and declare each of its members inside
curly braces:
Use the struct keyword inside the main() method, followed by the name of the structure and
then the name of the structure variable:
struct myStructure {
int myNum;
char myLetter;
};
int main() {
struct myStructure s1;
return 0;
}
Access Structure Members
To access members of a structure, use the dot syntax (.):
Example
// Create a structure called myStructure
struct myStructure {
int myNum;
char myLetter;
};
int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;
// Print values
printf("My number: %d\n", s1.myNum);
printf("My letter: %c\n", s1.myLetter);
return 0;
}
Try it Yourself »
Now you can easily create multiple structure variables with different values, using just one
structure:
Example
// Create different struct variables
struct myStructure s1;
struct myStructure s2;
s2.myNum = 20;
s2.myLetter = 'C';
Try it Yourself »
What About Strings in Structures?
Remember that strings in C are actually an array of characters, and unfortunately, you can't assign
a value to an array like this:
Example
struct myStructure {
int myNum;
char myLetter;
char myString[30]; // String
};
int main() {
struct myStructure s1;
return 0;
}
However, there is a solution for this! You can use the strcpy() function and assign the value
to s1.myString, like this:
Example
struct myStructure {
int myNum;
char myLetter;
char myString[30]; // String
};
int main() {
struct myStructure s1;
Result:
Simpler Syntax
You can also assign values to members of a structure variable at declaration time, in a single line.
Just insert the values in a comma-separated list inside curly braces {}. Note that you don't have to
use the strcpy() function for string values with this technique:
Example
// Create a structure
struct myStructure {
int myNum;
char myLetter;
char myString[30];
};
int main() {
// Create a structure variable and assign values to it
struct myStructure s1 = {13, 'B', "Some text"};
// Print values
printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString);
return 0;
}
Try it Yourself »
Note: The order of the inserted values must match the order of the variable types declared in the
structure (13 for int, 'B' for char, etc).
Copy Structures
You can also assign one structure to another.
s2 = s1;
Try it Yourself »
Modify Values
If you want to change/modify a value, you can use the dot syntax (.).
Example
struct myStructure {
int myNum;
char myLetter;
char myString[30];
};
int main() {
// Create a structure variable and assign values to it
struct myStructure s1 = {13, 'B', "Some text"};
// Modify values
s1.myNum = 30;
s1.myLetter = 'C';
strcpy(s1.myString, "Something else");
// Print values
printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString);
return 0;
}
Try it Yourself »
Modifying values are especially useful when you copy structure values:
Example
// Create a structure variable and assign values to it
struct myStructure s1 = {13, 'B', "Some text"};
// Copy s1 values to s2
s2 = s1;
// Change s2 values
s2.myNum = 30;
s2.myLetter = 'C';
strcpy(s2.myString, "Something else");
// Print values
printf("%d %c %s\n", s1.myNum, s1.myLetter, s1.myString);
printf("%d %c %s\n", s2.myNum, s2.myLetter, s2.myString);
Try it Yourself »
Real-Life Example
Use a structure to store different information about Cars:
Example
struct Car {
char brand[50];
char model[50];
int year;
};
int main() {
struct Car car1 = {"BMW", "X5", 1999};
struct Car car2 = {"Ford", "Mustang", 1969};
struct Car car3 = {"Toyota", "Corolla", 2011};
return 0;
}
Try it Yourself »
C Exercises
Test Yourself With Exercises
Exercise:
Fill in the missing part to create a Car structure:
Car {
char brand[50];
char model[50];
int year;
};
Submit Answer »
❮ PreviousNext ❮
W3schools Pathfinder
Log inSign Up
ADVERTISEMENT
C Enumeration (enum)
❮ PreviousNext ❮
C Enums
An enum is a special type that represents a group of constants (unchangeable values).
To create an enum, use the enum keyword, followed by the name of the enum, and separate the
enum items with a comma:
enum Level {
LOW,
MEDIUM,
HIGH
};
Inside the main() method, specify the enum keyword, followed by the name of the enum
(Level) and then the name of the enum variable (myVar in this example):
Now that you have created an enum variable (myVar), you can assign a value to it.
The assigned value must be one of the items inside the enum (LOW, MEDIUM or HIGH):
By default, the first item (LOW) has the value 0, the second (MEDIUM) has the value 1, etc.
If you now try to print myVar, it will output 1, which represents MEDIUM:
int main() {
// Create an enum variable and assign a value to it
enum Level myVar = MEDIUM;
return 0;
}
Try it Yourself »
Change Values
As you know, the first item of an enum has the value 0. The second has the value 1, and so on.
To make more sense of the values, you can easily change them:
enum Level {
LOW = 25,
MEDIUM = 50,
HIGH = 75
};
printf("%d", myVar); // Now outputs 50
Try it Yourself »
Note that if you assign a value to one specific item, the next items will update their numbers
accordingly:
enum Level {
LOW = 5,
MEDIUM, // Now 6
HIGH // Now 7
};
Try it Yourself »
enum Level {
LOW = 1,
MEDIUM,
HIGH
};
int main() {
enum Level myVar = MEDIUM;
switch (myVar) {
case 1:
printf("Low Level");
break;
case 2:
printf("Medium level");
break;
case 3:
printf("High level");
break;
}
return 0;
}
Try it Yourself »
Use enums when you have values that you know aren't going to change, like month days, days,
colors, deck of cards, etc.
❮ PreviousNext ❮
W3schools Pathfinder
Track your progress - it's free!
Log inSign Up
ADVERTISEMENT
C Examples
❮ PreviousNext ❮
Syntax
Create a simple "Hello World" program
Syntax Explained
Output/Print
Use printf to print textUsing many printf functionsInsert a new line with \n
Output Explained
Comments
Single-line comment before a line of codeSingle-line comment at the end of a line of
codeMulti-line comment
Comments Explained
Variables
Create an integer variable and print itCombine both text and a variableChange/overwrite
variable valuesAdd a variable to another variableDeclare many variables of the same type
with a comma-separated listAssign the same value to multiple variables of the same
typeReal-life variables example
Variables Explained
Constants
Create a constant variableGood practice - use uppercase letters when declaring constants
Constants Explained
Operators
Addition operatorSubtraction operatorDivision operatorModulus operatorIncrement
operatorDecrement operatorAssignment operatorAddition assignment operatorComparison
operatorLogical operatorsUsing the "sizeof" operator to get the memory size of different
variables
Operators Explained
Booleans
Create boolean variablesCompare two valuesCompare two variablesCompare two boolean
variablesReal-life example
Variables Explained
If...Else (Conditions)
The if statementThe else statementThe else if statementShort hand if...else
If...Else Explained
Switch
The switch statementThe switch statement with a default keyword
Switch Explained
Loops
While loopDo while loopFor loopNested loopBreak a loopContinue a loop
Loops Explained
Arrays
Create and access an arrayChange an array elementLoop through an arrayTwo-dimensional
arrayChange elements in a two-dimensional arrayLoop through a two-dimensional array
Arrays Explained
Strings
Create a stringAnother way to create a stringAccess string charactersChange string
charactersLoop through a stringSpecial characters in a stringGet the length of a
stringConcatenate stringsCopy stringsCompare strings
Strings Explained
User Input
Input a number and print the resultInput a string and print the result
User Input Explained
Memory Address/References
Get the memory address of a variable
Memory Address Explained
Pointers
Create a pointer variableGet the value of a variable with the dereference operator *Access an
array with pointersLoop through an array using pointers
Pointers Explained
Functions
Create and call a functionCall a function multiple timesFunction declaration and
definitionParameters and argumentsMultiple parametersPass arrays as function
parametersReturn valueReturn the sum of two parametersRecursion (make a function call
itself)Use a math function to get the square root of a number
Functions Explained
Files
Create a fileWrite to a fileAppend/add content to a fileRead the first line of a fileRead all
lines of a fileGood practice when reading files
Files Explained
Structures
Access a structureCreate multiple structure variables with different valuesString in
structureSimpler Syntax (shorthand)Copy structure valuesModify valuesReal Life Example
Structures Explained
Enums
Create an enum variable and assign a value to itChange the value of enum itemsChange the
value of a specific enum itemEnum in a switch statement
Enums Explained
❮ PreviousNext ❮
W3schools Pathfinder
Log inSign Up
ADVERTISEMENT
C Real-Life Examples
❮ PreviousNext ❮
Practical Examples
This page contains a list of practical examples used in real world projects.
// Student data
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25;
char studentGrade = 'B';
// Print variables
printf("Student id: %d\n", studentID);
printf("Student age: %d\n", studentAge);
printf("Student fee: %f\n", studentFee);
printf("Student grade: %c", studentGrade);
Try it Yourself »
Example
Calculate the area of a rectangle (by multiplying the length and width)
Example
Use different data types to calculate and output the total cost of a number of items:
// Print variables
printf("Number of items: %d\n", items);
printf("Cost per item: %.2f %c\n", cost_per_item, currency);
printf("Total cost = %.2f %c\n", total_cost, currency);
Try it Yourself »
Example
Calculate the percentage of a user's score in relation to the maximum score in a game:
For a tutorial about variables and data types in C, visit our Variables Chapter and Data Types
Chapter.
Booleans
Example
Find out if a person is old enough to vote:
You could also wrap the code above in an if...else to perform different actions depending on
the result:
Example
Output "Old enough to vote!" if myAge is greater than or equal to 18. Otherwise output "Not
old enough to vote.":
Conditions (If..Else)
Example
Use if..else statements to output some text depending on what time it is:
Example
Check whether the user enters the correct code:
if (doorCode == 1337) {
printf("Correct code.\nThe door is now open.");
} else {
printf("Wrong code.\nThe door remains closed.");
}
Try it Yourself »
Example
Find out if a number is positive or negative:
int myNum = 10;
if (myNum > 0) {
printf("The value is a positive number.");
} else if (myNum < 0) {
printf("The value is a negative number.");
} else {
printf("The value is 0.");
}
Try it Yourself »
Example
Find out if a person is old enough to vote:
Example
Find out if a number is even or odd:
int myNum = 5;
if (myNum % 2 == 0) {
printf("%d is even.\n", myNum);
} else {
printf("%d is odd.\n", myNum);
}
Try it Yourself »
Switch
Example
Use the weekday number to calculate and output the weekday name:
int day = 4;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
}
Try it Yourself »
While Loops
Example
Use a while loop to create a simple "countdown" program:
int countdown = 3;
Example
Use a while loop to play a game of Yatzy:
int dice = 1;
Example
Use a while loop to reverse some numbers:
For a tutorial about while loops in C, visit our While Loop Chapter.
For Loops
Example
Use a for loop to create a program that only print even values between 0 and 10:
int i;
Example
Use a for loop to create a program that counts to 100 by tens:
Try it Yourself »
Example
Use a for loop to create a program that prints the multiplication table of a specified number (2 in
this example):
int number = 2;
int i;
return 0;
Try it Yourself »
For a tutorial about for loops in C, visit our For Loop Chapter.
Arrays
Example
Create a program that calculates the average of different ages:
Try it Yourself »
Example
Create a program that finds the lowest age among different ages:
// Loop through the elements of the ages array to find the lowest age
for (int i = 0; i < length; i++) {
if (lowestAge > ages[i]) {
lowestAge = ages[i];
}
}
Try it Yourself »
Strings
Example
Use strings to create a simple welcome message:
Try it Yourself »
Example
Create a program that counts the number of characters found in a specific word:
Try it Yourself »
User Input
Example
Get the name of a user and print it:
char fullName[30];
Run example »
For a tutorial about user input in C, visit our User Input Chapter.
Functions
Example
Use a function to create a program that converts a value from fahrenheit to celsius:
int main() {
// Set a fahrenheit value
float f_value = 98.8;
// Call the function with the fahrenheit value
float result = toCelsius(f_value);
return 0;
}
Try it Yourself »
Structures
Example
Use a structure to store and output different information about Cars:
struct Car {
char brand[50];
char model[50];
int year;
};
int main() {
struct Car car1 = {"BMW", "X5", 1999};
struct Car car2 = {"Ford", "Mustang", 1969};
struct Car car3 = {"Toyota", "Corolla", 2011};
return 0;
}
Try it Yourself »
W3schools Pathfinder
Log inSign Up
ADVERTISEMENT
C Exercises
❮ PreviousNext ❮
Exercises
We have gathered a variety of C exercises (with answers) for each C Chapter.
Try to solve an exercise by editing some code, or show the answer to see what you've done
wrong.
Start C Exercises
Good luck!
Start C Exercises ❮
If you don't know C, we suggest that you read our C Tutorial from scratch.
❮ PreviousNext ❮
W3schools Pathfinder
Track your progress - it's free!
Log inSign Up
ADVERTISEMENT