0% found this document useful (0 votes)
7 views54 pages

C Program Lecture Note

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

C Program Lecture Note

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

What is 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.
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 language 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

Difference between C and C++


 C++ was developed as an extension of C, and both languages have almost the same syntax
 The main difference between C and C++ is that C++ support classes and objects, while C does not

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 (see
below).

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.

C Quickstart
Let's create our first C file.
Open Codeblocks and go to File > New > Empty File.

Page 1 of 54
Write the following C code and save the file as myfirstprogram.c (File > Save File as):
myfirstprogram.c
#include <stdio.h>
int main() {
printf("Hello World!");
return 0;
}

C Syntax
Example
#include <stdio.h>
int main() {
printf("Hello World!");
return 0;
}

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.
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 ;
Note: The body of int main() could also been written as:
int main(){printf("Hello World!");return 0;}
Remember: The compiler ignores white spaces. However, multiple lines makes the code more readable.
Line 5: return 0 ends the main() function.
Line 6: Do not forget to add the closing curly bracket } to actually end the main function.
C Output (Print Text)
To output values or print text in C, you can use the printf() function:

Page 2 of 54
#include <stdio.h>
int main() {
printf("Hello World!");
return 0;
}

You can use as many printf() functions as you want. However, note that it does not insert a new line at
the end of the output:
Example
#include <stdio.h>
int main() {
printf("Hello World!");
printf("I am learning C.");
return 0;
}

C 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:
Example
#include <stdio.h>
int main() {
printf("Hello World!\nI am learning C.\nAnd it is awesome!");
return 0;
}

Page 3 of 54
Tip: Two \n characters after each other will create a blank line:
Example
#include <stdio.h>
int main() {
printf("Hello World!\n\n");
printf("I am learning C.");
return 0;
}

What is \n exactly?
The newline character (\n) is called an escape sequence, and it forces the cursor to change its position to
the beginning of the next line on the screen. This results in a new line.
Examples of other valid escape sequences are:

Escape Sequence Description


\t Creates a horizontal tab

\\ Inserts a backslash character (\)

\" Inserts a double quote character

The example of the above explanation table are


For: (\t)

#include <stdio.h>

int main() {

printf("Hello World!\t");

printf("I am learning C.");

return 0;

Output

Hello World! I am learning C.

For: (\\)

#include <stdio.h>

Page 4 of 54
int main() {

printf("Hello World!\\");

printf("I am learning C.");

return 0;

Output

Hello World!\I am learning C.

For: \"

#include <stdio.h>

int main() {

printf("They call him \"Johnny\".");

return 0;

Output

They call him "Johnny".

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!");
Page 5 of 54
This example uses a single-line comment at the end of a line of code:
Example
printf("Hello World!"); // This is a comment
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.

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'. Char values 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.
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:

Page 6 of 54
Example
// Declare a variable
int myNum;

// Assign a value to the variable


myNum = 15;

Output Variables
You learned from the output chapter that you can output values/print text with the printf() function:
Example
printf("Hello World!");
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".

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, you must use the format
specifier %d or %i surrounded by double quotes, inside the printf() function:
Example
int myNum = 15;
printf("%d", myNum); // Outputs 15
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

Page 7 of 54
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);
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);
You will learn more about Data Types in the next chapter.

Change Variable Values


Note: 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);
Or copy values to empty variables:
Example
// Create a variable and assign the value 15 to it
int myNum = 15;

Page 8 of 54
// Declare a variable without assigning it a value
int myOtherNum;

// Assign the value of myNum to myOtherNum


myOtherNum = myNum;

// myOtherNum now has 15 as a value


printf("%d", myOtherNum);
Add Variables Together
To add a variable to another variable, you can use the + operator:
Example
int x = 5;
int y = 6;
int sum = x + y;
printf("%d", sum);

Declare Multiple Variables


To declare more than one variable of the same type, use a comma-separated list:
Example
int x = 5, y = 6, z = 50;
printf("%d", x + y + z);
You can also assign the same value to multiple variables of the same type:
Example
int x, y, z;
x = y = z = 50;
printf("%d", x + y + z);

C Variable Names
All C variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Note: It is recommended to use descriptive names in order to create understandable and maintainable
code:

