C Programming
C Programming
Muzzamil Arain 1
Problem Solving
How do humans solve problems?
•algorithm
Muzzamil Arain 2
Programming computers
Computers are dumb but they can do exactly what they are told to do
computers. Think of it as a language that computers can understand. Just like English or Spanish, programming
"One can't learn to play the piano in a few days, and one can't learn to program in a few days either." - Bjarne
Muzzamil Arain 3
Who created the First
Programming
Language?
the first programming language was created by Ada
pure calculation.
Muzzamil Arain 4
Interaction with Hardware
How High-Level Code Becomes Machine Code:
Compilation: The process of converting high-level code into machine code using a compiler (e.g., C, C++ are
compiled languages).
Interpretation: The process of executing high-level code line-by-line using an interpreter (e.g., Python,
Muzzamil Arain 5
Types of Programming Languages
• Low-Level Languages:
• Examples:
• Assembly Language: Uses simple instructions like MOV, ADD that are closer to machine code.
• High-Level Languages:
• Examples:
Muzzamil Arain 6
Program Execution Flow
• Source Code: You write a program using a high-level language.
• Execution: The CPU runs the machine code, and the program works.
• Career Growth: Programming is essential in many fields (IT, Data Science, AI, Cybersecurity)
Muzzamil Arain 7
Some Famous Programming Languages and Their Uses
OS development
systems
development
Python Web development, data analysis, AI, Easy syntax, versatile, interpreted
scripting
databases
enterprise apps
Muzzamil Arain 8
Introduction to C
C is a general-purpose programming language
1972.
science.
Why Learn C?
• It is one of the most popular programming
Muzzamil Arain 9
Features of C
Feature Description
Rich Library Support Offers built-in libraries for common operations like I/O, math, etc.
Muzzamil Arain 10
Uses of C Programming
• Operating Systems:
• Embedded Systems:
• Game Development:
• Compiler Development:
• Database Systems:
Muzzamil Arain 11
Get Started With C
To start using C, you need two things:
• A compiler, like GCC, to translate the C code into a language that the computer will understand
There are many text editors and compilers to choose from. In this tutorial, we will use an IDE .
C Install IDE
An IDE (Integrated Development Environment) is used to edit AND compile the code.
Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free, and they can be used to both edit
We will use Code::Blocks in our tutorial, which we believe is a good place to start.
You can find the latest version of Codeblocks at http://www.codeblocks.org/ . Download the mingw-setup.exe file,
which will install the text editor with a compiler.
Muzzamil Arain 12
Writing our First Program
Let's create our first C file.
Write the following C code and save the file as myfirstprogram.c ( File > Save File as ):
int main() {
printf("Hello World");
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.
Muzzamil Arain 13
Syntax
You have already seen the following code. Let's break it down to understand it better:
Example
#include <stdio.h>
int main() {
printf("Hello World!");
Example explained
Line 1: #include <stdio.h> is a header file library that lets us work with input and output functions, such as
Don't worry if you don't understand how #include <stdio.h> works. Just think of it as something that (almost)
always appears in your program.
Muzzamil Arain 14
Syntax
Line 2: A blank line. C ignores white space. But we use it to make the code more readable.
Line 3: Another thing that always appear in a C program is main(). This is called a function . Any code inside its
Line 4: printf() is a function used to output /print text to the screen. In our example, it will output "Hello World!".
Muzzamil Arain 15
Exercise
Insert the missing part of the code below to output "Hello World!".
int ____() {
______("Hello World!");
return 0;
}
Muzzamil Arain 16
Statements
A computer program is a list of "instructions" to be "executed" by a computer.
The following statement "instructs" the compiler to print the text "Hello World" to the screen:
Example
printf("Hello World!");
If you forget the semicolon ( ;), an error will occur and the program will not run:
Example
printf("Hello World!")
Many Statements
Most C programs contain many statements.
The statements are executed, one by one, in the same order as they are written:
Example
printf("Hello World!");
Muzzamil Arain 17
New Lines
To insert a new line, you can use the \n character:
Example
#include <stdio.h>
int main() {
return 0;
You can also output multiple lines with a single printf() function. However, this could make the code harder to
read:
Muzzamil Arain 18
Comments in C
Comments can be used to explain code, and to make it more readable. It can also be used to prevent execution
Single-line Comments
Single-line comments start with two forward slashes ( //).
Any text between // and the end of the line is ignored by the compiler (will not be executed).
Example
// This is a comment
printf("Hello World!");
Example
printf("Hello World!"); // This is a comment
Muzzamil Arain 19
Comments in C
Comments can be used to explain code, and to make it more readable. It can also be used to prevent execution
C Multi-line Comments
Multi-line comments start with /* and ends with */.
Example
/* The code below will print the words Hello World!
printf("Hello World!");
Good to know: Before version C99 (released in 1999), you could only use multi-line comments in C.
Muzzamil Arain 20
C Variables
Variables are containers for storing data values, like numbers and characters.
In C, there are different types of variables (defined with different keywords), for example:
• int - stores integers (whole numbers), without decimals, such as 123 or -123
• float - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Characters are surrounded by single quotes
Syntax
type variableName = value;
Where type is one of C types (such as int), and variableName is the name of the variable (such as x or myName ).
Muzzamil Arain 21
C Variables
So, to create a variable that should store a number , look at the following example:
Example
Create a variable called myNum of type int and assign the value 15 to it:
You can also declare a variable without assigning the value, and assign the value later:
Example
// Declare a variable
int myNum;
myNum = 15;
Muzzamil Arain 22
C Variables
In many other programming languages (like Python , Java , and C++ ), you would normally use a print function to
Example
int myNum = 15;
To output variables in C, you must get familiar with something called " format specifiers ", which you will learn about
Muzzamil Arain 23
Basic Data Types
The data type specifies the size and type of information the variable will store.
float 4 bytes Stores fractional numbers, containing one or more decimals. 1.99
double 8 bytes Stores fractional numbers, containing one or more decimals. 1.99
Muzzamil Arain 24
Data Types
As explained in the Variables slide, a variable in C must be a specified data type , and you must use a format
Example
// Create variables
// Print variables
printf("%d\n", myNum);
printf("%c\n", myLetter);
Muzzamil Arain 25
Format Specifiers
Format specifiers are used together with the printf() function to tell the compiler what type of data the variable
is storing. It is basically a placeholder for the variable value.
For example, to output the value of an int variable, use the format specifier %d surrounded by double quotes (""),
inside the printf() function:
Example
int myNum = 15;
Muzzamil Arain 26
Format Specifiers
To print different types in a single printf() function, you can use the following:
Example
int myNum = 15;
Example
printf("My favorite number is: %d", 15);
However , it is more sustainable to use variables as they are saved for later and can be re-used whenever.
Muzzamil Arain 27
Format Specifiers
To print other types, use %c for char and %f for float:
Example
// Create variables
// Print variables
printf("%d\n", myNum);
printf("%c\n", myLetter);
To combine both text and a variable, separate them with a comma inside the printf() function:
Example
int myNum = 15;
Muzzamil Arain 28
Basic Format Specifiers
There are different format specifiers for each data type. Here are some of them:
%d or %i int
%f or %F float
%1f double
%c char
%s string
Muzzamil Arain 29
Change Variable Values
If you assign a new value to an existing variable, it will overwrite the previous value:
Example
int myNum = 15; // myNum is 15
Example
int myNum = 15;
myNum = myOtherNum;
printf("%d", myNum);
Muzzamil Arain 30
The char Type
The char data type is used to store a single character.
The character must be surrounded by single quotes, like 'A' or 'c', and we use the %c format specifier to print it:
Example
char myGrade = 'A';
printf("%c", myGrade);
Alternatively, if you are familiar with ASCII, you can use ASCII values to display certain characters. Note that these
Example
char a = 65, b = 66, c = 67;
printf("%c", a);
printf("%c", b);
printf("%c", c);
Notes on Characters
If you try to store more than a single character, it will only print the last character:
Muzzamil Arain 31
Get the Memory Size
We introduced in the data types chapter that the memory size of a variable varies depending on the type:
The memory size refers to how much space a type occupies in the computer's memory.
To actually get the size (in bytes) of a data type or variable, use the sizeof operator:
Example
int myInt;
float myFloat;
double myDouble;
char myChar;
printf("%lu\n", sizeof(myInt));
printf("%lu\n", sizeof(myFloat));
printf("%lu\n", sizeof(myDouble));
printf("%lu\n", sizeof(myChar));
Note that we use the %lu format specifer to print the result, instead of %d. It is because the compiler expects the
sizeof operator to return a long unsigned int (%lu), instead of int (%d). On some computers it might work with
%d, but it is safer to use %lu.
performance.
For example, the size of a char type is 1 byte. Which means if you have an array of 1000 char values, it will occupy
1000 bytes (1 KB) of memory.
Using the right data type for the right purpose will save memory and improve the performance of your program.
Muzzamil Arain 32
Constants
If you don't want others (or yourself ) to change existing variable values, you can 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
You should always declare the variable as constant when you have values that are unlikely to change:
Example
const int minutesPerHour = 60;
Notes On Constants
When you declare a constant variable, it must be assigned with a value:
Example
Like this:
Muzzamil Arain 33
Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
int myNum = 100 + 50;
Although the + operator is often used to add together two values, like in the example above, it can also be used to
add together a variable and a value, or a variable and another variable:
Example
int sum1 = 100 + 50; // 150 (100 + 50)
Muzzamil Arain 34
Operators
C divides the operators into the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
Muzzamil Arain 35
Operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Muzzamil Arain 36
Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator ( =) to assign the value 10 to a variable called x :
Example
int x = 10;
Example
int x = 10;
x += 5;
Muzzamil Arain 37
Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in programming, because it
The return value of a comparison is either 1 or 0, which means true ( 1) or false ( 0). These values are known as
Boolean values , and you will learn more about them in the Booleans and If..Else topic.
In the following example, we use the greater than operator ( >) to find out if 5 is greater than 3:
Example
int x = 5;
int y = 3;
Muzzamil Arain 38
Comparison Operators
A list of all comparison operators:
> greater than x>y Returns 1 if the first value is greater than the second value
< less than x<y Returns 1 if the first value is less than the second value
>= greater than or x>=y Returns 1 if the first value is greater than, or equal to, the second
equal to value
<= less than or x<=y Returns 1 if the first value is less than, or equal to, the second value
equal to
Muzzamil Arain 39
Logical Operators
You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values, by combining multiple conditions:
&& AND x < 5 && x < 10 Returns 1 if both statements are true
! NOT !(x < 5 && x < 10) Reverse the result, returns 0 if the result is 1
Muzzamil Arain 40
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 take the values true or false:
Muzzamil Arain 41
Booleans
Before trying to print the boolean variables, you should know that boolean values are returned as integers :
• 0 represents false
Therefore, you must use the %d format specifier to print a boolean value:
Example
// Create boolean variables
Muzzamil Arain 42
Booleans
Comparing Values and Variables
Comparing values are useful in programming, because it helps us to find answers and make decisions.
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
From the example above, you can see that the return value is a boolean value ( 1).
Example
int x = 10;
int y = 9;
In the example below, we use the equal to ( ==) operator to compare different values:
Example
printf("%d", 10 10); // Returns 1 (true), because 10 is equal to 10
Muzzamil Arain 43
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;
Note: The memory address is in hexadecimal form (0x..). You will probably not get the same result in your program,
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.
Muzzamil Arain 44
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;
Muzzamil Arain 45
User Input
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
Muzzamil Arain 46
Operators Exercise
What will the following code output?
int x = 10;
x += 5;
printf("%d", x);
1. 10
2. 15
3. 5
4. An error
1. =
2. ==
3. !=
4. ||
Muzzamil Arain 47
Operators Exercise
Fill in the blanks to multiply 10 with 5, and print the result.
int x = 10;
int y = 5;
printf("___", x ___ y);
Use the addition assignment operator to add the value 5 to the variable x.
int x = 10;
x __ 5;
Muzzamil Arain 48
Operators Exercise
1. Write a program that inputs marks for 5 subjects and then calculate the total marks obtained and the average 2.
2. Write a program that inputs your age in years and then calculate the total number of months, weeks and days.
3. Write a C program to convert specified days into years, weeks and days.
4. Write a Program to find the size of int, float, double, and char.
Muzzamil Arain 49
Operators Exercise
1. Write a Program to Swap the values of two variables.
Muzzamil Arain 50
Conditional Statements
Conditional statements control the flow of a program by executing specific blocks of code based on certain
conditions.
• Traffic System
• Grading System
• Voting Eligibility
• Login Authentication
Muzzamil Arain 51
Conditional Statements
You have already learned that C supports the usual logical conditions from mathematics:
• Equal to a == b
You can use these conditions to perform different actions for different decisions.
Muzzamil Arain 52
Conditional Statements
C has the following conditional statements:
• Use else to specify a block of code to be executed, if the same condition is false
• Use else if to specify a new condition to test, if the first condition is false
Muzzamil Arain 53
Conditional Statements
The if Statement
Use the if statement to specify a block of code to be executed if a condition is true.
Syntax
if (condition) {
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) {
Muzzamil Arain 54
Conditional Statements
The else Statement
Use the else statement to specify a block of code to be executed if the condition is false.
Syntax
if (condition) {
} else {
Example
int time = 20;
printf("Good day.");
} else {
printf("Good evening.");
Muzzamil Arain 55
Conditional Statements
The else if Statement
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
} else if (condition2) {
} else {
Example
int time = 22;
printf("Good morning.");
printf("Good day.");
} else {
printf("Good evening.");
Muzzamil Arain 56
Conditional Statements
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;
printf("Good day.");
} else {
printf("Good evening.");
Example
int time = 20;
Muzzamil Arain 57
Conditional Statements
Real-Life Examples
This example shows how you can use if..else to "open a door" if the user enters the correct code:
Example
int doorCode = 1337;
if (doorCode == 1337) {
} else {
Muzzamil Arain 58
Conditional Statements
Real-Life Examples
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) {
} else {
Muzzamil Arain 59
Conditional Statements
Real-Life Examples
Find out if a person is old enough to vote:
Example
int myAge = 25;
} else {
Muzzamil Arain 60
Conditional Statements Exercise
Print "Hello World" if x is greater than y.
int x = 50;
int y = 10;
___(x__y) {
printf("Hello World");
}
Muzzamil Arain 61
Conditional Statements Exercise
Print "Yes" if x is equal to y, otherwise print "No".
int x = 50;
int y = 50;
___(x__y) {
printf("Yes");
}_____{
printf("No");
}
1. Good evening.
2. Good day.
3. No output
4. An error
Muzzamil Arain 62
Conditional Statements Exercise
What will the following code output?
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
1. Good day.
2. Good evening.
3. No output
4. An error
Muzzamil Arain 63
Conditional Statements Exercise
Which part of the code will execute if the condition in the if statement is false?
if (a > b) {
printf("a is greater");
} else {
printf("b is greater");
}
1. printf("a is greater");
2. printf("b is greater");
3. Both
4. Neither
Muzzamil Arain 64
Conditional Statements Exercise
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");
}
Muzzamil Arain 65
Conditional Statements Exercise
What will the following code output if time is 14?
int time = 14;
if (time < 10) {
printf("Good morning.");
} else if (time < 20) {
printf("Good day.");
} else {
printf("Good evening.");
}
1. Good morning.
2. Good day.
3. Good evening.
4. No output
Muzzamil Arain 66
Conditional Statements Exercise
1. Take three int values from user and print greatest among them.
2. A user inputs a number. The program determines whether the number is positive, negative or 0.
3. Take 5 input as marks for 5 subjects and calculate it’s percentage and also calculate grade based on
Muzzamil Arain 67
Loops in Programming
Loops or Iteration Statements in Programming are helpful when we need a specific task in repetition. They're
Loops are used when we need to execute a block of code repetitively . Loops in programming are control flow
structures that enable the repeated execution of a set of instructions or code block as long as a specified condition
is met.
1. Entry-Controlled loops:
In Entry controlled loops the test condition is checked before entering the main body of the loop. For Loop and
2. Exit-Controlled loops:
In Exit controlled loops the test condition is evaluated at the end of the loop body . The loop body will execute at
least once, irrespective of whether the condition is true or false. Do-while Loop is an example of Exit Controlled
loop.
Muzzamil Arain 68
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 (expression 1; expression 2; expression 3) {
Expression 1 is executed (one time) before the execution of the code block.
Expression 3 is executed (every time) after the code block has been executed.
Muzzamil Arain 69
For Loop
Example
int i;
printf("%d\n", i);
Example explained
Expression 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will
Expression 3 increases a value (i++) each time the code block in the loop has been executed.
Muzzamil Arain 70
For Loop Exercise
1. Write a C program to print * five times in a row using a for loop.
2. Write a C program to find the sum of the first 5 numbers (1 + 2 + 3 + 4 + 5) using a for loop.
4. Write a C program to print the first three even numbers (2, 4, 6) using a for loop.
5. Write a C program to print all even numbers between 1 and 20 using a for loop.
6. Write a C program to print the multiplication table of a given number (e.g., 5) using a for loop.
7. Write a C program to print all prime numbers between 1 and 50 using a for loop.
Muzzamil Arain 71
While Loop
The while loop loops through a block of code as long as a specified condition is true:
Syntax
while (condition) {
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++;
Note: Do not forget to increase the variable used in the condition ( i++), otherwise the loop will never end!
Muzzamil Arain 72
While Loop exercise
1. Write a C program to print "Hello, World!" five times using a while loop.
2. Write a C program to print all odd numbers between 1 and 9 using a while loop.
4. Write a C program to calculate the sum of the first 5 natural numbers (1 + 2 + 3 + 4 + 5) using a while loop.
6. Write a C program to print all numbers divisible by 5 from 1 to 50 using a while loop.
Muzzamil Arain 73
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if
the condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do {
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:
Example
int i = 0;
do {
printf("%d\n", i);
i++;
Muzzamil Arain 74
Break
The break statement can be used to jump out of a loop .
Example
int i;
if (i == 4) {
break;
printf("%d\n", i);
Muzzamil Arain 75
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;
if (i == 4) {
continue;
printf("%d\n", i);
Muzzamil Arain 76
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 [] .
To insert values to it, use a comma-separated list inside curly braces, and make sure all values are of the same
data type:
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
Muzzamil Arain 77
Arrays
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]);
Muzzamil Arain 78
Arrays
Loop Through an Array
You can loop through the array elements with the for loop.
Example
int myNumbers[] = {25, 50, 75, 100};
int i;
printf("%d\n", myNumbers[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;
Muzzamil Arain 79
Arrays
Avoid Mixing Data Types
It is important to note that all elements in an array must be of the same data type .
This means you cannot mix different types of values, like integers and floating point numbers, in the same array:
Example
int myArray[] = {25, 50, 75, 3.15, 5.99};
Muzzamil Arain 80
Strings
Strings are used for storing text /characters.
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);
Muzzamil Arain 81
Strings
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);
Muzzamil Arain 82
Strings
Loop Through a String
You can also loop through the characters of a string, using a for loop:
Example
char carName[] = "Volvo";
int i;
printf("%c\n", carName[i]);
Muzzamil Arain 83