C Programming - 1
C Programming - 1
Else
Conditions and If Statements
You have already learned that C supports the usual logical conditions from
mathematics:
You can use these conditions to perform different actions for different
decisions.
The if Statement
Use the if statement to specify a block of code to be executed if a condition
is true.
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. C is case sensitive.
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:
1
Example
if (20 > 18) {
printf("20 is greater than 18");
}
Note: To execute the given code (run the code on CodeBlocks API)
provided please add the following template:
#include<stdio.h>
int main()
{
// Add your code here (remember C is case sensitive)
return 0;
}
Example
#include<stdio.h>
int main()
{
// Add your code between braces
if (20 > 18) {
printf("20 is greater than 18");
}
return 0;
}
Example
int x = 20;
int y = 18;
if (x > y) {
printf("x is greater than y");
}
Example explained
In the example above we use two variables, x and y, to test whether x is
greater than y (using the > operator). As x is 20, and y is 18, and we know
that 20 is greater than 18, we print to the screen that "x is greater than y".
2
The else Statement
Use the else statement to specify a block of code to be executed if the
condition is false.
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.");
}
// Outputs "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".
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
}
3
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
In the example above, time (22) is greater than 10, so the first
condition is false. The next condition, in the else if statement, is
also false, so we move on to the else condition
since condition1 and condition2 are both false - and print to the screen
"Good evening".
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:
Example
int myNum = 10; // Is this a positive or negative number?
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.");
}
4
C Switch
Instead of writing many if..else statements, you can use
the switch statement.
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;
5
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
}
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.
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");
}
6
C While Loop
Loops
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make
code more readable.
While Loop
The while loop loops through a block of code as long as a specified condition
is true:
Syntax
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as
long as a variable (i) is less than 5:
Example
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
Syntax
do {
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be executed
at least once, even if the condition is false, because the code block is
executed before the condition is tested:
7
Example
int i = 0;
do {
printf("%d\n", i);
i++;
}
while (i < 5);
8
C For Loop
When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been
executed.
Example
int i;
Example explained
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5).
If the condition is true, the loop will start over again, if it is false, the loop will
end.
Statement 3 increases a value (i++) each time the code block in the loop
has been executed.
Another Example
This example will only print even values between 0 and 10:
Example
for (i = 0; i <= 10; i = i + 2) {
printf("%d\n", i);
}
9
Nested Loops
It is also possible to place a loop inside another loop. This is called a nested
loop.
The "inner loop" will be executed one time for each iteration of the "outer
loop":
Example
int i, j;
// Outer loop
for (i = 1; i <= 2; ++i) {
printf("Outer: %d\n", i); // Executes 2 times
// Inner loop
for (j = 1; j <= 3; ++j) {
printf(" Inner: %d\n", j); // Executes 6 times (2 * 3)
}
}
10
C Break and Continue
Break
You have already seen the break statement used. It was used to "jump out"
of a switch statement.
Example
int i;
Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
Example
int i;
11
Break Example
int i = 0;
Continue Example
int i = 0;
12
C 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 [].
Array indexes start with 0: [0] is the first element. [1] is the second element,
etc.
This statement accesses the value of the first element [0] in myNumbers:
Example
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);
// Outputs 25
Example
myNumbers[0] = 33;
Example
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
13
Loop Through an Array
You can loop through the array elements with the for loop.
Example
int myNumbers[] = {25, 50, 75, 100};
int i;
Example
// Declare an array of four integers:
int myNumbers[4];
// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;
Using this method, you should know the size of the array, in order for
the program to store enough memory.
C Multidimensional Arrays
Previously you learned about single dimension arrays. These are great,
and something you will use a lot while programming in C. However, if you
want to store data as a tabular form, like a table with rows and columns, you
need to get familiar with multidimensional arrays.
Arrays can have any number of dimensions. In this section, we will introduce
the most common; two-dimensional arrays (2D).
14
Two-Dimensional Arrays
A 2D array is also known as a matrix (a table of rows and columns).
Two-Dimensional Arrays
A 2D array is also known as a matrix (a table of rows and columns).
This statement accesses the value of the element in the first row
(0) and third column (2) of the matrix array.
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
The following example will change the value of the element in the first row
(0) and first column (0):
15
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%d\n", matrix[i][j]);
}
}
16
C Strings
Strings are used for storing text/characters.
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);
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]);
Note that we have to use the %c format specifier to print a single
character.
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!
17
Loop Through a String
You can also loop through the characters of a string, using a for loop:
Example
char carName[] = "Volvo";
int i;
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);
Differences
The difference between the two ways of creating strings, is that the first
method is easier to write, and you do not have to include the \0 character,
as C will do it for you.
You should note that the size of both arrays is the same: They both have 13
characters (space also counts as a character by the way), including
the \0 character:
Example
char greetings[] = {'H', 'e', 'l', 'l', 'o', '
', 'W', 'o', 'r', 'l', 'd', '!', '\0'};
char greetings2[] = "Hello World!";
18
C User Input
You have already learned that printf() is used to output values in C.
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);
19
Take String Input
You can also get a string entered by the user:
Example
Output the name of a user:
// Create a string
char firstName[30];
Example
char fullName[30];
From the example above, you would expect the program to print "John Doe",
but it only prints "John".
That's why, when working with strings, we often use the fgets() function
to read a line of text. Note that you must include the following arguments:
the name of the string variable, sizeof(string_name), and stdin:
Example
char fullName[30];
20
printf("Type your full name: \n");
fgets(fullName, sizeof(fullName), stdin);
21
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.
22
C Pointers
Creating Pointers
Previously we learned that we can get the memory address of a variable
with the reference operator &:
Example
int myAge = 43; // an int variable
A pointer variable points to a data type (like int) of the same type, and
is created with the * operator.
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
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.
23
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:
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.
24