Page 9 of 54
Example
// Good
int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is


int m = 60;

The general rules for naming variables are:


 Names can contain letters, digits and underscores
 Names must begin with a letter or an underscore (_)
 Names are case sensitive (myVar and myvar are different variables)
 Names cannot contain whitespaces or special characters like !, #, %, etc.
 Reserved words (such as int) cannot be used as names

Real-Life Example
Often in our examples, we simplify variable names to match their data type (myInt or myNum
for int types, myChar for char types etc). This is done to avoid confusion.
However, if you want a real-life example on how variables can be used, take a look at the following,
where we have made a program that stores different data of a college student:
Example
// Student data
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25;
char studentGrade = 'B';

// Print variables
printf("Student id: %d\n", studentID);
printf("Student age: %d\n", studentAge);
printf("Student fee: %f\n", studentFee);
printf("Student grade: %c", studentGrade);

Page 10 of 54
Data Types
As explained in the Variables chapter, a variable in C must be a specified data type, and you must use
a format specifier inside the printf() function to display it:

#include <stdio.h>

int main() {
// 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);
return 0;
}

Output

5
5.990000
D

Basic Data Types


The data type specifies the size and type of information the variable will store.
Data Type Size Description

Int 2 or 4 bytes Stores whole numbers, without decimals

Float 4 bytes Stores fractional numbers, containing one or more


decimals. Sufficient for storing 6-7 decimal digits

Double 8 bytes Stores fractional numbers, containing one or more


decimals. Sufficient for storing 15 decimal digits

Char 1 byte Stores a single character/letter/number, or ASCII


values

Basic data types Format Specifiers


There are different format specifiers for each data type. Here are some of them:
Format Specifier Data Type

%d or %i int

%f float

Page 11 of 54
%lf double

%c char

%s Used for strings (text)

Example for:
%d or %i int

#include <stdio.h>

int main() {
int myNum = 5; // integer

printf("%d\n", myNum);
printf("%i\n", myNum);
return 0;
}

Output

5
5

Example for:
%f float

#include <stdio.h>

int main() {
float myFloatNum = 5.99; // Floating point number

printf("%f", myFloatNum);
return 0;
}

Output

5.990000

Example for:
%lf double

#include <stdio.h>

Page 12 of 54
int main() {
double myDoubleNum = 19.99; // Double (floating point number)

printf("%lf", myDoubleNum);
return 0;
}

Output

19.990000

Example for:
%c Char

#include <stdio.h>

int main() {
char myLetter = 'D'; // Character

printf("%c", myLetter);
return 0;
}

Output
D

Example for:
%s Used for strings (text)

#include <stdio.h>

int main() {
char greetings[] = "Hello World!";
printf("%s", greetings);

return 0;
}

Output

Hello World!

Set Decimal Precision


You have probably already noticed that if you print a floating point number, the output will show many
digits after the decimal point:
#include <stdio.h>

Page 13 of 54
int main() {
float myFloatNum = 3.5;
double myDoubleNum = 19.99;

printf("%f\n", myFloatNum);
printf("%lf", myDoubleNum);
return 0;
}

Output

3.500000
19.990000

If you want to remove the extra zeros (set decimal precision), you can use a dot (.) followed by a number
that specifies how many digits that should be shown after the decimal point:

#include <stdio.h>

int main() {
float myFloatNum = 3.5;

printf("%f\n", myFloatNum); // Default will show 6 digits after the decimal point
printf("%.1f\n", myFloatNum); // Only show 1 digit
printf("%.2f\n", myFloatNum); // Only show 2 digits
printf("%.4f", myFloatNum); // Only show 4 digits
return 0;
}

Output

3.500000
3.5
3.50
3.5000

C Type Conversion
Type Conversion
Sometimes, you have to convert the value of one data type to another type. This is known as type
conversion.
For example, if you try to divide two integers, 5 by 2, you would expect the result to be 2.5. But since we
are working with integers (and not floating-point values), the following example will just output 2:
#include <stdio.h>

int main() {
int x = 5;

Page 14 of 54
int y = 2;
int sum = 5 / 2;

printf("%d", sum);
return 0;
}

Output

To get the right result, you need to know how type conversion works.
There are two types of conversion in C:
 Implicit Conversion (automatically)
 Explicit Conversion (manually)

