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

C Programming Course

Uploaded by

diwoutaflorence
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

C Programming Course

Uploaded by

diwoutaflorence
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

C PROGRAMMING

CRASH COURSE
Montchio Tabela Abigael
NAME C

TYPE Programming Language

CATEGORY High-Level programming language

TRANSLATOR TYPE Compiler

IDE Dev C++

Table of Contents
I) Introduction................................................................................................................................1
II) Structure of a C Program:.........................................................................................................1
Compiling and Executing our program:....................................................................................2
III) Comments in a C program........................................................................................................2
Single-Line Comments:..................................................................................................................2
Multi-Line Comments:................................................................................................................... 3
IV) Data Types in C programming..................................................................................................3
Data Types:....................................................................................................................................3
Format Specifiers:..........................................................................................................................3
Type Conversion:...........................................................................................................................
4
● Implicit Conversion (automatically)...................................................................................... 4
● Explicit Conversion (manually).............................................................................................4
V) Variables in C
programming.........................................................................................................4
Naming conventions:.....................................................................................................................5
● Snake case:......................................................................................................................... 5
● Camel case:..........................................................................................................................
5
● Pascal case:.........................................................................................................................5
Declaring (creating) Variables....................................................................................................... 5
Constants in C programming.....................................................................................................6
VI) Operators in C programming................................................................................................... 6
- Arithmetic Operators:............................................................................................................ 6
- Assignment Operators.......................................................................................................... 7
- Comparison Operators..........................................................................................................8
- Logical Operators..................................................................................................................8
VII) Input and Output in C programming....................................................................................... 8
Displaying Output:.........................................................................................................................8
Escape Character:.................................................................................................................. 9
Displaying Variables:.............................................................................................................10
Receiving User Input:.................................................................................................................. 11
Multiple Inputs:...................................................................................................................... 11
String Input:............................................................................................................................12
EXERCISE:..................................................................................................................................12
VIII) Conditional Statements in C programming.......................................................................... 13
If…Else Conditional statements:..................................................................................................13
- Using if................................................................................................................................ 13
- Using if..else....................................................................................................................... 14
- Using if…else if................................................................................................................... 15
- Using the Ternary operator (shorthand if):.......................................................................... 15
Switch…Case conditional statements:.........................................................................................16
- Using the default keyword:..................................................................................................17
IX) Looping and Iteration in C
programming.................................................................................18
- While Loop.................................................................................................................................18
- Do…While loop:.........................................................................................................................18
- For loop:.....................................................................................................................................19
- Nested Loops:............................................................................................................................20
EXERCISE:..................................................................................................................................21
X) Break/Continue in C Programming.........................................................................................21
- Using Break.............................................................................................................................. 21
- Using Continue......................................................................................................................... 22
XI Arrays in C Programming...........................................................................................................23
- Creating an Array.......................................................................................................................23
- Accessing the elements of an Array......................................................................................... 23
- Changing an element in an Array............................................................................................. 24
- Multi-Dimensional Arrays...........................................................................................................26
Two-dimensional Arrays........................................................................................................26
- Accessing Elements of a 2D array............................................................................................26
- Changing the elements of a 2D array...................................................................................... 26
- Traversing a 2D Array:............................................................................................................. 27
XII) Functions in C Programming...................................................................................................27
- Creating a Function...................................................................................................................28
- Calling a function...................................................................................................................... 28
- Function parameters/arguments................................................................................................29
- Declaring a function and defining it later....................................................................................30
- XIII) Recursive functions in C
programming...............................................................................31
- Mathematical functions in C.......................................................................................................33
- Square root function..................................................................................................................33
- Rounding a number.................................................................................................................. 34
- Raising a number to any power................................................................................................ 34
- Other Math Functions in the math.h library................................................................................35
XIV) Strings in C programming.......................................................................................................35
- Length of a string.................................................................................................................. 35
- Concatenate strings...............................................................................................................36
- Copy one string into another..................................................................................................36
- Compare two strings..............................................................................................................36
XV) Structures in C
programming..................................................................................................37
- Creating a structure............................................................................................................... 37
Practice Exercises:..........................................................................................................................39
I) Introduction
C is a very popular general-purpose programming language created by Dennis Ritchie at the Bell
Laboratories in 1972. It can be used to develop software like operating systems, databases,
compilers, and so on. C programming is an excellent language to learn to program for beginners.
● Procedural Language - Instructions in a C program are executed step by step.
● Speed - C programming is faster than most programming languages.
● General Purpose - C programming can be used to develop operating systems, embedded
systems, databases, and so on.
● Portable - You can move C programs from one platform to another, and run it without any or
minimal changes.

To start using C, you need two things:


● A text editor, like Notepad, to write the C code
● A compiler, like GCC, to translate the C code into a language that the computer will
understand (machine code).
There are many text editors and compilers to choose from. In this course, we will use an IDE called
Dev C++.
An integrated development environment (IDE) is a software application that helps programmers
develop software code efficiently. It provides programmers with all the features they might need such
as an editor and a compiler all in one application.

II) Structure of a C Program:


In this course, we will be writing our C code in rectangles as shown below. Consider this basic C
program:

#include <stdio.h>

