Introduction to C
Introduction to C
Basic concepts :
Introducing C:
C has been used to write everything from operating systems (including Windows and
many others) to complex programs like Python interpreter, Git, Oracle database, and
more.
Output :
Most computer programs are designed to produce outputs. Here some examples:
- “You’ve got a new message” notifications.
- “Game over” displayed on the screen when playing video games.
- Your account balance when checking your online banking app.
The simplest output consists of displaying a message on the screen.
printf(“Hello’);
Lesson Takeaways :
Important points:
1. You can write code that generates outputs with the printf function.
2. printf needs to include the text that you want to output inside parentheses.
3. A line of code is called a statement. A statement performs a specific task.
4. Each statement in C needs to end with a semicolon (;).
5. Text needs to be enclosed in double quotes.
Program Structure :
The first line of the code adds the <stdio.h> header file to the program.
#include <sdio.h>
A header is a file that contains functions and commands.
The <stdio.h> header contains the printf function, that we used for outputting text. This
is why we need to include it in our program, to enable us to use the printf function.
[N.B: The #include command is used to add a header file to the program. # This
symbol is necessary.]
Each C program has an entry point, or starting point, which is a function called main.
Curly brackets {} indicates the beginning and the end of a function, which can also be
called the function’s body. The code inside the brackets indicates what the function
does when executed.
int main() {
printf(“Hello’);
return 0;
}
When we run the code, the printf command will be executed, as it's inside the main()
function.
The main() function can contain a lot of statements, doing different things.
As a example:
#include <stdio.h>
int main() {
printf(“First”);
printf(“Second”);
return 0;
}
Lesson Takeaways :
Important points:
1. The #include statement is used to add a header file to the program.
2. To use the printf command, you need to include the <stdio.h> header.
3. The starting point of C programs is the function called main, which includes the
code that you want to run inside curly brackets.
4. The last statement of the main() function is return 0; , which indicates the
successful completion of the program.
Output Formatting :
Numbers :
The printf function supports special format specifiers, which allow output numbers and
output formatting.
printf(“%d”, 253);
%d is the format specifier, which denotes that a whole number is expected. The value of
the number is given after a comma in printf .
printf(“%f”, 3.14);
printf(“%c”, ‘X’);
Single characters need to be enclosed in single quotes, while strings use double
quotes.
A great feature of the format specifiers is that you can use a combination of multiple
specifiers and text in the printf() function. Example:
printf(“Score: %f. Level: %d”,42.8,4);
printf() does not add a new life after output. This means that when you use multiple
printf() statements, they will get printed on the same line.
The special character \n is used to create a new line in the output. You can use as many
\n characters as you need.
Lesson Takeaways :
Important points :
1. You can use format specifiers in printf(), to insert different values in the given
positions.
Variables :
Every program works with values.
A variable lets you store a value by assigning it to a name. The name can be used to
refer to the value later in the program.
Every variable has a type, which defines the type of the value it holds. A variable can
hold a text value, a number, a decimal, etc.
int score;
int is the type that stores whole numbers, or as we call them in programming integers.
After declaring our variable, we can assign it a value using the assignment = operator.
int score;
score = 253;
Now, the score holds the value 253.
Now, after declaring and assigning a value, we can output the value of our variable
#include <stdio.h>
int main() {
int score;
score = 253;
printf(“%d”, score);
return 0;
}
We used the %d format specifier, as score is an integer, and passed score to the printf
function as the value to be inserted.
We can combine the declaration and assignment into one statement, like this:
#include <stdio.h>
int main() {
int score = 253;
printf(“%d”, score);
return 0;
}
This is handy when we already know the value for our variable and makes it shorter and
more readable.
A variable can change its value during the program multiple times. For example, the
score can change during a game.
Lesson Takeaways :
Important points:
Data Types :
Variables need to have their data type, which defines the type of the value they store.
We have seen the int data type in the previous examples, used to store whole
numbers.
#include <stdio.h>
int main() {
int score = 253;
printf(“Score: %d”, score);
return 0;
}
Decimals :
To store decimals (or floating point numbers), C provides the float and double data
types.
#include <stdio.h>
int main() {
float height = 61.5;
printf(“%f”,height);
return 0;
}
[The format specifier for floats is %f ]
#include <stdio.h>
int main() {
double temp = 61.5;
printf(“%lf”,height);
return 0;
}
Char :
The char type is used to store a single character. It is similar to declaring a string, but
uses single quotes for the value.
#include <stdio.h>
int main() {
char letter = ‘X’;
printf(“%c”,letter);
return 0;
}
Constants :
Variables can be defined as constants. This means that they cannot be changed. To
define a constant, use the const keyword before the data type of the variable.
# include <stdio.h>
int main() {
const int num = 32;
printf(“%d”, num);
return 0;
}
Doing Math :
You can use arithmetic operators to perform calculations.
# include <stdio.h>
int main() {
int x = 3;
int y = 6;
printf(“%d”, x+y);
return 0;
}
# include <stdio.h>
int main() {
int win = 6;
int lost = 3;
int score = win-lost;
printf(“%d”, score);
return 0;
}
Multiplication :
Multiplication is done using the * operator.
#include <stdio.h>
int main()
{
int width = 62;
int height = 53;
int area = width*height;
printf("%d", area);
return 0;
}
Division :
The division / operator performs differently depending on the data type of the operand.
When both operands are integers, integer division, (also called truncated division),
removes any remainder resulting in an integer.
#include <stdio.h>
int main()
{
int kb = 35265;
int mb = kb/5356;
printf("%d", mb);
return 0;
}
In case we want a more precise result, we can use float division.
float kb = 35265;
float mb = kb/5356;
printf("%f", mb);
Remainder :
The % remainder operator (also called the modulo) is used to find the remainder of a
division. Let’s find out how many of 100 items will be left over if we divide them into
boxes of 8.
#include <stdio.h>
int main()
{
int items = 100;
int per_box = 8;
int left_over = items%per_box;
printf("%d", left_over);
return 0;
}
Lesson Takeaways :
Important points :
1. + is addition
2. - is subtraction
3. / is division
4. Dividing integers results in an integer, while dividing floats results in a float.
5. % finds the remainder of a division.
Comments :
Comments are annotations in the code that explain what the code is doing. Code is for
computers, while comments are for humans who read and work with the code.
A single-line comment starts with two forward slashes and continues until it reaches
the end of the line. Example:
int main() {
// storing the age
int age = 43; // some demo value
printf(“%d”, age);
Adding comments as you write code is good practice, because they provide clarification
and understanding when you need to refer back to it, as well as for others who might
need to read it.
You can also comment out lines of code, in case they work in progress or you don’t
want to delete them yet.
int main() {
int age = 43;
//age = 9;
printf(“%d”, age);
//printf(“Some demo program”);
The commented lines of code will get ignored when you run the program.
If you need to comment out multiple lines, or write a long, multi-line comment, you can
use the /**/ symbols.
int main() {
/* this is just a
demo program
that outputs a demo value */
int age = 12;
Anything between the /* and */ symbols becomes a comment.
Lesson Takeaways :
Important points :
1. Comments are explanatory statements that explain what the code is doing.
2. They can contain notes, todos as well as code that is work-in-progress.
3. // starts a single line comment.
4. /* */ is used for multi-line comments.
Taking Input:
Your programs may take user input. For example, these can be commands in a game,
or values for an app to process and generate the output.
The scanf() function is used to take user input based on the given format specifier. It
works similar to the printf() function.
#include <stdlib.h>
int main()
{
int num;
scanf("%d", &num);
We first declare the variable that will hold our input value. Then we use it in the scanf()
function.
[ The & sign before the variable name is the address operator. It gives
the address, or location in memory, of a variable. The scanf() function needs to use the
variable name with the & sign. ]
Multiple Inputs:
You can take multiple inputs throughout your program. For example let’s take two
integers as input and output their sum.
int x, y;
scanf(“%d%d”, &x, &y);
printf(“%d”, x+y);
Variables:
Also note how we declare the variables:
int x, y;
In case the variables have the same type, you can declare them on a single line, by
separating them with commas.
Lesson Takeaways :
Important points :
1. First, declare a variable that will store the input. Then, use it in the scanf()
function. scanf() is similar to printf() it uses a format specifier to prompt the user
for the corresponding input.
2. Remember, you need to use the & sign before the variable name in the scanf()
function - it is used to get the address of the variable, which tells scanf() where
to store the given value.
3. It is important to use the correct type for the variable that will store the input.
Conditionals:
Decision Making:
The if statement allows you to run a specified code if a given condition holds.
if(condition) {
//code to run
}
[ The condition is enclosed in parentheses, and code of the if statement is enclosed in
curly bracket {} ]
If Statement:
The following comparison operators may be used to form the condition:
Remember that you need to use two equal signs (==) to test for equality, since a single
equal sign is the assignment operator.
int position = 1;
if(position == 1) {
printf("Gold!");
}
Else Statement:
You can use the else statement after an if statement, if you want to run a code in case
the condition is not satisfied.
#include <stdlib.h>
int main() {
int score = 56;
if(score >= 100) {
printf("Completed!");
}
else {
printf("Game Over");
}
return 0;
}
else if Statement:
In case you need to check for multiple different values, you can use else if statements.
Lesson Takeaways :
Now you know how to make decisions in your program.
You can check for a condition using the if statement.
In case the condition does not hold, the code in an else statement can be executed.
Switch:
The switch statement can be used to check for equality against a list of values, instead
of multiple else if statements.
int main() {
int position = 6;
switch(position) {
case 1:
printf("Gold");
break;
case 2:
printf("Silver");
break;
case 3:
printf("Bronze");
break;
default:
printf("No medal");
break;
}
return 0;
}
Each case has a value to compare with. When the switch variable’s value is equal to a
case value, the code inside it is executed, until a break statement is reached. Each
case has to have a value and a colon.
The break statement is used to terminate the switch, when the case it matched.
If you forget to add the break after each case, the program will continue to execute the
code in the next case statements, even if their value does not match the variable’s
value.
switch(position) {
case 1:
printf("Gold");
case 2:
printf("Silver");
case 3:
printf("Bronze");
default:
printf("No medal");
}
This type of behaviour is called fall-through. It usually occurs due to errors, when the
programmer forgets to add the break statements for each case.
There is a default case at the end of the switch statement. It is used to run code, when
none of the cases match.
No break is needed in the default case as it is always the last statement in the switch.
Lesson Takeaways:
The switch statement is a handy way to check for multiple values.
Combining Conditions:
In some scenarios we need to combine multiple conditions. Let’s say we want to check
that the age value is between 18 and 45.
int main() {
int age = 24;
if(age >= 18 && age <= 45) {
printf("ok");
}
return 0;
}
The && operator is also referred to as the logical AND operator.
OR:
The logical OR operator, written as || combines conditions. The code will run if any one
of the conditions is satisfied. For example:
int balance = 24;
int level = 5;
if(balance > 1000 || level > 3) {
printf("Gold Tier");
}
NOT:
The logical NOT operator ! reverses the condition.
You can chain multiple conditions using parentheses and the logical operators.
Example:
Lesson Takeaways:
Logical operators allow you to combine multiple conditions.
Loops:
A Loop allows you to repeat a block of code multiple times. For example, a banking app
can loop through all transactions, or a shopping app can loop through all products in the
shopping cart to calculate the total.
while Loop:
The while loop takes a condition and repeats its statement while the condition is
satisfied.
int num = 1;
printf("%d\n",num);
num = num + 1;
The statement num = num + 1 increases the value of num by 1 each time the loops
run. This is important, as without it the loop would run forever. The loop stops as soon
as the value of num reaches the value 5.
printf("%d\n",num);
num++;
do{
printf("%d\n",x);
x +=3;
The difference with a while loop is that condition is checked after the code, meaning
the in the do is executed at least once, even if the condition is not satisfied. Also note
the semicolon after the while condition.
Lesson Takeaways
Here is a summary about the while loop:
1. The code in the while loop runs as long as the condition holds.
2. The ++ and -- operators are used to increase and decrease the value of
a variable by one.
3. C provides shorthand operators to perform mathematical operations on a
variable, for example num=num * 5 can be written as num *= 5.
4. The do-while loop is similar to a while loop, but it is guaranteed to run at
least once.
for loops:
Another loop structure is the for loop. It has the following form.
int main() {
printf("%d\n",i);
return 0;
1. The first part runs once when we enter the loop and initializes the variable.
2. The second part is the condition of the loop.
3. The third part runs every time the loop runs.
printf("%d\n",i);
Remember the break; statement that was used in switch to stop it when a case was
matched. It can also be used to stop a loop.
if(i==5){
break;
printf("%d",i);
continue:
The continue statement skips the current loop iteration and continues with the next
one.
if(i==5){
continue;
printf("%d\n",i);
This will skip the number 5 but will run until i reaches 10.
Lesson Takeaways:
Here is a summary:
Arrays:
Variables are great for storing and working with values. But what if we need to store
multiple similar values? For example, ages of a group of people. Instead of creating
separate variables for each person, we can use an array to store all values!
An array needs to be declared like a variable, with the type of the items it will hold.
int ages[7];
The name of the array is ages. It is created to hold 7 int values. Note the square
brackets [ ] after the name of the array.
int ages[7];
ages[2]=24;
ages[0]=31;
printf("%d", ages[2]);
return 0;
After declaring the array, we can access the items using their position, also called the
index.
The last item of the ages array will have the index 6, as it can hold 7 items.
int ages[7];
ages[2]=24;
ages[0]=31;
printf("%d", ages[2]);
return 0;
This will output the value of the 3rd item, as we used the 2nd index. Also make sure to
use the correct format specifier, when outputting values.
If u already know what values to store in the array, instead of assigning them one by
one, you can use the following syntax:
int ages[]={31,18,24,55,29};
printf("%d", ages[2]);
return 0;
Place the values in a comma-separated list, enclosed in curly braces. The code
above automatically creates an array containing 5 items, and stores the provided
values.
Note that in this case we do not need to specify the size of the array in the square
brackets.
Lesson Takeaways:
Arrays allow to store multiple values in a single variable.
To create an array, specify the item type and array size:
int cart[12];
Array items are accessed by their indexes in square brackets. The first item has the
index 0.
You can also initialize an array with values using this syntax:
int ages[]={31,18,24,55,29};
int i;
for(i=0; i<5; i++){
printf("%d\n", ages[i]);
}
return 0;
We used the i variable of the loop as the index for our array. During each iteration of the
loop it is incremented and used to access the corresponding item of the array.
Note that we need to set the condition based on the size of the array,in out case there
are 5 elements so we used the condition i<5 in the loop, as i start from 0.