Implicit Conversion
Implicit conversion is done automatically by the compiler when you assign a value of one type to
another.
For example, if you assign an int value to a float type:
#include <stdio.h>

int main() {
// Automatic conversion: int to float
float myFloat = 9;

printf("%f", myFloat);
return 0;
}

Output

9.000000

As you can see, the compiler automatically converts the int value 9 to a float value of 9.000000.
This can be risky, as you might lose control over specific values in certain situations.
Especially if it was the other way around - the following example automatically converts the float
value 9.99 to an int value of 9:
#include <stdio.h>

int main() {
// Automatic conversion: float to int
int myInt = 9.99;

printf("%d", myInt);
return 0;
}

Output

Page 15 of 54
What happened to .99? We might want that data in our program! So be careful. It is important that you
know how the compiler work in these situations, to avoid unexpected results.
As another example, if you divide two integers: 5 by 2, you know that the sum is 2.5. And as you know
from the beginning of this page, if you store the sum as an integer, the result will only display the
number 2. Therefore, it would be better to store the sum as a float or a double, right?
#include <stdio.h>

int main() {
float sum = 5 / 2;

printf("%f", sum); // 2.000000


return 0;
}

Output

2.000000

Why is the result 2.00000 and not 2.5? Well, it is because 5 and 2 are still integers in the division. In this
case, you need to manually convert the integer values to floating-point values. (see below).

Explicit Conversion
Explicit conversion is done manually by placing the type in parentheses () in front of the value.
Considering our problem from the example above, we can now get the right result:

#include <stdio.h>

int main() {
// Manual conversion: int to float
float sum = (float) 5 / 2;

printf("%f", sum);
return 0;
}

Output

2.500000

You can also place the type in front of a variable:

#include <stdio.h>

int main() {
int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;

printf("%f", sum);
return 0;
}
Page 16 of 54
Output

2.500000

And since you learned about "decimal precision" in the previous chapter, you could make the output even
cleaner by removing the extra zeros (if you like):
#include <stdio.h>

int main() {
int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;

printf("%.1f", sum);
return 0;
}

Output

2.5

C Constants

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:

#include <stdio.h>

int main() {
const int myNum = 15;
myNum = 10;

printf("%d", myNum);
return 0;
}

Output

prog.c: In function 'main':


prog.c:5:18: error: assignment of read-only variable 'myNum'
5 | myNum = 10;
| ^

You should always declare the variable as constant when you have values that are unlikely to change:

#include <stdio.h>

int main() {
const int minutesPerHour = 60;
const float PI = 3.14;
Page 17 of 54
printf("%d\n", minutesPerHour);
printf("%f\n", PI);
return 0;
}

Output

60
3.140000

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:

#include <stdio.h>

int main() {
const int minutesPerHour;
minutesPerHour = 60;

printf("%d", minutesPerHour);
return 0;
}

Output

prog.c: In function 'main':


prog.c:5:18: error: assignment of read-only variable 'minutesPerHour'
5 | minutesPerHour = 60;
| ^

Another thing about constant variables, is that it is considered good practice to declare them with
uppercase. It is not required, but useful for code readability and common for C programmers:

#include <stdio.h>

int main() {
const int BIRTHYEAR = 1980;

printf("%d", BIRTHYEAR);
return 0;
}

Output

1980

Page 18 of 54
C Operators

Operators are used to perform operations on variables and values.


In the example below, we use the + operator to add together two values:

#include <stdio.h>

int main() {
int myNum = 100 + 50;
printf("%d", myNum);
return 0;
}

Output

150

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:

#include <stdio.h>

int main() {
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
printf("%d\n", sum1);
printf("%d\n", sum2);
printf("%d\n", sum3);
return 0;
}

Output

Page 19 of 54
150
400
800

C divides the operators into the following groups:


 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators

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

#include <stdio.h>

int main() {
int x = 5;
int y = 3;
printf("%d", x + y);
return 0;
}

Output

Page 20 of 54
#include <stdio.h>

int main() {
int x = 5;
int y = 3;
printf("%d", x - y);
return 0;
}

Output

#include <stdio.h>

int main() {
int x = 5;
int y = 3;
printf("%d", x * y);
return 0;
}