int main() {
printf("HelloWorld!");
return 0;
}
Line 1: #include <stdio.h> is a preprocessor command. It tells the C compiler to include code
from the header file library. stdio.h is a header file that lets us work with input and output
functions, such as printf() (used on line 4). Header files add functionality to C programs. Header
files have the extension .h
To use a header file in a C program, we have to include it at the top of the program code. We
have two types of header files;
- System header files: These are standard header files that come with the C programming
language such as stdio.h, math.h, time.h, string.h etc. We include them using the
syntax: #include <stdio.h>
- User header files: These are header files created by the user. Say we create a header
file named myheader.h, We can include it at the top of our code using the syntax:
#include “myheader.h”
Line 2: A blank line. C ignores white space (empty space). But we use it to make the code more
readable.

Montchio Tabela A. v1.0 1


Line 3: Another thing that always appears in a C program, is main(). This is called a function.
Any code inside its curly brackets {} belongs to this main() function and will be executed. The
main function is where the program execution begins.

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

Line 5: return 0 is what the main() function returns. Here, it ends the main() function and hence
ends the execution of our program.

Things to note:

- Every C statement ends with a semicolon.


- C ignores white space (empty space).

Compiling and Executing our program:

● Open the Dev C++ IDE application.


● Create a new source file:
● Type in the code
● Save the file by clicking on the File menu and selecting Save or using the keyboard shortcut
Ctrl + S
● When the Save dialog box appears, enter the name you want the file to be saved as and
select a location where the file should be saved in and click Save. Note, in the dropdown of
Save as Type, select C source file.
● Now press F9 key on your keyboard to compile the program. If there are any errors, resolve
them before continuing.
● When there are no more errors, press F10 key to run or execute the program. You should
see a screen like this:

Congratulations. You have just written and executed a C program.

III) Comments in a C program


Comments in C are not compiled or executed and are mainly for documentation purposes. Comments
help us make notes in our program. Comments can be used to explain code making it more readable.
In C, we have two types of comments: Single line comments and Multi-line comments.

Single-Line Comments:
Single-line comments start with two forward slashes (//). Any text after // and the end of the line
is ignored by the compiler. This example uses a single-line comment before a line of code:

Montchio Tabela A. v1.0 2


// This is a comment
printf("Hello World!");

We can also write single line comments on the same line as our C statements:

printf("Hello World!"); // This is a comment

We can write multiple single line comments by writing each comment on it’s own line:

// This is comment 1
// This is comment 2 // This is comment 3
printf("Hello World!");

Multi-Line Comments:
With single-line comments, we can only comment one line at a time. To comment multiple lines
at once, we can use a multi-line comment. Multi-line comments start with /* and ends with */. Any
text between /* and */ will be ignored by the compiler:
/* This is a multi-line comment and we
can write on as many lines as we
like and it won’t be a problem.
*/ printf("Hello
World!");

IV) Data Types in C programming


Data Types:
Data types tell C what kind of data we are dealing with. We use data types when declaring variables
and functions. In C, we have 4 main basic data types:

Data Size Description


Type

int
2 or 4 Stores whole numbers, without decimals
bytes

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

Montchio Tabela A. v1.0 3


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

Format Specifiers:
If we want to output our data using the printf() function, we need to pass in a format specifier to tell
the compiler what kind of data is to be printed and how it should be printed.
There are different format specifiers for each data type. Here are some of them:
Format Specifier Data Type

%d or %i int

%f float

%lf double

%c char

%s Used for strings (text),

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. To get the right output, we can use type conversion. In C, there are two types of
conversion:

● Implicit Conversion (automatically)


Implicit conversion is done automatically by the compiler when you assign a value of one type
to another. We can use format specifiers for implicit type conversions. For example, if you
assign an int value to a float type:

// Automatic conversion: int to float float myFloat


= 9;
printf("%f", myFloat); // outputs 9.000000

● Explicit Conversion (manually)


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:

// Manual conversion: int to float


float sum = (float) 5 / 2;
printf("%f", sum); // output 2.500000

Montchio Tabela A. v1.0 4


V) Variables in C programming
Variables are like containers used for storing data when our program is executing. We can use
variables to store numbers, characters, arrays etc. Variables help us refer to our data when we need
it. The data stored in a variable can be changed at any point during program execution.
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). It is
recommended to use descriptive names in order to create understandable and maintainable code:

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.

Naming conventions:
In programming, we have different naming conventions for how we name variables. For variable
names with multiple words, we cannot use white space when creating the variables because this will
cause our program to crash with errors. Example:

number of books = 10;


The variable name above will cause compilation errors due to the white space between the words. To
solve this problem, we use naming conventions. Below are some naming conventions we can use:
● Snake case:
Using snake case, we separate each word using an underscore ( _ ) character.

number_of_books = 10;

● Camel case:
Using camel case, we write the first word in lowercase and after that the first letter of each
word is written in uppercase.

numberOfBooks = 10;

● Pascal case:
Using pascal case, we write the first letter of each word in uppercase.

NumberOfBooks = 10;

Montchio Tabela A. v1.0 5


Declaring (creating) Variables
To create a variable, specify the type and assign it a value. It has the following syntax:
type variableName = value;
Example: Creating a variable called myNumber of type int and assigning the value 3 to it:

int myNumber = 3;

Above, the data-type is int, the variable name is myNumber and its value is 3. We can also create
a variable without assigning a value to it. In this case, we can assign the value later.

// Declare a variable
int myNumber;

// Assign a value to the variable myNumber


myNumber = 3;

Constants in C programming
If we want to create a variable whose data cannot be changed, we can declare it as a constant. This
will make the variable unchangeable and read-only. To create a constant, we can use the const
keyword.

const int myNumber = 3;// myNumber will always have the value 3

