0% found this document useful (0 votes)
6 views

C Programming

The document provides an introduction to C programming, covering problem-solving approaches, the nature of programming languages, and the history of programming. It explains the process of compiling and interpreting code, types of programming languages, and the features and uses of C. Additionally, it includes practical examples and exercises for writing and understanding basic C code, including variables, data types, and format specifiers.

Uploaded by

Ali Muzzammil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

C Programming

The document provides an introduction to C programming, covering problem-solving approaches, the nature of programming languages, and the history of programming. It explains the process of compiling and interpreting code, types of programming languages, and the features and uses of C. Additionally, it includes practical examples and exercises for writing and understanding basic C code, including variables, data types, and format specifiers.

Uploaded by

Ali Muzzammil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

C Programming

By Muzzamil Arain (BS Cyber Security QUEST)

Muzzamil Arain 1
Problem Solving
How do humans solve problems?

•Hit and trial

•Learn from examples

•algorithm

What about computers?

•Obey / execute the commands given

How can we (humans) communicate with the machine (computer)?

Muzzamil Arain 2
Programming computers
Computers are dumb but they can do exactly what they are told to do

Giving instructions to a computer to perform a task is what we call “programming”

These set of instructions are called a “computer program”

This capability of computers is what makes them so powerful

What is a Programming Language?


A programming language is a set of rules and syntax that allows humans to communicate instructions to

computers. Think of it as a language that computers can understand. Just like English or Spanish, programming

languages have their own vocabulary and grammar.

"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

Stroustrup, Creator of C++.

Muzzamil Arain 3
Who created the First
Programming
Language?
the first programming language was created by Ada

Lovelace, one of the earliest female mathematicians.

Augusta Ada King, Countess of Lovelace, also known

as Ada Lovelace, was an English mathematician and

writer chiefly known for her work on Charles

Babbage's proposed mechanical general-purpose

computer, the Analytical Engine. She was the first to

recognise that the machine had applications beyond

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,

JavaScript are interpreted languages).

Muzzamil Arain 5
Types of Programming Languages
• Low-Level Languages:

• Close to machine language, which computers understand directly.

• Examples:

• Machine Language (Binary): Uses only 0s and 1s.

• Assembly Language: Uses simple instructions like MOV, ADD that are closer to machine code.

• Use Case: System programming or hardware-level programming.

• High-Level Languages:

• Easier to read, write, and understand. They use English-like syntax.

• Examples:

• C, C++, Java, Python, JavaScript.

• Use Case: Application development, web development, and software solutions.

Muzzamil Arain 6
Program Execution Flow
• Source Code: You write a program using a high-level language.

• Compilation: A compiler translates your code into machine-readable language.

• Execution: The CPU runs the machine code, and the program works.

Why Learn Programming Languages?


• Problem-Solving: Automates tasks and solves problems efficiently.

• Build Software: Creates applications, games, websites, and tools.

• Control Hardware: Programs devices like robots, machines, or microcontrollers.

• Career Growth: Programming is essential in many fields (IT, Data Science, AI, Cybersecurity)

Muzzamil Arain 7
Some Famous Programming Languages and Their Uses

Programming Language Primary uses Key Features

C System programming, embedded systems, Fast, low-level, procedural, portable

OS development

C++ Software development, games, real-time Object-oriented, fast, powerful

systems

Java Cross-platform applications, Android Platform-independent, OOP-based

development

Python Web development, data analysis, AI, Easy syntax, versatile, interpreted

scripting

JavaScript Web development (front-end and back-end) Lightweight, interpreted, event-driven

SQL Database management, querying data Declarative, query language for

databases

C# Desktop applications, games (Unity), .NET framework, object-oriented

enterprise apps

Muzzamil Arain 8
Introduction to C
C is a general-purpose programming language

created by Dennis Ritchie at the Bell Laboratories in

1972.

It is a very popular language, despite being old. The

main reason for its popularity is because it is a

fundamental language in the field of computer

science.

C is strongly associated with UNIX, as it was

developed to write the UNIX operating system.

Why Learn C?
• It is one of the most popular programming

languages in the world

• If you know C, you will have no problem learning