Output

15

#include <stdio.h>

int main() {
int x = 12;
int y = 3;
printf("%d", x / y);
return 0;
}

Output

#include <stdio.h>

int main() {
int x = 5;
int y = 2;
printf("%d", x % y);
return 0;
}

Output

1
Page 21 of 54
#include <stdio.h>

int main() {
int x = 5;
printf("%d", ++x);
return 0;
}

Output

#include <stdio.h>

int main() {
int x = 5;
printf("%d", --x);
return 0;
}
Output

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

#include <stdio.h>

int main() {
int x = 10;
printf("%d", x);
return 0;
}

Output

10

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

#include <stdio.h>

int main() {
int x = 10;
x += 5;
printf("%d", x);
return 0;
}
Page 22 of 54
Output

15

A list of all assignment operators:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Examples for each of the operator assignments

#include <stdio.h>

int main() {
int x = 5;
printf("%d", x);
return 0;
}

Output

#include <stdio.h>

int main() {
int x = 5;
x += 3;
Page 23 of 54
printf("%d", x);
return 0;
}

Output

#include <stdio.h>

int main() {
int x = 5;
x -= 3;
printf("%d", x);
return 0;
}

Output

#include <stdio.h>

int main() {
int x = 5;
x *= 3;
printf("%d", x);
return 0;
}

Output

15

#include <stdio.h>

int main() {
float x = 5;
x /= 3;
printf("%f", x);
return 0;
}

Output

1.66667

#include <stdio.h>

int main() {

Page 24 of 54
int x = 5;
x %= 3;
printf("%d", x);
return 0;
}

Output

#include <stdio.h>

int main() {
int x = 5;
x &= 3;
printf("%d", x);
return 0;
}

Output

#include <stdio.h>

int main() {
int x = 5;
x |= 3;
printf("%d", x);
return 0;
}

Output

#include <stdio.h>

int main() {
int x = 5;
x ^= 3;
printf("%d", x);
return 0;
}

Output

#include <stdio.h>

Page 25 of 54
int main() {
int x = 5;
x >>= 3;
printf("%d", x);
return 0;
}

Output

#include <stdio.h>
int main() {
int x = 5;
x <<= 3;
printf("%d", x);
return 0;
}

Output

40

c. 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 chapter.
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:
#include <stdio.h>

int main() {
int x = 5;
int y = 3;
printf("%d", x > y); // returns 1 (true) because 5 is greater than 3
return 0;
}

Output

A list of all comparison operators:

Operator Name Example

== Equal to x == y

Page 26 of 54
!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Examples for each of the comparison operators

#include <stdio.h>

int main() {
int x = 5;
int y = 3;
printf("%d", x == y); // returns 0 (false) because 5 is not equal to 3
return 0;
}

Output

#include <stdio.h>

int main() {
int x = 5;
int y = 3;
printf("%d", x != y); // returns 1 (true) because 5 is not equal to 3
return 0;
}

Output

#include <stdio.h>

int main() {
int x = 5;
int y = 3;
printf("%d", x > y); // returns 1 (true) because 5 is greater than 3
return 0;
}

Output

Page 27 of 54
#include <stdio.h>

int main() {
int x = 5;
int y = 3;
printf("%d", x < y); // returns 0 (false) because 5 is not less than 3
return 0;
}

Output

#include <stdio.h>

int main() {
int x = 5;
int y = 3;

// Returns 1 (true) because five is greater than, or equal, to 3


printf("%d", x >= y);
return 0;
}

Output

#include <stdio.h>

int main() {
int x = 5;
int y = 3;

// Returns 0 (false) because 5 is neither less than or equal to 3


printf("%d", x <= y);
return 0;
}

Output

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

Operator Name Description Example

Page 28 of 54
&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)

Examples for each of the Logical Operators

#include <stdio.h>

int main() {
int x = 5;
int y = 3;

// Returns 1 (true) because 5 is greater than 3 AND 5 is less than 10


printf("%d", x > 3 && x < 10);
return 0;
}

Output

#include <stdio.h>

int main() {
int x = 5;
int y = 3;

// Returns 1 (true) because one of the conditions are true (5 is greater than 3, but 5 is not less than 4)
printf("%d", x > 3 || x < 4);
return 0;
}