If we try to assign another value to myNumber, during compilation it will cause an error stating that
we cannot change its value as it is a constant.
We can use constants to declare variables that we know won’t change during program execution
such as the value of Pi, the number of minutes in an hour etc.

const int minutesPerHour = 60;


const float PI = 3.14;

VI) Operators in C programming


Operators are used to perform operations on variables and values. In the example below, we use
the + operator to add together two values:

Montchio Tabela A. v1.0 6


// add two values
int sum = 25 + 75;

// we can also add two


variables int firstNumber = 2;
int secondNumber = 5;
int sum = firstNumber + secondNumber;

// we can also add a variable to a value


int firstNumber = 2; int
sum = firstNumber + 36;
In C, we have several type of operators, namely:
● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Bitwise operators
- Arithmetic Operators:
Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

Adds together two


+ Addition x+y
values
Subtracts one value
- Subtraction x-y
from another
* Multiplication Multiplies two values x*y
Divides one value
/ Division x/y
by another
Returns the division
% Modulus x%y
remainder
Increases the value
++ Increment ++x
of a variable by 1
-- Decrement Decreases the value --x
of a variable by 1
- Assignment Operators
Assignment operators are used to assign values to variables.

Operator Description Example

Simple assignment
C = A + B will assign the
operator. Assigns values
value of A + B to C
from right side to left side

Montchio Tabela A. v1.0 7


+= Add AND assignment
operator. It adds the right C += A is equivalent to C =
side to the left and assigns C+A
the result to the left.

-= Subtract AND assignment


operator. It subtracts the C -= A is equivalent to C =
right side from the left and C-A
assigns the result to the left.

*= Multiply AND assignment


operator. It multiplies the C *= A is equivalent to C =
right side with the left and C*A
assigns the result to the left.

/= Divide AND assignment


operator. It divides the left C /= A is equivalent to C =
side with the right and C/A
assigns the result to the left.

%= Modulus AND assignment


operator. It takes modulus C %= A is equivalent to C
using the two operands and =
assigns the result to the left C%A
operand.
- Comparison Operators
Comparison operators are used to compare two values (or variables). The output of comparison
operators are the boolean values 0 or 1. 0 means the result is false and 1 means the result is true.
Assume x has the value 10 and y has the value 20.

Operator Name Example

== Equal to
x == y returns false
(0)

!= Not equal
x != y returns true
(1)

> Greater than


x > y returns false
(0)

Montchio Tabela A. v1.0 8


< Less than
x < y returns true
(1)

>= Greater than or equal to


x >= y returns false
(0)

<= Less than or equal to


x <= y returns true
(1)

- Logical Operators
We can also test for true or false values using logical operators. Consider x to have the value of 3
and y to have the value of 8

Name Description Example


Operato
r

&& Logical Returns true if both


x < 5 && y >
and statements are true
10 will return
false.

|| Logical or Returns true if one of the


x < 5 || y >
statements is true
10 will return
true.

! Logical Reverse the result, !(x < 5 && y >


not
returns false if the result 10) will return
is true true.

VII) Input and Output in C programming


When we import the stdio.h header library file to our code, we are able to receive input from the
user via the keyboard and also display the output to the user.

Displaying Output:
To output values or print text in C, you can use the printf() function:

Montchio Tabela A. v1.0 9


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

OUTPUT:

// we can also use multiple print statements.


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

OUTPUT:

/* Note that the second print state will be printed on the same line
as the first. A new line is not created.*/
Escape Character:
The backslash character ( \ ) is called an escape character. It is used with a second character to
escape the second character, meaning it tells the compiler not to attribute any special function to the
second character. Sometimes we can combine the escape character with special letters to tell the
compiler to carry out a particular function too. For example when used in combination with the letter
n, it tells the compiler to create a new line.
- \n : adds a new line
#include <stdio.h>

