C Programming Course
C Programming Course
CRASH COURSE
Montchio Tabela Abigael
NAME 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.
#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.
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:
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:
We can also write single line comments on the same line as our C statements:
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!");
int
2 or 4 Stores whole numbers, without decimals
bytes
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
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:
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;
● 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;
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;
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.
Simple assignment
C = A + B will assign the
operator. Assigns values
value of A + B to C
from right side to left side
== Equal to
x == y returns false
(0)
!= Not equal
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
Displaying Output:
To output values or print text in C, you can use the printf() function:
OUTPUT:
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>
OUTPUT:
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
OUTPUT:
Displaying Variables:
We can also output variables in C:
OUTPUT:
OUTPUT:
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() {
OUTPUT:
#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:
OUTPUT:
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:
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:
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 }
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:
#include <stdio.h>
int main() {
int time = 20;
(time < 18) ? printf("Good day.") : printf("Good evening.");
return 0;
}
OUTPUT:
Syntax:
switch(expression) {
Example:
#include
<stdio.h> int
main() { int day
= 4; switch (day)
{
OUTPUT:
#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:
- 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.
#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:
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
OUTPUT:
#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.
#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:
- Creating an Array
Example: Create an array of integers containing the numbers 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.
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.
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).
Example: Using our previous array, change the value of the third element to 24.
Exercise 1: Write a program that traverses an array. Note that traversing means going through
each element in an array and printing it.
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.
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:
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:
OUTPUT:
Note that array indexes start from 0, that is [0] is the first element. [1] is the second element,
etc.
OUTPUT:
- Traversing a 2D Array:
OUTPUT:
- 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.
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.
int main() {
myFunction(); // call the function
return 0;
}
OUTPUT:
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.
Example
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> //
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.
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.
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.
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>
int main() {
int n;
printf("Enter a number: ");
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:
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>
OUTPUT:
As you can see above, the ceil() function rounds 1.5 to 2 and the floor() function rounds 1.5 to 1.
e.g
2
2
=2*2=4
int main() {
printf( "%f" , pow( 4, 3));
return 0;
}
OUTPUT:
- 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:
#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:
#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.
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "Hi";
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.
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];
};
#include <stdio.h>
struct info {
int age; char
name[40];
};
Notice that we are using the strcpy() function to assign the name to the character array called
name.
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.
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.
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.
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.
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.
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