Output

#include <stdio.h>

int main() {
int x = 5;
int y = 3;

// Returns false (0) because ! (not) is used to reverse the result


printf("%d", !(x > 3 && x < 10));
return 0;
}
Output
0
Page 29 of 54
Conditional Statements
If ... Else
Conditions and If 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.
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
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
#include <stdio.h>

int main() {
if (20 > 18) {
printf("20 is greater than 18");
}
return 0;
}

Output
20 is greater than 18

We can also test variables:

#include <stdio.h>
int main() {
int x = 20;
int y = 18;
if (x > y) {
printf("x is greater than y");
}
return 0;
}
Output
x is greater than y
Page 30 of 54
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".
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
}

#include <stdio.h>

int main() {
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
return 0;
}

Output
Good evening.

Example explained
In the example above, time (20) is greater than 18, so the condition is false. Because of this, we move on
to the else condition and print to the screen "Good evening". If the time was less than 18, the program
would print "Good day".

The else if Statement


Use the else if statement to specify a new condition if the first condition is false.

Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

#include <stdio.h>

int main() {
int time = 22;
if (time < 10) {

Page 31 of 54
printf("Good morning.");
} else if (time < 20) {
printf("Good day.");
} else {
printf("Good evening.");
}
return 0;
}

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

#include <stdio.h>

int main() {
int myNum = 10;

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

return 0;
}

Output
The value is a positive number.

C Short Hand If Else


Short Hand If...Else (Ternary Operator)
There is also a short-hand if else, which is known as the ternary operator because it consists of three
operands. It can be used to replace multiple lines of code with a single line. It is often used to replace
simple if else statements:
Syntax
variable = (condition) ? expressionTrue : expressionFalse;

Instead of writing:
#include <stdio.h>

int main() {

Page 32 of 54
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
return 0;
}
Output
Good evening.

You can simply write:

#include <stdio.h>

int main() {
int time = 20;
(time < 18) ? printf("Good day.") : printf("Good evening.");
return 0;
}

Output
Good evening.

C Switch

Switch Statement
Instead of writing many if..else statements, you can use the switch statement.
The switch statement selects one of many code blocks to be executed:
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

This is how it works:


 The switch expression is evaluated once
 The value of the expression is compared with the values of each case
 If there is a match, the associated block of code is executed
 The break statement breaks out of the switch block and stops the execution
 The default statement is optional, and specifies some code to run if there is no case match
The example below uses the weekday number to calculate the weekday name:

#include <stdio.h>

int main() {
int day = 4;
Page 33 of 54
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
}

return 0;
}

Output
Thursday

The break Keyword


When C reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for more testing.
A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in
the switch block.

The default Keyword


The default keyword specifies some code to run if there is no case match:
#include <stdio.h>

int main() {
int day = 4;

switch (day) {
case 6:
printf("Today is Saturday");
break;
case 7:
printf("Today is Sunday");
break;
Page 34 of 54
default:
printf("Looking forward to the Weekend");
}

return 0;
}

Output
Looking forward to the Weekend

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:
#include <stdio.h>

int main() {
int i = 0;

while (i < 5) {
printf("%d\n", i);
i++;
}

return 0;
}

Output
0
1
2
3
4

Note: Do not forget to increase the variable used in the condition (i++), otherwise the loop will never
end!

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.

Page 35 of 54
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:

#include <stdio.h>

int main() {
int i = 0;

do {
printf("%d\n", i);
i++;
}
while (i < 5);

return 0;
}

Output
0
1
2
3
4
Do not forget to increase the variable used in the condition, otherwise the loop will never end!

C For Loop

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 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
The example below will print the numbers 0 to 4:
#include <stdio.h>

int main() {
int i;

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


printf("%d\n", i);
}
Page 36 of 54
return 0;
}
Output
0
1
2
3
4

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:
#include <stdio.h>

int main() {
int i;

for (i = 0; i <= 10; i = i + 2) {


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

return 0;
}
Output
0
2
4
6
8
10

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

#include <stdio.h>

int main() {
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) {
Page 37 of 54
printf(" Inner: %d\n", j); // Executes 6 times (2 * 3)
}
}

return 0;
}

Output
Outer: 1
Inner: 1
Inner: 2
Inner: 3
Outer: 2
Inner: 1
Inner: 2
Inner: 3

C Break and Continue


Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump
out" of a switch statement.
The break statement can also be used to jump out of a loop.
This example jumps out of the for loop when i is equal to 4:

#include <stdio.h>

int main() {
int i;

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


if (i == 4) {
break;
}
printf("%d\n", i);
}

return 0;
}

Output
0
1
2
3

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:
#include <stdio.h>

int main() {
int i;
Page 38 of 54
for (i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
printf("%d\n", i);
}

return 0;
}
Output
0
1
2
3
5
6
7
8
9

Break and Continue in While Loop


You can also use break and continue in while loops:
#include <stdio.h>

int main() {
int i = 0;

while (i < 10) {


if (i == 4) {
break;
}
printf("%d\n", i);
i++;
}

return 0;
}

Output
0
1
2
3

#include <stdio.h>

int main() {
int i = 0;

while (i < 10) {


if (i == 4) {
i++;
Page 39 of 54
continue;
}
printf("%d\n", i);
i++;
}

return 0;
}

Output
0
1
2
3
5
6
7
8
9

Page 40 of 54
C Files

File Handling
In C, you can create, open, read, and write to files by declaring a pointer of type FILE, and use
the fopen() function:
FILE*fptr
fptr = fopen(filename, mode);

FILE is basically a data type, and we need to create a pointer variable to work with it (fptr). For now, this
line is not important. It's just something you need when working with files.
To actually open a file, use the fopen() function, which takes two parameters:

Parameter Description

filename The name of the actual file you want to open (or create),
like filename.txt

mode A single character, which represents what you want to do


with the file (read, write or append):
w - Writes to a file
a - Appends new data to a file
r - Reads from a file

Create a File
To create a file, you can use the w mode inside the fopen() function.
The w mode is used to write to a file. However, if the file does not exist, it will create one for you:

Example
FILE *fptr;

// Create a file
fptr = fopen("filename.txt", "w");

Page 41 of 54
// Close the file
fclose(fptr);
Note: The file is created in the same directory as your other C files, if nothing else is specified.
On our computer, it looks like this:

#include <stdio.h>

int main() {
FILE *fptr;

// Create a file on your computer (filename.txt)


fptr = fopen("filename.txt", "w");

// Close the file


fclose(fptr);

return 0;
}

Create File Example


This is just an example of how it may look like on your computer when you create a file in C:

Page 42 of 54
Tip: If you want to create the file in a specific folder, just provide an absolute path:
fptr = fopen("C:\directoryname\filename.txt", "w");

Closing the file


Did you notice the fclose() function in our example above?
This will close the file when we are done with it.
It is considered as good practice, because it makes sure that:
 Changes are saved properly
 Other programs can use the file (if you want)
 Clean up unnecessary memory space

C Write To Files

Write To a File
Let's use the w mode from the previous chapter again, and write something to the file we just created.
The w mode means that the file is opened for writing. To insert content to it, you can use
the fprint() function and add the pointer variable (fptr in our example) and some text:

Example
FILE *fptr;

// Open a file in writing mode


fptr = fopen("filename.txt", "w");

// Write some text to the file


fprintf(fptr, "Some text");

// Close the file


fclose(fptr);
As a result, when we open the file on our computer, it looks like this:
Example

#include <stdio.h>

int main() {

Page 43 of 54
FILE *fptr;

// Open a file in writing mode


fptr = fopen("filename.txt", "w");

// Write some text to the file


fprintf(fptr, "Some text");

// Close the file


fclose(fptr);

return 0;
}

Write To a File Example


This is just an example to show what it looks like when you open the file that you just wrote to:

Note: If you write to a file that already exists, the old content is deleted, and the new content is inserted.
This is important to know, as you might accidentally erase existing content.
For example:
Example
fprintf(fptr, "Hello World!");
As a result, when we open the file on our computer, it says "Hello World!" instead of "Some text":

#include <stdio.h>
Page 44 of 54
int main() {
FILE *fptr;

// Open a file in writing mode


fptr = fopen("filename.txt", "w");

// Write some text to the file


fprintf(fptr, "Hello World!");

// Close the file


fclose(fptr);

return 0;
}

Write To a File Example


This is just an example to show what it looks like when you open the file that you just wrote to:

Append Content To a File


If you want to add content to a file without deleting the old content, you can use the a mode.
The a mode appends content at the end of the file:

Page 45 of 54
Example
FILE *fptr;

// Open a file in append mode


fptr = fopen("filename.txt", "a");

// Append some text to the file


fprintf(fptr, "\nHi everybody!");

// Close the file


fclose(fptr);
As a result, when we open the file on our computer, it looks like this:

#include <stdio.h>

int main() {
FILE *fptr;

// Open a file in append mode


fptr = fopen("filename.txt", "a");

// Append some text to the file


fprintf(fptr, "\nHi everybody!");

// Close the file


fclose(fptr);

return 0;
}

Append Content To a File Example


This is just an example to show what it looks like when you append content to a file:

Page 46 of 54
Note: Just like with the w mode; if the file does not exist, the a mode will create a new file with the
"appended" content.

C Read Files

Read a File
In the previous chapter, we wrote to a file using w and a modes inside the fopen() function.
To read from a file, you can use the r mode:
Example
FILE *fptr;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

This will make the filename.txt opened for reading.


It requires a little bit of work to read a file in C. Hang in there! We will guide you step-by-step.
Next, we need to create a string that should be big enough to store the content of the file.
For example, let's create a string that can store up to 100 characters:
Example
FILE *fptr;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

// Store the content of the file


char myString[100];
Page 47 of 54
In order to read the content of filename.txt, we can use the fgets() function.
The fgets() function takes three parameters:

Example
fgets(myString, 100, fptr);
1. The first parameter specifies where to store the file content, which will be in the myString array
we just created.
2. The second parameter specifies the maximum size of data to read, which should match the size
of myString (100).
3. The third parameter requires a file pointer that is used to read the file (fptr in our example).
Now, we can print the string, which will output the content of the file:
Example
FILE *fptr;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

// Store the content of the file


char myString[100];

// Read the content and store it inside myString


fgets(myString, 100, fptr);

// Print the file content


printf("%s", myString);

// Close the file


fclose(fptr);

Example

#include <stdio.h>

int main() {
FILE *fptr;

Page 48 of 54
// Open a file in read mode
fptr = fopen("filename.txt", "r");

// Store the content of the file


char myString[100];

// Read the content and store it inside myString


fgets(myString, 100, fptr);

// Print file content


printf("%s", myString);

// Close the file


fclose(fptr);

return 0;
}

Output

Hello World!

Note: The fgets function only reads the first line of the file. If you remember, there were two lines of text
in filename.txt.
To read every line of the file, you can use a while loop:
Example

#include <stdio.h>

int main() {
FILE *fptr;

Page 49 of 54
// Open a file in read mode
fptr = fopen("filename.txt", "r");

// Store the content of the file


char myString[100];

// Read the content and print it


while(fgets(myString, 100, fptr)) {
printf("%s", myString);
}

// Close the file


fclose(fptr);

return 0;
}

Output
Hello
Hi everybody!

If you try to open a file for reading that does not exist, the fopen() function will return NULL.
Tip: As a good practice, we can use an if statement to test for NULL, and print some text instead (when
the file does not exist):
Example
FILE *fptr;

// Open a file in read mode


fptr = fopen("loremipsum.txt", "r");

// Print some text if the file does not exist


if(fptr == NULL) {
printf("Not able to open the file.");
}

Page 50 of 54
// Close the file
fclose(fptr);
If the file does not exist, the following text is printed:

Example

#include <stdio.h>

int main() {
FILE *fptr;

// Open a file in read mode


fptr = fopen("loremipsum.txt", "r");

// Print some text if the file does not exist


if(fptr == NULL) {
printf("Not able to open the file.");
}

// Close the file


fclose(fptr);

return 0;
}

Output

Not able to open the file.

With this in mind, we can create a more sustainable code if we use our "read a file" example above again:
Example
If the file exist, read the content and print it. If the file does not exist, print a message:

Page 51 of 54
#include <stdio.h>

int main() {
FILE *fptr;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

// Store the content of the file


char myString[100];

// If the file exist


if(fptr != NULL) {

// Read the content and print it


while(fgets(myString, 100, fptr)) {
printf("%s", myString);
}

// If the file does not exist


} else {
printf("Not able to open the file.");
}

// Close the file


fclose(fptr);

return 0;
}

Output
Hello
Hi everybody!

Page 52 of 54
Why Learn C?

C programming language is the most popular language. It is a must for software engineering students. If
you learn C, It will help you to learn other languages easily like Java, C++, C#, Python, etc. C language is
faster than other programming languages like Java and Python. It can handle low-level activities. We can
compile the C code in a variety of computer platforms.
List of some key advantages of C language:
 Easy to learn.
 Versatile Language, which can be used in both applications and technologies.
 MIddle-level language.
 C is a structured language.

Features of C Language

There are some key features of C language that show the ability and power of C language:
 Simplicity and Efficiency: The simple syntax and structured approach make the C language easy
to learn.
 Faster Language: C is a static programming language, which is faster than dynamic languages.
Like Java and Python are dynamic languages, C is a compiler-based program. That is the reason for
faster code compilation and execution.
 Portable: C provides the feature that you write code once and run it anywhere on any computer. It
shows the machine-independent nature of the C language.
 Memory Management: C comes with the free() function to free the allocated memory at any time.
 Pointers: C comes with the feature of pointers. Through pointers, we can directly access or interact
with the memory. We can initialize a pointer as an array, variables, etc.
 Structured Language: C provides the feature of structural programming, It allows you to code into
different parts using functions that can be stored as libraries for reusability.

Applications of C Language

C was used in programs that were used in making operating systems. C was known as a system
development language because the code written in C runs as fast as the code written in assembly language.
The use of C is given below:
 Operating Systems
 Language Compilers
 Assemblers
 Text Editors
 Print Spoolers
 Network Drivers
a) M Explain the following: Constant ,Variable ,Data types ,Identifier and Strings.5mks
b) List all the arithmetic and relational operators that are used for variables. 5 mks
c) Write short note on the following in creating application as used in visual basic program:
(i)Form (ii) Project.5 mks
d) Explain the followings :
Key trapping and Visual Basic looping 5 mks
e) Explain the following: Constant ,Variable ,Data types ,Identifier and Strings.5mks
Page 53 of 54
f) List all the arithmetic and relational operators that are used for variables. 5 mks
g) Write short note on the following in creating application as used in visual basic program:
(i)Form (ii) Project.5 mks
h) Explain the followings :
Key trapping and Visual Basic looping 5 mks
i) Explain the following: Constant ,Variable ,Data types ,Identifier and Strings.5mks
j) List all the arithmetic and relational operators that are used for variables. 5 mks
k) Write short note on the following in creating application as used in visual basic program:
(i)Form (ii) Project.5 mks
l) Explain the followings :
Key trapping and Visual Basic looping 5 mks
m) Explain the following: Constant ,Variable ,Data types ,Identifier and Strings.5mks
n) List all the arithmetic and relational operators that are used for variables. 5 mks
o) Write short note on the following in creating application as used in visual basic program:
(i)Form (ii) Project.5 mks
p) Explain the followings :
Key trapping and Visual Basic looping 5 mks
q) Explain the following: Constant ,Variable ,Data types ,Identifier and Strings.5mks
r) List all the arithmetic and relational operators that are used for variables. 5 mks
s) Write short note on the following in creating application as used in visual basic program:
(i)Form (ii) Project.5 mks
t) Explain the followings :
Key trapping and Visual Basic looping 5 mks
u) Explain the following: Constant ,Variable ,Data types ,Identifier and Strings.5mks
v) List all the arithmetic and relational operators that are used for variables. 5 mks
w) Write short note on the following in creating application as used in visual basic program:
(i)Form (ii) Project.5 mks
x) Explain the followings :
Key trapping and Visual Basic looping 5 mks
y) Explain the following: Constant ,Variable ,Data types ,Identifier and Strings.5mks
z) List all the arithmetic and relational operators that are used for variables. 5 mks
aa) Write short note on the following in creating application as used in visual basic program:
(i)Form (ii) Project.5 mks
bb) Explain the followings :
Key trapping and Visual Basic looping 5 mks
 odern Programs
 Databases
 Language Interpreters
 Utilities

Page 54 of 54

You might also like