other popular programming languages such as

Java, Python, C++, C#, etc, as the syntax is similar

• C is very fast, compared to other programming

languages, like Java and Python

• C is very versatile; it can be used in both

applications and technologies

"While other languages may come and go, C will

remain a fundamental part of the computing

landscape." - Dennis Ritchie

Muzzamil Arain 9
Features of C
Feature Description

Procedural Language Follows step-by-step instructions (functions and procedures).

Low-Level Access Direct interaction with hardware (e.g., memory management).

Portable Can be compiled and executed on different platforms.

Rich Library Support Offers built-in libraries for common operations like I/O, math, etc.

Muzzamil Arain 10
Uses of C Programming
• Operating Systems:

• UNIX, Linux, and parts of Windows are built using C.

• Embedded Systems:

• Microcontrollers and hardware devices use C for direct hardware interaction.

• Game Development:

• Game engines require fast execution, making C suitable.

• Compiler Development:

• C is used to create compilers for other programming languages.

• Database Systems:

• Databases like MySQL are implemented in C.

Muzzamil Arain 11
Get Started With C
To start using C, you need two things:

• A text editor, like Notepad, to write C code

• 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

and debug C code.

Note: Web-based IDE's can work as well, but functionality is limited.

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.

Open Codeblocks and go to File > New > Empty File .

Write the following C code and save the file as myfirstprogram.c ( File > Save File as ):

Basic Structure of a C Program


#include <stdio.h>

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

printf() (used in line 4). Header files add functionality to C programs.

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

curly brackets {} will be executed.

Line 4: printf() is a function used to output /print text to the screen. In our example, it will output "Hello World!".

Note that: Every C statement ends with a semicolon ;

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.

In a programming language, these programming instructions are called statements .

The following statement "instructs" the compiler to print the text "Hello World" to the screen:

Example
printf("Hello World!");

It is important that you end the statement with a semicolon ;

If you forget the semicolon ( ;), an error will occur and the program will not run:

Example
printf("Hello World!")

error: expected ';' before 'return'

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!");

printf("Have a good day!");

Muzzamil Arain 17
New Lines
To insert a new line, you can use the \n character:

Example
#include <stdio.h>

int main() {

printf("Hello World! \n ");

printf("I am learning C.");

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

when testing alternative code.

Comments can be singled-lined or multi-lined .

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).

This example uses a single-line comment before a line of code:

Example
// This is a comment

printf("Hello World!");

This example uses a single-line comment at the end of a line of code:

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

when testing alternative code.

Comments can be singled-lined or multi-lined .

C Multi-line Comments
Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

Example
/* The code below will print the words Hello World!

to the screen, and it is amazing */

printf("Hello World!");

Single or multi-line comments?


It is up to you which you want to use. Normally, we use // for short comments, and /* */ for longer.

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

Declaring (Creating) Variables


To create a variable, specify the type and assign it a value :

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 ).

The equal sign is used to assign a value to the variable.

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:

int myNum = 15;

You can also declare a variable without assigning the value, and assign the value later:

Example
// Declare a variable

int myNum;

// Assign a value to the variable

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

display the value of a variable. However, this is not possible in C:

Example
int myNum = 15;

printf(myNum); // Nothing happens

To output variables in C, you must get familiar with something called " format specifiers ", which you will learn about

in the next chapter.

Muzzamil Arain 23
Basic Data Types
The data type specifies the size and type of information the variable will store.

In this tutorial, we will focus on the most basic ones:

Data Type Size Description Example

int 2 or 4 bytes Stores whole numbers, without decimals 1

float 4 bytes Stores fractional numbers, containing one or more decimals. 1.99

Sufficient for storing 6-7 decimal digits

double 8 bytes Stores fractional numbers, containing one or more decimals. 1.99

Sufficient for storing 15 decimal digits

char 1 byte Stores a single character/letter/number, or ASCII values ‘A’

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

specifier inside the printf() function to display it:

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);

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.

A format specifier starts with a percentage sign %, followed by a character.

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;

printf("%d", myNum); // Outputs 15

Muzzamil Arain 26
Format Specifiers
To print different types in a single printf() function, you can use the following:

Example
int myNum = 15;

char myLetter = 'D';

printf("My number is %d and my letter is %c", myNum, myLetter);

Print Values Without Variables


You can also just print a value without storing it in a variable, as long as you use the correct format specifier:

Example
printf("My favorite number is: %d", 15);

printf("My favorite letter is: %c", 'D');

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

int myNum = 15; // 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);

To combine both text and a variable, separate them with a comma inside the printf() function:

Example
int myNum = 15;

printf("My favorite number is: %d", myNum);

Muzzamil Arain 28
Basic Format Specifiers
There are different format specifiers for each data type. Here are some of them:

Format Specifiers Data type

%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

myNum = 10; // Now myNum is 10

You can also assign the value of one variable to another:

Example
int myNum = 15;

int myOtherNum = 23;

// Assign the value of myOtherNum (23) to myNum

myNum = myOtherNum;

// myNum is now 23, instead of 15

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

values are not surrounded by quotes ( ''), as they are numbers:

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:

Data TypeSize int2 or 4 bytesfloat4 bytesdouble8 byteschar1 byte

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.

Why Should I Know the Size of Data Types?


Knowing the size of different data types is important because it says something about memory usage and

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

myNum = 10; // error: assignment of read-only variable 'myNum'

You 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;

Notes On Constants
When you declare a constant variable, it must be assigned with a value:

Example
Like this:

const int minutesPerHour = 60;

This however, will not work :

const int minutesPerHour;

minutesPerHour = 60; // error

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)

int sum2 = sum1 + 250; // 400 (150 + 250)

int sum3 = sum2 + sum2; // 800 (400 + 400)

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.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x

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;

The addition assignment operator ( +=) adds a value to a variable:

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

helps us to find answers and make decisions.

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;

printf("%d", x > y); // returns 1 (true) because 5 is greater than 3

Muzzamil Arain 38
Comparison Operators
A list of all comparison operators:

Operator Name Example Description

== Equal to x==y Returns 1 if the values are equal

!= Not equal to x!=y Returns 1 if the values are not equal

> 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:

Operator Name Example Description

&& AND x < 5 && x < 10 Returns 1 if both statements are true

|| OR x < 5 || x < 4 Returns 1 if one of the statements is 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

For this, C has a bool data type, which is known as booleans .

Booleans represent values that are either true or 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:

bool isProgrammingFun = true;

bool isFishTasty = false;

Muzzamil Arain 41
Booleans
Before trying to print the boolean variables, you should know that boolean values are returned as integers :

• 1 (or any other number that is not 0) represents true

• 0 represents false

Therefore, you must use the %d format specifier to print a boolean value:

Example
// Create boolean variables

bool isProgrammingFun = true;

bool isFishTasty = false;

// Return boolean values

printf("%d", isProgrammingFun); // Returns 1 (true)

printf("%d", isFishTasty); // Returns 0 (false)

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).

You can also compare two variables:

Example
int x = 10;

int y = 9;

printf("%d", x > y);

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

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

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.

When we assign a value to the variable, it is stored in this memory address.

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.

Muzzamil Arain 44
User Input
You have already learned that printf() is used to output values in C.

To get user input , you can use the scanf() function:

Example
Output a number entered by the user:

// Create an integer variable that will store the number we get from the user

int myNum;

// Ask the user to type a number

printf("Type a number: \n");

// Get and save the number the user types

scanf ("%d", &myNum);

// Output the number the user typed

printf("Your number is: %d", 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;

// Ask the user to type a number AND a character

printf("Type a number AND a character and press enter: \n");

// Get and save the number AND character the user types

scanf("%d %c", &myNum, &myChar);

// Print the number

printf("Your number is: %d\n", myNum);

// Print the character

printf("Your character is: %c\n", myChar);

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

Which operator is used to check if two values are equal?

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);

Fill in the blanks to divide 10 by 5, and print the result.


int x = 10;
int y = 5;
printf("_____", x ____ y);

Use the correct operator to increase the value of the variable x by 1.


int x = 10;
x__;

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.

hint (years = days/365;

weeks = (days % 365)/7;

days = days - ((years*365) + (weeks*7)); )

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.

