C Program Lecture Note
C Program Lecture Note
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
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:
#include <stdio.h>
int main() {
printf("Hello World!\t");
return 0;
Output
For: (\\)
#include <stdio.h>
Page 4 of 54
int main() {
printf("Hello World!\\");
return 0;
Output
For: \"
#include <stdio.h>
int main() {
return 0;
Output
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
Page 6 of 54
Example
// Declare a variable
int myNum;
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.
Page 8 of 54
// Declare a variable without assigning it a value
int myOtherNum;
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;
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
%d or %i int
%f float
Page 11 of 54
%lf double
%c char
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!
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;
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
#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
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
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
#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
a. Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
#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
#include <stdio.h>
int main() {
int x = 10;
x += 5;
printf("%d", x);
return 0;
}
Page 22 of 54
Output
15
= 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
#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
== Equal to x == y
Page 26 of 54
!= Not equal x != y
#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;
Output
#include <stdio.h>
int main() {
int x = 5;
int y = 3;
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:
Page 28 of 54
&& Logical and Returns true if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)
#include <stdio.h>
int main() {
int x = 5;
int y = 3;
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;
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
#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".
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.
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.
#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
}
#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
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!
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;
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;
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
#include <stdio.h>
int main() {
int 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
int main() {
int i = 0;
return 0;
}
Output
0
1
2
3
#include <stdio.h>
int main() {
int i = 0;
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
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;
return 0;
}
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");
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;
#include <stdio.h>
int main() {
Page 43 of 54
FILE *fptr;
return 0;
}
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;
return 0;
}
Page 45 of 54
Example
FILE *fptr;
#include <stdio.h>
int main() {
FILE *fptr;
return 0;
}
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;
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;
Example
#include <stdio.h>
int main() {
FILE *fptr;
Page 48 of 54
// Open a file in read mode
fptr = fopen("filename.txt", "r");
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");
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;
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;
return 0;
}
Output
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;
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