int main() { printf("Hello


World!\n");
printf("Hello
World!\n");
return 0;
}

OUTPUT:

Montchio Tabela A. v1.0 10


- \t : adds a tab space

#include <stdio.h >

int main() {
printf(" Hello World! \t");
printf(" I am learning C.");
return 0;
}

When using our print() function, we write what we want to print in double quotes. What if double quotes
is part of what we want to print, we can use the escape character to tell the compilers which double
quotes to ignore.
- \”: lets us use double quotes in our output

#include <stdio.h >


int main() {
printf( "His name is \" Kang \" .");
return 0;
}

OUTPUT:

Displaying Variables:
We can also output variables in C:

Montchio Tabela A. v1.0 11


#include <stdio.h>
int main() {
int number = 10;
printf("The number is %d", number);
return 0; }

/* notice we are using the integer format specifier %d to denote where


the integer variable should be printed */

OUTPUT:

/* we can also print multiple variables in the same print statement. */


#include <stdio.h>
int main() {
int firstNumber = 10; int
secondNumber = 20; float
decimalNumber = 25.9;
printf("The first number is %d and the second number is %d and the
decimal number is %f", firstNumber, secondNumber, decimalNumber);
return 0;
}

OUTPUT:

Receiving User Input:


We use the printf() function to display output. To receive user input, we use the scanf() function:

Montchio Tabela A. v1.0 12


#include <stdio.h >
int main() {
// Create an integer variable that will store the age of the user
int myAge;
// Ask the user to type their age
printf(" Type your age and press enter: \n ");
// Get the age and save it in the integer variable called myAge
scanf( "%d" , &myAge);
// Print the user’s age
printf(" Your age is: %d", myAge);
return 0;
}

OUTPUT:

The scanf() function takes two arguments: the format specifier of the variable (%d in the example
above) and the reference operator (&myAge), which stores the memory address of the variable.
Multiple Inputs:
The scanf() function also allows multiple inputs (an integer and a character in the following
example):

#include <stdio.h>
int main() {

// 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);
return 0;
}

OUTPUT:

Montchio Tabela A. v1.0 13


String Input:
Sometimes we may want to receive input, such as a user's name. To do this, we can use an array of
characters to store the name in.

#include <stdio.h>
int main() {
// Create a an array of 30 characters
char firstName[30];
// Ask the user to input some text
printf("Enter your first name: \n");
// Get and save the text
scanf("%s", firstName);
// Output the text
printf("Hello %s", firstName);
return 0;
}

OUTPUT:

Montchio Tabela A. v1.0 14


EXERCISE:
Write a simple calculator program that adds two numbers. This program takes two input numbers
from the user and outputs the results;

#include <stdio.h >


int main() {
// Calculator that adds two numbers
int firstNumber;
int secondNumber;
int sum;
printf(" Enter the first number: ");
scanf(" %d", &firstNumber);
printf(" Enter the second number: ");
scanf(" %d", &secondNumber);
sum = firstNumber + secondNumber;
printf(" The sum of %d and %d is %d", firstNumber, secondNumber,
sum);
return 0;
}

OUTPUT:

VIII) Conditional Statements in C programming


In programming, there are times when we want to carry out different actions based on a specific
condition. For example, if we want to write a program that should be used only by people 18 years
and above, we can use a condition to check if the person using the program is the required age.
In C programming, we use If and Switch statements to check for conditions.

If…Else Conditional statements:


In C, we can use the following:
● 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

Montchio Tabela A. v1.0 15


Syntax:
The if statement has the following syntax:

if (condition) {
// block of code to be executed if the condition is true
}
Example:

- Using if

#include <stdio.h>
int main() {
if (20 > 18) {
printf("20 is greater than 18");
} return
0;
}
OUTPUT:

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

- Using if..else
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:

Montchio Tabela A. v1.0 16


#include <stdio.h>
int main() {

int time = 20;


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

OUTPUT:

- Using if…else if
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: A program to check if a number is positive or negative.

Montchio Tabela A. v1.0 17


#include <stdio.h>
int main() {
int num = 10;
if (num > 0) {
printf("The value is a positive number.");
} else if (num < 0) {
printf("The value is a negative number.");
} else {
printf("The value is 0.");
}
return 0;
}

OUTPUT:

Exercise: Modify the program above to receive as input a number from the user then output if
the number is a positive or a negative number.
- Using the Ternary operator (shorthand if):
The ternary operator can be used to replace multiple lines of if else code with a single line.
The syntax of the ternary operator is:

(condition) ? expressionTrue : expressionFalse;

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

OUTPUT:

Switch…Case conditional statements:


Sometimes, we may have many conditions to check and instead of writing multiple if..else if
statements, it’s more readable to use a switch..case statement.

Syntax:
switch(expression) {

Montchio Tabela A. v1.0 18


case x: // code
block break;
case y: // code
block break;
default:
// code block
}
Points to note:
● 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 the code to run if there is no match

Example:

#include
<stdio.h> int
main() { int day
= 4; switch (day)
{

Montchio Tabela A. v1.0 19


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:

- Using 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;
default:
printf("Looking forward to the Weekend");
} return
0;
}

OUTPUT:

Montchio Tabela A. v1.0 20


IX) Looping and Iteration in C programming
Loops help us repeat an action multiple times as long as a specific condition remains true. In C, we
have the while loop, the do..while loop and the for loop. When a loop is executed once, we say the
loop has done one iteration. If the loop executes 10 times, we say the loop has done 10 iterations.

- While Loop
The while loop loops through a block of code as long as a specified condition is true. The while
loop is useful when we don’t know how many times we want to execute the specific action.
Syntax:
while (condition) {
// code block to be executed
}
Example: Write a program that prints the numbers from 1 to 5;

#include <stdio.h>
int main() {
int i = 1;
while (i < 6) {
printf("%d\n", i);
i++;
}
return 0;
}

OUTPUT:

- Do…While loop:
The difference between the while loop and the do..while loop is that the while loop checks
the condition before executing the code while the do while loop executes the code before checking
the condition.

Montchio Tabela A. v1.0 21


Syntax:
do {
// code block to be executed
}while (condition);
Example: Write a program to print all the numbers from 1 to 10;

#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d\n", i);
i++;
}
while (i < 11);
return 0;
}

OUTPUT:

- For loop:
The for loop is best used when we know exactly how many times we want to run a specific action.
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.

Example:

Montchio Tabela A. v1.0 22


#include <stdio.h>
int main() {
int i;
for (i = 1; i < 6; i++) {
printf("%d\n", i);
}

return 0;
}

OUTPUT:

- Nested Loops:
We can place a loop inside another loop. When we do this, we refer to it as nested loops.
We can nest any of the loops inside each other, e.g a while loop inside a for loop and vice
versa. We can also nest the same type of loops e.g a for loop inside a for loop or a while
loop inside another while loop.

Example:

#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) {
printf(" Inner: %d\n", j); // Executes 6 times (2 * 3)
}
} return
0;
}

OUTPUT:

Montchio Tabela A. v1.0 23


EXERCISE:
Write a program that prints all the even numbers between 1 and 19.
Solution:
To solve the problem above, we will use a loop to iterate through all the numbers from 1 to 19, then
inside the loop we will use a conditional statement to check if the number is even or not.

#include <stdio.h>
int main() {
int i;
for (i = 1; i < 20; i++) {
if (i % 2 == 0)
{ printf("%d\n", i);
}
}

return 0;
}

OUTPUT:

X) Break/Continue in C Programming
We can use the break keyword to stop the execution of a switch statement or a loop. Continue
breaks one iteration in the loop and continues with the next iteration.

Montchio Tabela A. v1.0 24


- Using Break
Example: Write a program that prints numbers from 1 to 10, and use a break statement to stop the
execution of the loop when the number has already printed 3 numbers..

#include <stdio.h>
int main() {
int i; for (i = 1; i <
11; i++) {
if (i == 4)
{ break; }
printf("%d\n", i);
} return
0;
}

OUTPUT:

- Using Continue
Example: Write a program that prints numbers from 0 to 9 but skips the number 4 while it is
executing.

#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
printf("%d\n", i);
} return
0;
}

OUTPUT:

Montchio Tabela A. v1.0 25


XI Arrays in C Programming
In C, each variable can only store one value. To store multiple values in the same variable, we use
an Array. We create/define arrays the same way we create normal variables with the exception that
we add square brackets to the name of the array.

- Creating an Array
Example: Create an array of integers containing the numbers 10,20,30,40,50.

int myNumbers[] = {10, 20, 30, 40, 50};

Above, the data-type is int, the name of the variable is myNumbers, notice the square brackets [ ],
indicating that it is an array. To add values to the array, we use curly brackets { } and separate each
value with a comma { 10, 20, 30, 40, 50 }. Here, we created an array and gave the array its
elements all at once. We can also create an array without assigning any elements during creation
but we have to indicate its size.

Example: Create an empty integer array that can hold 6 elements.

int myNumbers[6];

We can also create an array, denoting its size and also assigning values to it.

Example: Create an integer array that can hold 4 elements and assign the first two elements to it.

int myNumbers[4] = {10, 20};

- Accessing the elements of an Array


Each element in an array has a position, or an index number. The first element in an array is at
index 0 and so on and so forth. To access any element, we refer to its index number.

Montchio Tabela A. v1.0 26


Example: Access the third element of an array.

#include <stdio.h >


int main() {
int myNumbers[] = {25, 50, 75, 100};
printf("The third element is %d", myNumbers[2]);
return 0;
}
OUTPUT:

Recall that arrays start counting from 0. So the third element will be at position 2 (hint, count from 0
to 2 and see how many numbers you have).

- Changing an element in an Array


We can change the element in an array by using the index of the element.

Example: Using our previous array, change the value of the third element to 24.

#include <stdio.h >


int main() {
int myNumbers[] = {25, 50, 75, 100};
myNumbers[2] = 24;
printf("The third element is %d", myNumbers[2]);
return 0;
}
OUTPUT:

Exercise 1: Write a program that traverses an array. Note that traversing means going through
each element in an array and printing it.

#include <stdio.h> int main() { int


myNumbers[5] = {10, 20, 30, 40, 50}; int i;
for(i = 0; i < 5; i++)
{ printf("%d\t", myNumbers[i]);
} return
0;
}

Montchio Tabela A. v1.0 27


Exercise 2: Write a program that receives the ages of 10 students from the user and returns the
sum of the ages of the 10 students. Use an array to store the ages of the students.

#include <stdio.h >


int main() {
int studentAge[11];
int i, sum;
printf( "You will be asked to enter 10 ages.\n" );
for (i = 1; i <= 10 ; i++)
{
printf( "Enter the age for student %d:\n ", i);
scanf( "%d" , &studentAge[i]);
sum += studentAge[i];
}
printf( "The sum of all the ages is: %d", sum);
return 0;
}

OUTPUT:

Exercise 3: Write a program that takes an input the name of the user and then greets the user. Use
an array to store the name.

Montchio Tabela A. v1.0 28


#include <stdio.h>

int main() {
char userName[25];
printf( "What is your name:\n" );
scanf( "%s" , &userName);
printf( "\nHello %s, I wrote this in the C Programming Language." ,
userName);
return 0;
}

OUTPUT:

- Multi-Dimensional Arrays
So far, we have been dealing with one-dimensional arrays. In C, we can also perform operations on
multi-dimensional arrays. A multi-dimensional array is basically an array of arrays. An array can
have any number of dimensions. Here, we will limit ourselves to 2 dimensional arrays. A two
dimensional array is commonly referred to as a matrix.

Two-dimensional Arrays
A 2D array is also known as a matrix (a table of rows and columns). To create a 2D array of
integers, take a look at the following example:

int myNumbers[2][3] = { {1, 4, 2}, {3, 6, 8} };

In the example above, the first dimension represents the number of rows [2], while the second
dimension represents the number of columns [3]. The values are placed in row-order, and can be
visualized like this:

- Accessing Elements of a 2D array


To access an element of a two-dimensional array, we use the index of both the row and the
column.
Montchio Tabela A. v1.0 29
#include <stdio.h>
int main() {

int myNumbers[2][3] = { {1, 4, 2}, {3, 6, 8} };


printf("The element is %d", myNumbers[0][2]);
return 0;
}

OUTPUT:

Note that array indexes start from 0, that is [0] is the first element. [1] is the second element,
etc.

- Changing the elements of a 2D array


To change the element of a 2D array, we use the index of both the row and the column.

#include <stdio.h >


int main() {
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;
printf("The element is %d", matrix[0][0]);
return 0;
}

OUTPUT:

As you can see above, 9 is printed instead of 1.

- Traversing a 2D Array:

#include <stdio.h> int main() { int


matrix[2][3] = { {1, 4, 2}, {3, 6, 8} }; int
i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%d\n", matrix[i][j]);
}
} return
0;
}

OUTPUT:

Montchio Tabela A. v1.0 30


XII) Functions in C Programming
A function is a block of code that runs only when it is called. So far we have been writing our
programs in the function called main because this is the function that is automatically executed
when our program is executed. We can pass data, known as parameters or arguments, into a
function. Functions are used to perform certain actions, and they are important for reusing code:
Define the code once, and use it many times. A function must return something. A function which
does not return anything is known as a Procedure.

- Creating a Function
When creating a function, we have to indicate the return type of the function and the function name.
The return type of the function is the datatype of the value that is returned by the function.

returnType functionName() { // function body here


}

The data types are our return types.

int main() {
// function body here
return 0;
}
Each time we create the main function with a return type of int, we always have to return 0, because
0 is an integer and we must return something.
To create our main function or any function without returning anything, we use the return type void,
which means nothing.

void main() {
// function body here
}
The void keyword can be used to convert functions to procedures given that nothing is returned.

Montchio Tabela A. v1.0 31


- Calling a function
We don’t have to call the main function because this is done automatically as it is the entry point of
our program. However, when we create or declare any other function, we have to call it before it can
be executed. Note, we have to declare our function before calling it.
To call a function, we just need to write its name followed by two parentheses and a semicolon.

#include <stdio.h >


// Create a function
void myFunction() {
printf("I have been called!");
}

int main() {
myFunction(); // call the function
return 0;
}

OUTPUT:

We can call the function as many times as we like:

#include <stdio.h >


// Create a function
void myFunction() {
printf("I have been called!\n");
}

int main() {
myFunction();
myFunction();
myFunction();
return 0;
}

OUTPUT:

Note that we added a newline character so that each line is printed on a new line.

- Function parameters/arguments
We can give information to our functions via parameters. These parameters will serve as input to
the function. These parameters serve as variables inside our functions. We define parameters by
Montchio Tabela A. v1.0 32
including them inside our function definition and we can define as many parameters as we like, we
just have to separate them using commas.
Note that for each parameter, we follow the same rules we use when creating a variable: i.e, we
have to include its datatype and its name.

returnType functionName(datatype parameter1, datatype parameter2) {


// code to be executed
}

Example

#include <stdio.h >


void greetings(char name[]) {
printf("Hello %s\n", name);
}

int main() {
greetings("Muluh");
greetings("Awa");
greetings("Jam");
return 0;
}

OUTPUT:

As you can see above, our function greetings() takes in an array called name with a datatype of
char. The function then prints a Hello message with the name that was passed into the function. In
our main() function, we call the greetings() function three times, passing a different name each
time.

Exercise: Write a program that receives as input two numbers from the user, adds them and
returns the sum. The Addition functionality should be abstracted to a separate function.

#include <stdio.h> int


sum(int x, int y) {
return x + y;
}

int main() { int number1, number2;


printf("Enter two numbers: ");
scanf("%d %d", &number1,
&number2);
printf("Result is: %d", sum(number1,
number2)); return 0;
}
Montchio Tabela A. v1.0 33
In our code above, notice that in our main function we use number1 and number2 as our variable
names and in our sum() function we use x and y as our variable names. x and y only exist in the
sum() function and if we try to access them outside this function we will get an error. This is known
as the scope of the variable. A variable with global scope is a variable that can be accessed
anywhere in the program and a variable with a local scope is a variable that can only be accessed
in the block of code it is defined in. If we define a variable inside a loop, the variable will only exist
inside that loop.
In our code above, we are calling our sum() function inside the printf() statement.

- Declaring a function and defining it later


We can declare a function and define its body later. But note that we must always declare a function
before we can be able to call it without running into compilation errors.

#include <stdio.h> //
Function declaration
int sum(int, int);

int main()
{
int number1, number2;
printf("Enter two numbers: ");
scanf("%d %d", &number1,
&number2);
printf("Result is: %d",sum(number1,number2));
return 0;
}

// Function definition
int sum(int x, int y) {
return x + y;
}
Above, we declared the function sum(), and we defined it later below the main() function.

- XIII) Recursive functions in C programming


A recursive function is a function that calls itself while it is executing until a certain condition is met.
Recursion helps us break complicated problems into a simple function that can be called multiple
times until the problem is solved.
A recursive function has the following characteristics:
- Base case: The base case is the condition that determines when the function will stop
calling itself. It is usually the simplest form of the problem that can be solved without using
recursion.
- Recursive case: This the code that is executed each time the function calls itself. Each time
the recursive case is executed, it should move closer to the base case.

Example: Factorial numbers ( ! ):

Montchio Tabela A. v1.0 34


Factorial numbers are used widely in mathematics calculations. The factorial function denoted by
the exclamation symbol “!” indicates that we multiply all whole numbers from our chosen number
down to 1 e.g
The factorial formula can be written as:

n! = n * (n-1) * (n-2) * … * 1
Where n is any whole number e.g
1! = 1
2! = 2 * 1
3! = 3 * 2 * 1
4! = 4 * 3 * 2 * 1 5!
=5*4*3*2*1
e.t.c

With factorials, 1! Is always 1. We can also notice that when calculating the factorial of any
number, we are also calculating the factorial of the numbers before it. E.g we can rewrite our
factorials above as:
1! = 1 2!
= 2 * 1 3!
= 3* 2!
4! = 4 * 3!
5! = 5 * 4!
e.t.c
To program problems like the Factorial function in C, we can use the concept of recursive functions.

Montchio Tabela A. v1.0 35


#include <stdio.h>
int factorial(int n)
{
// base case
if (n == 0 || n == 1) {
return 1;
}
// recursive case else {
return n * factorial(n-1); }
}

int main() {
int number;
printf("Enter a positive number: ");
scanf("%d", &number);
printf("\n%d! = %d", number, factorial(number)); return
0;
}

OUTPUT:

In our code above, we have defined a function called factorial() which takes as input an integer. In
this function our base case is the simplest form of a factorial which indicates that if our integer is 0
or 1, then 1 should be returned else we multiply the integer by the factorial of the integer that comes
before it, hence calling the factorial() function again even though we are in the factorial() function.
This is what we mean by a function that is calling itself.
To explore how our function is being called, we can add a printf() statement to print something each
time our function is called.

Montchio Tabela A. v1.0 36


#include <stdio.h>
int factorial(int n)
{ printf("Calling the factorial function with input as %d\n", n);
// base case
if (n == 0 || n == 1) {
return 1;
} else { return n *
factorial(n-1);
}
}

int main() {
int number;
printf("Enter a positive number: ");
scanf("%d", &number); printf("\n%d! = %d",
number, factorial(number)); return 0;
}

OUTPUT:

- Mathematical functions in C
In C, for functions such as the square root function, calculating the sin, cos and tan, we can use
the standard math header library. This library already has functions written for the most commonly
used math functions.
To use these functions, we must import or include the math.h header file in our program:

#include <math.h>

- Square root function


Example: Calculate the square root of any number entered by the user.

Muluh MG Godson v1.0 37


#include <stdio.h>
#include <math.h>

int main() {
int n;
printf("Enter a number: ");

scanf( "%d" , &n);


printf( "The square root of %d is %f" , n, sqrt(n));
return 0;
}

OUTPUT:

To reduce the number of decimal places printed, we can use a precision specifier e.g %.2f is going
to print a floating point number with 2 decimal places. %.3f will print it with 1 decimal places etc.
Example:

printf( "The square root of %d is %.2f" , n, sqrt(n));

OUTPUT:

- Rounding a number
The ceil() function rounds a number upwards to the nearest integer while the floor() function rounds
a number down to the nearest integer.
Example: Write a program that rounds a number upwards and downwards.

1 =2*2*2=8

43 = 4 * 4 * 4 = 64
Montchio Tabela A. v1.0 38
#include <stdio.h>
#include <math.h>

int main() { printf("%f\n",


ceil(1.5)); printf("%f\n",
floor(1.5));
return 0;
}

OUTPUT:

As you can see above, the ceil() function rounds 1.5 to 2 and the floor() function rounds 1.5 to 1.

- Raising a number to any power


The pow() function returns the value of x to the power of y 𝑥𝑦:

e.g

2
2

=2*2=4

#include <stdio.h >


#include <math.h >

int main() {
printf( "%f" , pow( 4, 3));
return 0;
}

OUTPUT:

- Other Math Functions in the math.h library


Function Description

abs(x) Returns the absolute value of x

acos(x) Returns the arccosine of x

Muluh MG Godson v1.0 39


asin(x) Returns the arcsine of x

atan(x) Returns the arctangent of x

cbrt(x) Returns the cube root of x

cos(x) Returns the cosine of x

exp(x) Returns the value of Ex

sin(x) Returns the sine of x (x is in radians)

tan(x) Returns the tangent of an angle

XIV) Strings in C programming


When we combine letters or characters together, we form words. We can refer to these words as
strings. Earlier, we were using a character array to hold multiple letters together. In C programming,
we can use the string.h header library to be able to manipulate strings.

- Length of a string
To get the length of a string, we can use the strlen() function.

#include <string.h>
#include <stdio.h>

int main() {
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet));
return 0;
}

OUTPUT:

Montchio Tabela A. v1.0 40


- Concatenate strings
To concatenate strings means to combine them together. We use the strcat() function to
concatenate strings.

#include <stdio.h>
#include <string.h>

int main() {
char str1[20] = "Hello ";
char str2[] = "World!";
// Concatenate str2 to str1 (the result is stored in str1)
strcat(str1, str2); // Print str1 printf("%s", str1);
return 0;
}

OUTPUT:

- Copy one string into another


To copy one string into another, we use the strcpy() function.

#include <stdio.h>
#include <string.h>

int main() {
char str1[20] = "Hello";
char str2[20] = "World";
// Copy str1 to str2
strcpy(str2, str1); //
Print str2 printf("%s",
str2); return 0;

As you can see above, when we print the value of str2, instead of getting world we are getting
hello which is the value of str1. This is because we used the strcpy() function to copy the value of
str1 into str2.

Montchio Tabela A. v1.0 41


- Compare two strings
To compare if one string is the same as the other, we use the strcmp() function. If the result of this
function is 0, this means the strings are the same, any other number means the strings are different.
If the number returned is positive, this means the first string is greater than the second. If the
number returned is negative, this means the second string is greater than the first. The value
returned is the difference between the ASCII value of the first character in the strings that don’t
match. Example if we compare cat and car, the difference between the ASCII values of t and r is 2
and hence 2 or -2 will be returned depending on the order of the strings.

#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "Hi";

// Compare str1 and str2, and print the result printf("%d\n",


strcmp(str1, str2));