2. Write a C program to find the ASCII value of a character.

Muzzamil Arain 50
Conditional Statements
Conditional statements control the flow of a program by executing specific blocks of code based on certain

conditions.

Real life example

• If it rains, I will stay home else I can go outside

• If I pass this course, I will get a certificate

• 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:

• Less than: a < b

• Less than or equal to: a <= b

• Greater than: a > b

• Greater than or equal to: a >= b

• Equal to a == b

• Not 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 if to specify a block of code to be executed, if a specified condition is true

• 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

• Use switch to specify many alternative blocks of code to be executed

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) {

// 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");

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) {

// 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."

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) {

// 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."

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;

if (time < 18) {

printf("Good day.");

} else {

printf("Good evening.");

You can simply write:

Example
int time = 20;

(time < 18) ? printf("Good day.") : printf("Good evening.");

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) {

printf("Correct code.\nThe door is now open.");

} else {

printf("Wrong code.\nThe door remains closed.");

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) {

printf("The value is a positive number.");

} else if (myNum < 0) {

printf("The value is a negative number.");

} else {

printf("The value is 0.");

Muzzamil Arain 59
Conditional Statements
Real-Life Examples
Find out if a person is old enough to vote:

Example
int myAge = 25;

int votingAge = 18;

if (myAge >= votingAge) {

printf("Old enough to vote!");

} else {

printf("Not old enough to vote.");

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");
}

Print "Hello World" if x is equal to y.


int x = 50;
int y = 50;
___(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");
}

What will the following code output?


int time = 15;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}

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

percentage using conditional statements on below conditions:

• A+ if percentage is more than 90%.

• A if percentage is Between 80% to 90%.

• B if percentage is Between 70% to 80%.

• C if percentage is Between 60% to 70%.

• C- if percentage is Between 50% to 60%.

• F if percentage is less than 50%.

Muzzamil Arain 67
Loops in Programming
Loops or Iteration Statements in Programming are helpful when we need a specific task in repetition. They're

essential as they reduce hours of work to seconds.

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.

Types of Loops in Programming:


In programming, loops are categorized into two main types based on the control mechanism: entry-controlled

loops and exit-controlled loops.

1. Entry-Controlled loops:
In Entry controlled loops the test condition is checked before entering the main body of the loop. For Loop and

While Loop is Entry-controlled loops.

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) {

// code block to be executed

Expression 1 is executed (one time) before the execution of the code block.

Expression 2 defines the condition for executing the code block.

Expression 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Muzzamil Arain 69
For Loop
Example
int i;

for (i = 0; i < 5; i++) {

printf("%d\n", i);

Example explained

Expression 1 sets a variable before the loop starts (int i = 0).

Expression 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.

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.

3. Write a C program using a for loop to print numbers from 1 to 10.

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) {

// 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++;

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.

3. Write a C program to print all multiples of 3 up to 15 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.

5. Write a C program to count down from 10 to 1 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 {

// 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:

Example
int i = 0;

do {

printf("%d\n", i);

i++;

while (i < 5);

Muzzamil Arain 74
Break
The break statement can be used to jump out of a loop .

This example jumps out of the for loop when i is equal to 4:

Example
int i;

for (i = 0; i < 10; 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.

This example skips the value of 4:

Example
int i;

for (i = 0; i < 10; 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:

int myNumbers[] = {25, 50, 75, 100};

We have now created a variable that holds an array of four integers.

Access the Elements of an Array


To access an array element, refer to its index number .

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]);

// Now outputs 33 instead of 25

Muzzamil Arain 78
Arrays
Loop Through an Array
You can loop through the array elements with the for loop.

The following example outputs all elements in the myNumbers array:

Example
int myNumbers[] = {25, 50, 75, 100};

int i;

for (i = 0; i < 4; i++) {

printf("%d\n", myNumbers[i]);

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;

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.

For example, "Hello World" is a string of 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:

char greetings[] = "Hello World!";

Note that you have to use double quotes ( "").

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 [].

This example prints the first character (0) in greetings :

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!

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;

for (i = 0; i < 5; ++i) {

printf("%c\n", carName[i]);

Muzzamil Arain 83

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy