C & C++ Language-3
C & C++ Language-3
Example
// Create variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
OUT PUT
5
5.990000
D
Double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for
storing 15 decimal digits
Out Put
#include <stdio.h>
int main() {
printf("%d\n", myNum);
printf("%i\n", myNum);
return 0;
%f Float
Out Put
#include <stdio.h>
int main() {
printf("%f", myFloatNum);
return 0;
}
C Type Conversion
Type Conversion
Sometimes, you have to convert the value of one data type to another type. This is
known as type conversion.
For example, if you try to divide two integers, 5 by 2, you would expect the result to
be 2.5. But since we are working with integers (and not floating-point values), the result
is just 2:
Example
int x = 5;
int y = 2;
int sum = 5 / 2;
printf("%d", sum); //
Outputs 2
Implicit Conversion (automatically)
Explicit Conversion (manually)
Implicit Conversion
Implicit conversion is done automatically by the compiler when you assign a value of one
type to another.
Example
// Automatic conversion: int to float
float myFloat = 9;
printf("%f", myFloat); // 9.000000
As you can see, the compiler automatically converts the int value 9 to a float value
of 9.000000.
This can be risky, as you might lose control over specific values in certain situations.
Especially if it was the other way around - the following example automatically converts
the float value 9.99 to an
Example
// Automatic conversion: float to int
int myInt = 9.99;
printf("%d", myInt); // 9
What happened to .99? We might want that data in our program! So be careful. It is
important that you know how the compiler work in these situations, to avoid unexpected
results.
As another example, if you divide two integers: 5 by 2, you know that the sum is 2.5.
And as you know from the beginning of this page, if you store the sum as an integer, the
result will only display the number 2. Therefore, it would be better to store the sum as
a float or a double, right?
Example
float sum = 5 / 2;
Why is the result 2.00000 and not 2.5? Well, it is because 5 and 2 are still integers in
the division. In this case, you need to manually convert the integer values to floating-
point values. (See below).
Explicit Conversion
Explicit conversion is done manually by placing the type in parentheses () in front of the
value.
Considering our problem from the example above, we can now get the right result:
Example
// Manual conversion: int to float
float sum = (float) 5 / 2;
Example
int num1 = 5;
int num2 = 2;
float result = (float) num1 / num2;
If you don't want others (or yourself) to change existing variable values, use
the const keyword (this will declare the variable as "constant", which
means unchangeable and read-only):
Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'
Out Put
prog.c: In function 'main':
prog.c:5:18: error: assignment of read-only variable 'myNum'
5 | myNum = 10;
| ^
ou should always declare the variable as constant when you have values that
are unlikely to change:
Example
const int minutesPerHour = 60;
const float PI = 3.14;
Out Put
60
3.140000
Notes on Constants
When you declare a constant variable, it must be assigned with a value:
Example
const int minutesPerHour = 60;
const int minutesPerHour;
minutesPerHour = 60; // error
Good Practice
Another thing about constant variables, is that it is considered good practice to
declare them with uppercase. It is not required, but useful for code readability
and common for C programmers:
Example
const int BIRTHYEAR = 1980;
Out Put
1980
C Operators
#include <stdio.h>
int main() {
int x = 5;
printf("%d", ++x);
return 0;
#include <stdio.h>
int main() {
int x = 5;
printf("%d", --x);
return 0;
}
C Booleans
Booleans
Very often, in programming, you will need a data type that can only have one of
two values, like:
YES / NO
ON / OFF
TRUE / FALSE
Boolean Variables
In C, the bool type is not a built-in data type, like int or char.
It was introduced in C99, and you must import the following header file to use
it:
#include <stdbool.h>
A boolean variable is declared with the bool keyword and can only take the
values true or false:
Before trying to print the boolean variables, you should know that boolean
values are returned as integers:
Try it
1
0
#include <stdio.h>```````````````````````
int main() {
return 0;
}
However, it is more common to return a boolean value
by comparing values and variables.
For example, you can use a comparison operator, such as the greater than (>)
operator, to compare two values:
Example
printf("%d", 10 > 9); // Returns 1 (true) because 10 is greater than 9
Try It
#include <stdio.h>
int main() {
return 0;
Output 1
From the example above, you can see that the return value is a
boolean value.
Example
int x = 10;
int y = 9;
printf("%d", x > y);
Try it Yourself »
include <stdio.h>
int main() {
int x = 10;
int y = 9;
return 0;
Output 1
Example
printf("%d", 10 == 10); // Returns 1 (true), because 10 is equal to 10
printf("%d", 10 == 15); // Returns 0 (false), because 10 is not equal to
15
printf("%d", 5 == 55); // Returns 0 (false) because 5 is not equal to 55
Try It
#include <stdio.h>
int main() {
return 0;
Output 1
You are not limited to only compare numbers. You can also compare boolean
variables, or even special structures, like arrays (which you will learn more
about in a later chapter):
Example
bool isHamburgerTasty = true;
bool isPizzaTasty = true;
Out Put
1
Remember to include the <stdbool.h> header file when working
with bool variables.
In the example below, we use the >= comparison operator to find out if the age
(25) is greater than OR equal to the voting age limit, which is set to 18:
Example
int myAge = 25;
int votingAge = 18;
Out Put
You can use these conditions to perform different actions for different decisions.
Syntax
If (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an
error.
In the example below, we test two values to find out if 20 is greater than 18. If
the condition is true, print some text:
Example
if (20 > 18) {
printf("20 is greater than 18");
}
Out Put
20 is greater than 18
Example
int x = 20;
int y = 18;
if (x > y) {
printf("x is greater than y");
}
Out Put
x is greater than y
Example explained
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
Example explained
In the example above, time (20) is greater than 18, so the condition is false.
Because of this, we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".
The else if Statement
Use the else if statement to specify a new condition if the first condition
is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
Example
int time = 22;
if (time < 10) {
printf("Good morning.");
} else if (time < 20) {
printf("Good day.");
} else {
printf("Good evening.");
}
Outputs "Good evening."
Example explained
However, if the time was 14, our program would print "Good day."
Another Example
This example shows how you can use if..else to find out if a number is positive
or negative:
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.");
}
OUTPUT
C Exercises
est Yourself With Exercises
Exercise:
Print "Hello World" if x is greater than y.
int x = 50;
int y = 10;
(x y) {
printf("Hello World");
}
C Short Hand If Else
Short Hand If...Else (Ternary Operator)
There is also a short-hand if else, which is known as the ternary
operator because it consists of three operands. It can be used to replace
multiple lines of code with a single line. It is often used to replace simple if else
statements:
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:
Example
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
Example
int time = 20;
(time < 18) ? printf("Good day.") : printf("Good evening.");
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The example below uses the weekday number to calculate the weekday name:
Example
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;
}
OutPut Thursday
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no
need for more testing.
A break can save a lot of execution time because it "ignores" the execution of
all the rest of the code in the switch block.
The default Keyword
The default keyword specifies some code to run if there is no case match:
Example
int day = 4;
switch (day) {
case 6:
printf("Today is Saturday");
break;
case 7:
printf("Today is Sunday");
break;
default:
printf("Looking forward to the Weekend");
}
Note: The default keyword must be used as the last statement in the switch,
and it does not need a break.
Exercise:
Insert the missing parts to complete the following switch statement:
int day = 2;
switch ( ) {
1:
printf("Monday");
;
2:
printf("Sunday");
;
}
OutPut
int day = 2;
day
switch ( ) {
case
1:
printf("Monday");
break
;
case
2:
printf("Sunday");
break
;
}
C While Loop
C Arrays
Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
To create an array, define the data type (like int) and specify the name of the
array followed by square brackets [].
int myNumbers[] = {25, 50, 75, 100};
Array indexes start with 0: [0] is the first element. [1] is the second element,
etc.
Example
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);
Outputs 25
Change an Array Element
To change the value of a specific element, refer to the index number:
Example
myNumbers[0] = 33;
Example
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
Now outputs 33
Example
int myNumbers[] = {25, 50, 75, 100};
int i;
OutPuts 25 50 75 100
Set Array Size
Another common way to create arrays, is to specify the size of the array, and
add elements later:
Example
// Declare an array of four integers:
int myNumbers[4];
// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;
OutPut 25
Using this method, you should know the size of the array, in order for the
program to store enough memory.
You are not able to change the size of the array after creation.
Exercise:
Create an array of type int called myNumbers.
Unlike many other programming languages, C does not have a String type to
easily create string variables. Instead, you must use the char type and create
an array of characters to make a string in C:
To output the string, you can use the printf() function together with the
format specifier %s to tell C that we are now working with strings:
Example
char greetings[] = "Hello World!";
printf("%s", greetings);
output
Hello World!
Access Strings
Since strings are actually arrays in C, you can access a string by referring to its
index number inside square brackets [].
Example
char greetings[] = "Hello World!";
printf("%c", greetings[0]);
OutPut H
Modify Strings
To change the value of a specific character in a string, refer to the index
number, and use single quotes:
Example
char greetings[] = "Hello World!";
greetings[0] = 'J';
printf("%s", greetings);
// Outputs Jello World! instead of Hello World!
Example
char carName[] = "Volvo";
int i;
V
o
l
v
o
You should also note that you can create a string with a set of characters. This
example will produce the same result as the example in the beginning of this
page:
Example
char greetings[] = {'H', 'e', 'l', 'l', 'o', '
', 'W', 'o', 'r', 'l', 'd', '!', '\0'};
printf("%s", greetings);
OutPut
Hello World!
Hello World!
Example
Output a number entered by the user:
// Create an integer variable that will store the number we get from the
user
int myNum;
Multiple Inputs
The scanf() function also allow multiple inputs (an integer and a character in the
following example):
Example
// Create an int and a char variable
int myNum;
char myChar;
// Get and save the number AND character the user types
scanf("%d %c", &myNum, &myChar);
Out Put
Type a number AND a character and press enter: 5b
Your number is: 5
Your character is: b
Example
Output the name of a user:
// Create a string
char firstName[30];
Out Put
Enter your first name and press enter:
Note: When working with strings in scanf(), you must specify the
size of the string/array (we used a very high number, 30 in our example, but
atleast then we are certain it will store enough characters for the first name),
and you don't have to use the reference operator (%).
Example
char fullName[30];
printf("Hello %s", fullName);
From the example above, you would expect the program to print "John Doe",
but it only prints "John".
Example
char fullName[30];
printf("Hello %s", fullName);
OutPut
Enter your first name and press enter:
Use the scanf() function to get a single word as input, and
use fgets() for multiple words.
C Memory Address
Memory Address
When a variable is created in C, a memory address is assigned to the variable.
The memory address is the location of where the variable is stored on the
computer.
To access it, use the reference operator (&), and the result represents where the
variable is stored:
Example
int myAge = 43;
printf("%p", &myAge); // Outputs 0x7ffe5367e044
Note: The memory address is in hexadecimal form (0x..). You will probably not
get the same result in your program, as this depends on where the variable is
stored on your computer.
You should also note that &myAge is often called a "pointer". A pointer basically
stores the memory address of a variable as its value. To print pointer values,
we use the %p format specifier.
Pointers are one of the things that make C stand out from other programming
languages, like Python and Java.
C Pointers
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
OUT PUT
43
0x7ffe5367e044
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
// Output the value of myAge (43)
printf("%d\n", myAge);
OUT PUT
43
0x7ffe5367e044
0x7ffe5367e044
Example explained
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
Note that the * sign can be confusing here, as it does two different things in our
code:
Good To Know: There are two ways to declare pointer variables, but the first
way is recommended:
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.
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
Example
int main() {
printf("Hello World!");
return 0;
}
Hello World!
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
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;
}
Example
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
Outputs
C Exercises
Exercise:
Create a method named myFunction and call it inside main().
void {
printf("I just got executed!");
}
int main() {
return 0;
}
C Function Parameters
Parameters and Arguments
Information can be passed to functions as a parameter. Parameters act as
variables inside the function.
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
}
Example
void myFunction(char name[]) {
printf("Hello %s\n", name);
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
OutPuts
Hello Liam
Hello Jenny
Hello Anja
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;
}
OutPuts
Hello Liam. You are 3 years old.
Hello Jenny. You are 14 years old.
Hello Anja. You are 30 years old.
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.
Pass Arrays as Function Parameters
You can also pass arrays to a function:
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;
}
OutPuts
10
20
30
40
50
Example Explained
The function (myFunction) takes an array as its parameter (int myNumbers[5]), and
loops through the array elements with the for loop.
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;
}
Result is: 8
Example
int myFunction(int x, int y) {
return x + y;
}
int main() {
printf("Result is: %d", myFunction(5, 3));
return 0;
}
Result is: 8
int myFunction(int x, int y) {
return x + y;
}
int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
Result is: 8
You just learned from the previous chapters that you can create and call a
function in the following way:
Example
// Create a function
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the function
return 0;
}
void myFunction() { // declaration
// the body of the function (definition)
}
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:
Function declaration
void myFunction();
// Function definition
void myFunction() {
printf("I just got executed!");
}
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)
Result is: 8
Example
// Function declaration
int myFunction(int, int);
// Function definition
int myFunction(int x, int y) {
return x + y;
}
Result is: 8
C Recursion
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
C Math Functions
Math Functions
There is also a list of math functions available, that allows you to perform
mathematical tasks on numbers.
include <stdio.h>
#include <math.h>
int main() {
printf("%f", sqrt(16));
return 0;
Example
printf("%f", ceil(1.4));
printf("%f", floor(1.4));
Power
The pow() function returns the value of x to the power of y (xy):
Example
int main() {
return 0;
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.
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):
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");
int main() {
FILE *fptr;
fclose(fptr);
return 0;
Tip: If you want to create the file in a specific folder, just provide an absolute
path:
fptr = fopen("C:\directoryname\filename.txt", "w");
C Write To Files
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 fprint() 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 »
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 fprint() 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 »
Example
FILE *fptr;
As a result, when we open the file on our computer, it looks like this:
Run example »
C Read Files
Read a File
In the previous chapter, we wrote to a file using w and a modes inside
the fopen() function.
Example
FILE *fptr;
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
Example
FILE *fptr;
Note: The fgets function only reads the first line of the file. If you remember,
there were two lines of text in filename.txt.
Example
FILE *fptr;
OutPut
Hello World!
Hi everybody!
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;
With this in mind, we can create a more sustainable code if we use our "read a
file" example above again:
Example
FILE *fptr;
C Structures (structs)
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:
struct myStructure {
int myNum;
char myLetter;
};
int main() {
struct myStructure s1;
return 0;
}
Example
include <stdio.h>
struct myStructure {
int myNum;
char myLetter;
};
int main() {
s1.myNum = 13;
s1.myLetter = 'B';
// Print values
}OutPut
My number: 13
My letter: B
Now you can easily create multiple structure variables with different values,
using just one structure:
Example
#include <stdio.h>
struct myStructure {
int myNum;
char myLetter;
};
int main() {
s1.myNum = 13;
s1.myLetter = 'B';
s2.myNum = 20;
s2.myLetter = 'C';
// Print values
return 0;
Out Put
s1 number: 13
s1 letter: B
s2 number: 20
s2 letter: C
Example
include <stdio.h>
struct myStructure {
int myNum;
char myLetter;
};
int main() {
return 0;
Out Put
prog.c: In function �main�:
prog.c:12:15: error: assignment to expression with array type
12 | s1.myString = "Some text"; // Assign a value to the string
| ^
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;
return 0;
}
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"};
return 0;
}
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.
Example
struct myStructure s1 = {13, 'B', "Some text"};
struct myStructure s2;
s2 = s1;
Example
#include <stdio.h>
struct myStructure {
int myNum;
char myLetter;
char myString[30];
};
int main() {
// Copy s1 values to s2
s2 = s1;
// Print values
return 0;
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"};
return 0;
}
Modifying values are especially useful when you copy structure values:
Example
#include <stdio.h>
#include <string.h>
struct myStructure {
int myNum;
char myLetter;
char myString[30];
};
int main() {
// Copy s1 values to s2
s2 = s1;
// Change s2 values
s2.myNum = 30;
s2.myLetter = 'C';
// Print values
return 0;
}
Result: 13 B Some text
30 C Something else
Imagine you have to write a program to store different information about Cars,
such as brand, model, and year. What's great about structures is that you can
create a single "Car template" and use it for every cars you make. See below for
a real life example.
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;
}
C Exercises
Exercise:
Fill in the missing part to create a Car structure:
Car {
char brand[50];
char model[50];
int year;
};
C Exercise:
Insert the missing part of the code below to output "Hello World!".
int () {
("Hello World!");
return 0;
}
C Comments
Exercise:
Comments in C are written with special characters. Insert the missing parts:
C Variables
Exercise 1:
Create a variable named myNum and assign the value 50 to it.
= ;
Exercise 2:
Use the correct format specifier to output the value of myNum:
Exercise 3:
Display the sum of 5 + 10, using two variables: x and y.
= ;
int y = 10;
printf("%d", x + y);
Exercise 3:
Fill in the missing parts to create three variables of the same type, using
a comma-separated list:
x = 5 y = 6 z = 50;
printf("%d", x + y + z);
C Data Types
Exercise 1:
Add the correct data type for the following variables:
myNum = 5;
myFloatNum = 5.99;
myLetter = 'D';
Exercise 2:
Add the correct format specifier to print the value of the following variable:
C Operators
Exercise 1:
Fill in the blanks to multiply 10 with 5, and print the result.
int x = 10;
int y = 5;
printf(" ", x y);
Exercise 2:
Fill in the blanks to divide 10 by 5, and print the result.
int x = 10;
int y = 5;
printf(" ", x y);
Exercise 3:
Use the correct operator to increase the value of the variable x by 1.
int x = 10;
x ;
Exercise 4:
Use the addition assignment operator to add the value 5 to the variable x.
int x = 10;
x 5;
C If….Else
Exercise 1:
Print "Hello World" if x is greater than y.
int x = 50;
int y = 10;
(x y) {
printf("Hello World");
}
Exercise 2:
Print "Hello World" if x is equal to y.
int x = 50;
int y = 50;
(x y) {
printf("Hello World");
}
Exercise 3:
Print "Yes" if x is equal to y, otherwise print "No".
int x = 50;
int y = 50;
(x y) {
printf("Yes");
} {
printf("No");
}
Exercise 4:
Print "1" if x is equal to y, print "2" if x is greater than y, otherwise print "3".
int x = 50;
int y = 50;
(x y) {
printf("1");
} (x y) {
printf("2");
} {
printf("3");
}
C Switch
Exercise 1:
Insert the missing parts to complete the following switch statement.
int day = 2;
switch ( ) {
1:
printf("Monday");
;
2:
printf("Sunday");
;
}
Exercise 2:
Complete the switch statement, and add the correct keyword at the end to
specify some code to run if there is no case match in the switch statement.
int day = 4;
switch ( ) {
1:
printf("Saturday");
;
2:
printf("Sunday");
;
:
printf("Weekend");
}
C Loops
Exercise 1:
Print i as long as i is less than 6.
int i = 1;
(i < 6) {
printf("%d\n", i);
;
}
Exercise 2:
Use the do/while loop to print i as long as i is less than 6.
int i = 1;
{
printf("%d\n", i);
;
}
(i < 6);
Exercise 3:
Use a for loop to print "Yes" 5 times:
(int i = 0; i < 5; ) {
printf("Yes\n");
}
Exercise 4:
Stop the loop if i is 5.
C Arrays
Exercise 1:
Create an array of type int called myNumbers.
Exercise 2:
Print the value of the second element in the myNumbers array.
Exercise 3:
Change the value of the first element to 33:
int myNumbers[] = {25, 50, 75, 100};
;
Exercise 4:
Loop through the elements in the array using a for loop.
(i = 0; i < 4; i++) {
printf("%d\n", );
}
C String
Exercise 1:
Fill in the missing part to create a "string" named greetings, and assign it the
value "Hello".
= ;
Exercise 2:
Another way of creating strings:
Fill in the missing part to create a "string" named greetings, and assign it the
value "Hi".
Exercise 3:
Use the correct format specifier to output the string:
Exercise 4:
Print the first character in the greetings string:
C Pointers
Create a pointer variable called ptr, that points to the int variable myAge:
int myAge = 43;
= &myAge;
C Functions
Exercise 1:
Create a method named myFunction and call it inside main().
void () {
printf("I just got executed!");
}
int main() {
return 0;
}
Exercise 2:
Insert the missing parts to call myFunction two times.
void myFunction() {
printf("I just got executed!");
}
int main() {
return 0;
}
Exercise 3:
Add a name parameter of type char (string) to myFunction.
void myFunction( ) {
printf("Hello %s\n", name);
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
Exercise 4:
Insert the missing part to print the number 8 in main, by using a
specific keyword inside myFunction:
int myFunction(int x) {
5 + x;
}
int main() {
printf("%d", myFunction(3));
return 0;
}
C Structures
Exercise 1:
Fill in the missing part to create a Car structure:
Car {
char brand[50];
char model[50];
int year;
};
Exercise 2:
Fill in the missing parts to create a struct variable of "Car" named "car1"
inside main:
struct Car {
char brand[50];
char model[50];
int year;
};
int main() {
struct ;
return 0;
}
Exercise 3:
Fill in the missing parts to assign the following values to the car1 variable:
struct Car {
char brand[50];
char model[50];
int year;
};
int main() {
struct Car car1 = { , , };
return 0;
}
C++ Introduction
What is C++?
C++ is a cross-platform language that can be used to create high-performance
applications.
C++ gives programmers a high level of control over system resources and
memory.
The language was updated 4 major times in 2011, 2014, 2017, and 2020 to C+
+11, C++14, C++17, C++20.
C++ can be found in today's operating systems, Graphical User Interfaces, and
embedded systems.
C++ is portable and can be used to develop applications that can be adapted to
multiple platforms.
The main difference between C and C++ is that C++ support classes and
objects, while C does not.
There are many text editors and compilers to choose from. In this tutorial, we
will use an IDE (see below).
Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all
free, and they can be used to both edit and debug C++ code.
Note: Web-based IDE's can work as well, but functionality is
limited.
C++ Quickstart
Let's create our first C++ file.
Write the following C++ code and save the file as myfirstprogram.cpp (File >
Save File as):
myfirstprogram.cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Don't worry if you don't understand the code above - we will discuss it in detail
in later chapters. For now, focus on how to run the code.
Then, go to Build > Build and Run to run (execute) the program. The result
will look something to this:
Hello World!
Process returned 0 (0x0) execution time : 0.011 s
Press any key to continue.
Congratulations! You have now written and executed your first
C++ program.
Code:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Result:
Hello World!
C++ Syntax
Let's break up the following code to understand it better:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Example explained
Line 1: #include <iostream> is a header file library that lets us work with input
and output objects, such as cout (used in line 5). Header files add functionality
to C++ programs.
Line 2: using namespace std means that we can use names for objects and
variables from the standard library.
Line 3: A blank line. C++ ignores white space. But we use it to make the code
more readable.
Line 4: Another thing that always appear in a C++ program, is int main(). This
is called a function. Any code inside its curly brackets {} will be executed.
Line 7: Do not forget to add the closing curly bracket } to actually end the main
function.
C++ Output (Print Text)
The cout object, together with the << operator, is used to output values/print
text:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
You can add as many cout objects as you want. However, note that it does not
insert a new line at the end of the output:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
cout << "I am learning C++";
return 0;
}
Result
C++ Topics
1. C++ Comments
2. C++ Variables
3. C++ User Input
4. C++ Data Type ( Boolean data Type, Character,Strings)
5. C++ Operators ( Arithmetic, Assignment, Comparison, Logical)
6. C++ String ( String Concatenation, Numbers & String,String Lenth,
Access String, Special Characters, User Inputs,
7. C++ Maths
8. C++ Booleans
9. C++ Conditions If Statements
10. C++ Swith
11. While Loop
12. C++ Loop ( Do/While Loop,
13. C++ Break and Continue
14. C++ Array
15. C++Structures
16. C++ Functions
17. C++ OPPS
C++ OOP
OOP stands for Object-Oriented Programming.
Look at the following illustration to see the difference between class and
objects:
Class
Fruit
Objects
Apple
Banana
Mango
Another example:
Class
Bike
Objects
TVS
BAJAJ
HONDA
When the individual objects are created, they inherit all the variables and
functions from the class.
You will learn much more about classes and objects in the next chapter.
C++ Classes/Objects
C++ Classes/Objects
C++ is an object-oriented programming language.
Everything in C++ is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and
brake.
A class is a user-defined data type that we can use in our program, and it works
as an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the class keyword:
Example
Create a class called "MyClass":
Example explained
The class keyword is used to create a class called MyClass.
The public keyword is an access specifier, which specifies that
members (attributes and methods) of the class are accessible from
outside the class. You will learn more about access specifiers later.
Inside the class, there is an integer variable myNum and a string
variable myString. When variables are declared within a class, they are
called attributes.
At last, end the class definition with a semicolon ;.
Create an Object
In C++, an object is created from a class. We have already created the class
named MyClass, so now we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object
name.
To access the class attributes (myNum and myString), use the dot syntax (.) on the
object:
Example
Create an object called "myObj" and access the attributes:
int main() {
MyClass myObj; // Create an object of MyClass