// Compare str1 and str3, and print the result printf("%d\n",


strcmp(str1, str3));

return 0;
}

OUTPUT:

As you can see, when we compare str1 and str2, we get 0 because the two strings are the same.
When we compare str1 and str3, the result is -4 because the two strings are different.

XV) Structures in C programming


Structures (also called structs) are a way to group several related variables into one place. Each
variable in the structure is known as a member of the structure. With arrays, the elements can only
be of the same data type but with structures we can have elements with different data types. A
structure is like a custom data type. Note that structures can also contain other structures.
- Creating a structure
We create a structure using the struct keyword and the members of the structure are created the
same way we create variables.

Montchio Tabela A. v1.0 42


struct structureName { // Structure declaration
dataType variableName; // Member
dataType variableName; // Member
};
Note the semicolon at the closing bracket of the structure definition.
Example: Create a structure called info that has as members the students name and age.

struct info { int


age; char
name[40]; };

To use our structure, we must create a variable using the structure as the data type of the variable.
Example: create a variable called person that is of the info structure we created earlier.

#include <stdio.h>

struct info {
int age; char
name[40];
};

int main() { struct


info Person; return
0;
}
To access the members of the structure, we use the dot-notation.
Example to access the age of the variable person, we can do Person.name and the age as
Person.age

#include <stdio.h>

struct info {
int age; char
name[40];
};

int main() { struct


info Person;
strcpy(Person.name, "Jam");
Person.age = 17;
printf("The name is %s and the age is %d", Person.name, Person.age);
return 0;
}

Montchio Tabela A. v1.0 43


OUTPUT:

Notice that we are using the strcpy() function to assign the name to the character array called
name.

We can also assign values to a structure when we create it.

struct info Person = {17, "Jam"};

Practice Exercises:
1) Write a program that takes the name, age and height of 5 students and prints the information
in a tabular manner. The height should be limited to 2 decimal places.

2) Write a program to find the roots of a quadratic equation 𝑎𝑥2 + 𝑏𝑥 + 𝑐 = 0, where a, b

and c are real numbers and a is not 0

3) Write a program that prints the following pyramids:

Half pyramid of stars

Half pyramid of numbers

Montchio Tabela A. v1.0 44


Half pyramid of letters

4) A simple calculator that can perform addition, subtraction, division and multiplication. The
program should receive as input two numbers from the user and the operation to be carried
out. Then prints the result.
5) Write a program that prints the factors of a positive number. The program should receive as
input a positive number from the user and then print all its factors.

6) Write a program to check if a number is a palindrome. A palindrome is a number which is the


same when it is reversed. e.g 1001 is a palindrome because if we start writing it backwards
(from the last number to the first), we still end up with 1001.

7) Write a program that can be used to search for a number in an array of numbers using the
sequential search algorithm.

8) Write a program that can be used to sort numbers in ascending order. The program should
receive different numbers from the user and then arrange the numbers from the smallest to
the biggest. You can use the bubble sort algorithm to implement this.

9) Write the sorting program using the Merge sort algorithm.

10) Write a searching program using the binary search algorithm. The program should first sort
the numbers using the merge sort algorithm before searching.

11) The Tower of Hanoi is a mathematical puzzle where we have three rods (1, 2, and 3) and N
disks. Initially, all the disks are stacked in decreasing value of diameter i.e the smallest disk is
placed on the top and they are on rod 1. The objective of the puzzle is to move the entire
stack to another rod (here considered 3), obeying the following simple rules:
● Only one disk can be moved at a time.
● Each move consists of taking the upper disk from one of the stacks and placing it on
top of another stack i.e. a disk can only be moved if it is the uppermost disk on a
stack.
● No disk may be placed on top of a smaller disk.

Montchio Tabela A. v1.0 45


Write a program that can solve this puzzle for any number of disks.

12) You are a software developer working for a company that sells car parts.

Your manager has assigned you to write a C program to keep track of inventory for the
company's warehouses. The program should allow the user to add new parts to inventory,
update existing parts, remove parts, and display the current inventory.
Exercise:
Write a C program that uses structures to represent car parts. Each part should have the
following attributes: part number, part name, quantity in stock, and price. The program
should allow the user to perform the following actions:
● Add a new part to inventory
● Update an existing part's quantity or price
● Remove a part from inventory
● Display the current inventory
The program should be able to handle a maximum of 100 parts in inventory, and should not
use dynamic memory allocation.

Montchio Tabela A. v1.0 46


Note: You may also want to include input validation to ensure that the user enters valid
values for part numbers, quantities, and prices.
13) You work for a software company that develops video games. Your manager has assigned
you to work on a project for a new game that involves managing a virtual zoo.

Your task is to develop a program that allows players to keep track of the animals in their
zoo, including their names, species, and feeding schedule.
Exercise:
Create a C program that defines a structure called "Animal" with the following properties:
- name (a string)
- species (a string)
- feeding schedule (an integer representing the number of times per day the animal
should be fed)
● Create a function that takes user input to create a new animal struct and add it to an
array of animals.
● Create a function that takes user input to search for a specific animal by name, and
then prints out its properties.
● Create a function that takes user input to update the feeding schedule of a specific
animal by name.
● Create a function that takes user input to delete an animal from the array of animals.
● Add a menu to the program that allows the user to select between adding a new
animal, searching for an animal, updating an animal's feeding schedule, deleting an
animal, and exiting the program.
● Test the program by creating a few animals and testing all of the functions.

END

Montchio Tabela A. v1.0 47

You might also like