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

C-Notes

C is a general-purpose programming language created in 1972, known for its speed and versatility, widely used in various applications including operating systems. The tutorial covers the basics of C programming, including syntax, variables, data types, and how to use an IDE for coding. It emphasizes the importance of understanding format specifiers for outputting variables and provides examples to illustrate key concepts.

Uploaded by

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

C-Notes

C is a general-purpose programming language created in 1972, known for its speed and versatility, widely used in various applications including operating systems. The tutorial covers the basics of C programming, including syntax, variables, data types, and how to use an IDE for coding. It emphasizes the importance of understanding format specifiers for outputting variables and provides examples to illustrate key concepts.

Uploaded by

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

Learn C

C is a general-purpose programming language, developed in 1972, and still quite popular.

C is very powerful; it has been used to develop operating systems, databases, applications, etc.

Examples in Each Chapter


Our Try it Yourself tool makes it easy to learn C. You can edit code and view the result in your browser:

Example
#include <stdio.h>

int main() {

printf("Hello World!");

return 0;

}
C Introduction
What is C?
C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972.

It is a very popular language, despite being old.

C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Why Learn C?
 It is one of the most popular programming language in the world
 If you know C, you will have no problem to learn other popular programming languages such as Java,
Python, C++, C#, etc, as the syntax is similar
 C is very fast, compared to other programming languages, like Java and Python
 C is very versatile; it can be used in both applications and technologies

Difference between C and C++


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

Get Started
This tutorial will teach you the very basics of C.

It is not necessary to have any prior programming experience.


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

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


 A compiler, like GCC, to translate the C code into a language that the computer will understand

There are many text editors and compilers to choose from. In this tutorial, we will use an IDE (see below).

C Install IDE
An IDE (Integrated Development Environment) is used to edit AND compile the code.

Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free, and they can be used to both edit
and debug C code.

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

We will use Code::Blocks in our tutorial, which we believe is a good place to start.

You can find the latest version of Codeblocks at http://www.codeblocks.org/downloads/26. Download the mingw-
setup.exe file, which will install the text editor with a compiler.

C Quickstart
Let's create our first C file.

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

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

myfirstprogram.c
#include <stdio.h>

int main() {
printf("Hello World!");
return 0;
}

Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, focus on
how to run the code.

In Codeblocks, it should look like this:


Then, go to Build > Build and Run to run (execute) the program. The result will look something to this:

Hello World!
Process returned 0 (0x0) execution time : 0.011 s
Press any key to continue.

Congratulations! You have now written and executed your first C program.
C Syntax
Syntax
You have already seen the following code a couple of times in the first chapters. Let's break it down to understand
it better:

Example
#include <stdio.h>

int main() {

printf("Hello World!");

return 0;

Example explained

Line 1: #include <stdio.h> is a header file library that lets us work with input and output functions, such
as printf() (used in line 4). Header files add functionality to C++ programs.

Don't worry if you don't understand how #include <stdio.h> works. Just think of it as something that (almost)
always appears in your program.

Line 2: A blank line. C ignores white space. But we use it to make the code more readable.

Line 3: Another thing that always appear in a C program, is main(). This is called a function. Any code inside its
curly brackets {} will be executed.

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

Note that: Every C statement ends with a semicolon ;

Note: The body of int main() could also been written as:
int main(){printf("Hello World!");return 0;}

Remember: The compiler ignores white spaces. However, multiple lines makes the code more readable.

Line 5: return 0 ends the main() function.

Line 6: Do not forget to add the closing curly bracket } to actually end the main function.
C Output (Print Text)
Output (Print Text)
The printf() function is used to output values/print text:

Example
#include <stdio.h>

int main() {

printf("Hello World!");

return 0;

You can add as many printf() functions as you want. However, note that it does not insert a new line at the end
of the output:

Example
#include <stdio.h>

int main() {

printf("Hello World!");

printf("I am learning C.");

return 0;

}
C New Lines
New Lines
To insert a new line, you can use the \n character:

Example
#include <stdio.h>

int main() {

printf("Hello World!\n");

printf("I am learning C.");

return 0;

You can also output multiple lines with a single printf() function. However, be aware that this will make the code
harder to read:

Example
#include <stdio.h>

int main() {

printf("Hello World!\nI am learning C.\nAnd it is awesome!");

return 0;

}
Tip: Two \n characters after each other will create a blank line:

Example
#include <stdio.h>

int main() {

printf("Hello World!\n\n");

printf("I am learning C.");

return 0;

What is \n exactly?

The newline character (\n) is called an escape sequence, and it forces the cursor to change its position to the
beginning of the next line on the screen. This results in a new line.

Examples of other valid escape sequences are:

Escape Sequence Description

\t Creates a horizontal tab

\\ Inserts a backslash character (\)

\" Inserts a double quote character

\t Example

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

printf("Hello World!\t");

printf("I am learning C.");

return 0;

\\ Example

#include <stdio.h>

int main() {

printf("Hello World!\\");

printf("I am learning C.");

return 0;

\” Example

#include <stdio.h>

int main() {

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

return 0;

}
C Comments
Comments in C
Comments can be used to explain code, and to make it more readable. It can also be used to prevent execution
when testing alternative code.

Comments can be singled-lined or multi-lined.

Single-line Comments
Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will not be executed).

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

Example
#include <stdio.h>

int main() {

// This is a comment

printf("Hello World!");

return 0;

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

Example
#include <stdio.h>

int main() {

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


return 0;

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

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

Example
#include <stdio.h>

int main() {

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

to the screen, and it is amazing */

printf("Hello World!");

return 0;

Single or multi-line comments?

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

Good to know: Before version C99 (released in 1999), you could only use multi-line comments in C.
C Variables
Variables are containers for storing data values.

In C, there are different types of variables (defined with different keywords), for example:

 int - stores integers (whole numbers), without decimals, such as 123 or -123
 float - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes

Declaring (Creating) Variables


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

Syntax
type variableName = value;

Where type is one of C types (such as int), and variableName is the name of the variable (such as x or myName).
The equal sign is used to assign a value to the variable.

So, to create a variable that should store a number, look at the following example:

Example
Create a variable called myNum of type int and assign the value 15 to it:

int myNum = 15;

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

Example
intmyNum;
myNum = 15;

Note: If you assign a new value to an existing variable, it will overwrite the previous value:

Example
intmyNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10

Output Variables
you can output values/print text with the printf() function:
Example
#include <stdio.h>

int main() {

printf("Hello World!");

return 0;

In many other programming languages (like Python, Java, and C++), you would normally use a print function to
display the value of a variable too. However, this is not possible in C:

Example
#include <stdio.h>

int main() {

int myNum = 15;

printf(myNum);

return 0;

To output variables in C, you must get familiar with something called "format specifiers".

Format Specifiers
Format specifiers are used together with the printf() function to tell the compiler what type of data the variable is
storing. A format specifier starts with a percentage sign %, followed by a character.

For example, to output the value of an int variable, you must use the format specifier %d or %i surrounded by
double quotes, inside the printf() function:

Example
#include <stdio.h>

int main() {

int myNum = 15;

printf("%d", myNum);

return 0;

To print other types, use the format specifier %c for char and %f for float:

Example
#include <stdio.h>

int main() {

// Create variables

int myNum = 5; // Integer (whole number)

float myFloatNum = 5.99; // Floating point number

char myLetter = 'D'; // Character

// Print variables

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

printf("%f\n", myFloatNum);

printf("%c\n", myLetter);

return 0;

}
Add Variables Together
To add a variable to another variable, you can use the + operator:

Example
#include <stdio.h>

int main() {

int x = 5;

int y = 6;

int sum = x + y;

printf("%d", sum);

return 0;

Declare Multiple Variables


To declare more than one variable of the same type, use a comma-separated list:

Example
#include <stdio.h>

int main() {

int x = 5, y = 6, z = 50;

printf("%d", x + y + z);

return 0;
}

You can also assign the same value to multiple variables of the same type:

Example
#include <stdio.h>

int main() {

int x, y, z;

x = y = z = 50;

printf("%d", x + y + z);

return 0;

C Variable Names
All C variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

Note: It is recommended to use descriptive names in order to create understandable and maintainable code:

Example
// Good
int minutesPerHour = 60;

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


int m = 60;

The general rules for naming variables are:

 Names can contain letters, digits and underscores


 Names must begin with a letter or an underscore (_)
 Names are case sensitive (myVar and myvar are different variables)
 Names cannot contain whitespaces or special characters like !, #, %, etc.
 Reserved words (such as int) cannot be used as names
C Data Types
Data Types
As explained in the Variables chapter, a variable in C must be a specified data type, and you must use
a format specifier inside the printf() function to display it:

Example
#include <stdio.h>

int main() {

// Create variables

int myNum = 5; // Integer (whole number)

float myFloatNum = 5.99; // Floating point number

char myLetter = 'D'; // Character

// Print variables

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

printf("%f\n", myFloatNum);

printf("%c\n", myLetter);

return 0;

Basic Data Types


The data type specifies the size and type of information the variable will store.

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


Data 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 7 decimal digits

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


Sufficient for storing 15 decimal digits

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

Basic Format Specifiers


There are different format specifiers for each data type. Here are some of them:

Format Specifier Data Type

or %i int
%d

%f float

%lf double

%c char

%s Used for strings,

%d or %i Example
#include <stdio.h>

int main() {

int myNum = 5; // integer

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

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

return 0;

%f Example

#include <stdio.h>

int main() {

float myFloatNum = 5.99; // Floating point number

printf("%f", myFloatNum);

return 0;

%lf Example

#include <stdio.h>

int main() {
double myDoubleNum = 19.99; // Double (floating point number)

printf("%lf", myDoubleNum);

return 0;

%c Example

#include <stdio.h>

int main() {

char myLetter = 'D'; // Character

printf("%c", myLetter);

return 0;

%s Example

#include <stdio.h>

int main() {

char greetings[] = "Hello World!";

printf("%s", greetings);

return 0;
}

C Constants
Constants
When you don't want others (or yourself) to override existing variable values, use the const keyword (this will
declare the variable as "constant", which means unchangeable and read-only):

Example
#include <stdio.h>

int main() {

const int myNum = 15;

myNum = 10;

printf("%d", myNum);

return 0;

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

Example
#include <stdio.h>

int main() {

const int minutesPerHour = 60;


const float PI = 3.14;

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

printf("%f\n", PI);

return 0;

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

Example
Like this:

const int minutesPerHour = 60;

This however, will not work:

#include <stdio.h>

int main() {

const int minutesPerHour;

minutesPerHour = 60;

printf("%d", minutesPerHour);

return 0;

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

Example
#include <stdio.h>

int main() {

const int BIRTHYEAR = 1980;

printf("%d", BIRTHYEAR);

return 0;

C Operators
Operators
Operators are used to perform operations on variables and values.

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

Example
#include <stdio.h>

int main() {

int myNum = 100 + 50;


printf("%d", myNum);

return 0;

Although the + operator is often used to add together two values, like in the example above, it can also be used to
add together a variable and a value, or a variable and another variable:

Example
#include <stdio.h>

int main() {

int sum1 = 100 + 50; // 150 (100 + 50)

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

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

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

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

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

return 0;

C divides the operators into the following groups:

 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

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

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


1

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


1

+ Example

#include <stdio.h>

int main() {

int x = 5;

int y = 3;
printf("%d", x + y);

return 0;

- Example
#include <stdio.h>

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

* Example

#include <stdio.h>

int main() {

int x = 5;

int y = 3;

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

return 0;

/ Example

#include <stdio.h>

int main() {
int x = 12;

int y = 3;

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

return 0;

% Example

#include <stdio.h>

int main() {

int x = 5;

int y = 2;

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

return 0;

++ Example

#include <stdio.h>

int main() {

int x = 5;

printf("%d", ++x);

return 0;

}
-- Example

#include <stdio.h>

int main() {

int x = 5;

printf("%d", --x);

return 0;

Assignment Operators
Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:

Example
#include <stdio.h>

int main() {

int x = 10;

printf("%d", x);

return 0;

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

Example
#include <stdio.h>

int main() {

int x = 10;

x += 5;

printf("%d", x);

return 0;

A list of all assignment operators:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3


|= x |= 3 x=x|3

^= x ^= 3 x=x^3

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

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

= Example

#include <stdio.h>

int main() {

int x = 5;

printf("%d", x);

return 0;

+= Example

#include <stdio.h>

int main() {

int x = 5;

x += 3;

printf("%d", x);

return 0;
}

-= Example

#include <stdio.h>

int main() {

int x = 5;

x -= 3;

printf("%d", x);

return 0;

*= Example

#include <stdio.h>

int main() {

int x = 5;

x *= 3;

printf("%d", x);

return 0;

/= Example

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

float x = 5;

x /= 3;

printf("%f", x);

return 0;

%= Example

#include <stdio.h>

int main() {

int x = 5;

x %= 3;

printf("%d", x);

return 0;

&= Example

#include <stdio.h>

int main() {

int x = 5;

x &= 3;
printf("%d", x);

return 0;

|= Example

#include <stdio.h>

int main() {

int x = 5;

x |= 3;

printf("%d", x);

return 0;

^= Example

#include <stdio.h>

int main() {

int x = 5;

x ^= 3;

printf("%d", x);

return 0;

}
>>= Example

#include <stdio.h>

int main() {

int x = 5;

x >>= 3;

printf("%d", x);

return 0;

<< = Example

#include <stdio.h>

int main() {

int x = 5;

x <<= 3;

printf("%d", x);

return 0;

Comparison Operators
Comparison operators are used to compare two values.

Note: The return value of a comparison is either true (1) or false (0).

In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:

Example
#include <stdio.h>

int main() {

int x = 5;

int y = 3;

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

return 0;

A list of all comparison operators:

Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

== Example

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

int x = 5;

int y = 3;

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

return 0;

!= Example

#include <stdio.h>

int main() {

int x = 5;

int y = 3;

printf("%d", x != y); // returns 1 (true) because 5 is not equal to 3

return 0;

> Greater than Example

#include <stdio.h>

int main() {

int x = 5;

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

return 0;

< Example

#include <stdio.h>

int main() {

int x = 5;

int y = 3;

printf("%d", x < y); // returns 0 (false) because 5 is not less than 3

return 0;

>= Example

#include <stdio.h>

int main() {

int x = 5;

int y = 3;

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

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

return 0;
}

<= Example

#include <stdio.h>

int main() {

int x = 5;

int y = 3;

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

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

return 0;

Logical Operators
Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical Returns true if both statements are x < 5 && x <
and true 10

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


true

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

#include <stdio.h>

int main() {

int x = 5;

int y = 3;

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

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

return 0;

|| Example

#include <stdio.h>

int main() {

int x = 5;

int y = 3;

// Returns 1 (true) because one of the conditions are true (5 is greater than 3, but 5 is not less
than 4)

printf("%d", x > 3 || x < 4);

return 0;
}

! Example

#include <stdio.h>

int main() {

int x = 5;

int y = 3;

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

printf("%d", !(x > 3 && x < 10));

return 0;

Sizeof Operator
The memory size (in bytes) of a data type or a variable can be found with the sizeof operator:

Example
#include <stdio.h>

int main() {

int myInt;

float myFloat;

double myDouble;

char myChar;
printf("%lu\n", sizeof(myInt));

printf("%lu\n", sizeof(myFloat));

printf("%lu\n", sizeof(myDouble));

printf("%lu\n", sizeof(myChar));

return 0;

Note that we use the %lu format specifer to print the result, instead of %d. It is because the compiler expects the
sizeof operator to return a long unsigned int (%lu), instead of int (%d). On some computers it might work with %d,
but it is safer to use %lu.

C If ... Else
Conditions and If Statements
You learned from the operators comparison chapter, that C supports the usual logical conditions from
mathematics:

 Less than: a < b


 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

C has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is true


 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed
The if Statement
Use the if statement to specify a block of C code to be executed if a condition is true.

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

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some
text:

Example
#include <stdio.h>

int main() {

if (20 > 18) {

printf("20 is greater than 18");

return 0;

We can also test variables:

Example
#include <stdio.h>

int main() {

int x = 20;

int y = 18;

if (x > y) {

printf("x is greater than y");

}
return 0;

Example explained

In the example above we use two variables, x and y, to test whether x is greater than y (using the > operator). As
x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that "x is greater than y".

The else Statement


Use the else statement to specify a block of code to be executed if the condition is false.

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

Example
#include <stdio.h>

int main() {

int time = 20;

if (time < 18) {

printf("Good day.");

} else {

printf("Good evening.");

return 0;

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

The else if Statement


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

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

Example
#include <stdio.h>

int main() {

int time = 22;

if (time < 10) {

printf("Good morning.");

} else if (time < 20) {

printf("Good day.");

} else {

printf("Good evening.");

return 0;

Example explained

In the example above, time (22) is greater than 10, so the first condition is false. The next condition, in the else
if statement, is also false, so we move on to the else condition since condition1 and condition2 is both false -
and print to the screen "Good evening".
However, if the time was 14, our program would print "Good day."

C Short Hand If Else


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

Syntax
variable = (condition) ? expressionTrue : expressionFalse;

Instead of writing:

Example
#include <stdio.h>

int main() {

int time = 20;

if (time < 18) {

printf("Good day.");

} else {

printf("Good evening.");

return 0;

You can simply write:

Example
#include <stdio.h>

int main() {
int time = 20;

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

return 0;

C Switch
Switch Statement
Instead of writing many if..else statements, you can use the switch statement.

The switch statement selects one of many code blocks to be executed:

Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

This is how it works:

 The switch expression is evaluated once


 The value of the expression is compared with the values of each case
 If there is a match, the associated block of code is executed
 The break statement breaks out of the switch block and stops the execution
 The default statement is optional, and specifies some code to run if there is no case match

The example below uses the weekday number to calculate the weekday name:

Example
#include <stdio.h>

int main() {

int day = 4;
switch (day) {

case 1:

printf("Monday");

break;

case 2:

printf("Tuesday");

break;

case 3:

printf("Wednesday");

break;

case 4:

printf("Thursday");

break;

case 5:

printf("Friday");

break;

case 6:

printf("Saturday");

break;

case 7:

printf("Sunday");

break;

}
return 0;

The break Keyword


When C reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no need for more testing.

A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch
block.

The default Keyword


The default keyword specifies some code to run if there is no case match:

Example
#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;

Note: The default keyword must be used as the last statement in the switch, and it does not need a break.

C While Loop
Loops
Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

While Loop
The while loop loops through a block of code as long as a specified condition is true:

Syntax
while (condition) {
// code block to be executed
}

In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

Example
#include <stdio.h>

int main() {

int i = 0;
while (i < 5) {

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

i++;

return 0;

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

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the
condition is true, then it will repeat the loop as long as the condition is true.

Syntax
do {
// code block to be executed
}
while (condition);

The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is
false, because the code block is executed before the condition is tested:

Example
#include <stdio.h>

int main() {

int i = 0;
do {

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

i++;

while (i < 5);

return 0;

Do not forget to increase the variable used in the condition, otherwise the loop will never end!

C For Loop
For Loop
When you know exactly how many times you want to loop through a block of code, use the for loop instead of
a while loop:

Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}

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

Statement 2 defines the condition for executing the code block.

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

The example below will print the numbers 0 to 4:


Example
#include <stdio.h>

int main() {

int i;

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

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

return 0;

Example explained

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

Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will
start over again, if it is false, the loop will end.

Statement 3 increases a value (i++) each time the code block in the loop has been executed.

Another Example
This example will only print even values between 0 and 10:

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

int i;

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

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

return 0;

C Break and Continue


Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of
a switch statement.

The break statement can also be used to jump out of a loop.

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

Example
#include <stdio.h>

int main() {

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

if (i == 4) {

break;

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

return 0;

Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the
next iteration in the loop.

This example skips the value of 4:

Example
#include <stdio.h>

int main() {

int i;

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

if (i == 4) {
continue;

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

return 0;

Break and Continue in While Loop


You can also use break and continue in while loops:

Break Example
#include <stdio.h>

int main() {

int i = 0;

while (i < 10) {

if (i == 4) {

break;
}

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

i++;

return 0;

Continue Example
#include <stdio.h>

int main() {

int i = 0;

while (i < 10) {

i++;

if (i == 4) {

continue;

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

return 0;
}

C Arrays
Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To create an array, define the data type (like int) and specify the name of the array followed by square brackets
[].

To insert values to it, use a comma-separated list, inside curly braces:

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

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

Access the Elements of an Array


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

Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

This statement accesses the value of the first element [0] in myNumbers:

Example
#include <stdio.h>

int main() {

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


printf("%d", myNumbers[0]);

return 0;

Change an Array Element


To change the value of a specific element, refer to the index number:

Example
myNumbers[0] = 33;

Example
#include <stdio.h>

int main() {

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

myNumbers[0] = 33;

printf("%d", myNumbers[0]);

return 0;

Loop Through an Array


You can loop through the array elements with the for loop.

The following example outputs all elements in the myNumbers array:


Example
#include <stdio.h>

int main() {

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

int i;

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

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

return 0;

Set Array Size


Another common way to create arrays, is to specify the size of the array, and add elements later:

Example
#include <stdio.h>

int main() {

// Declare an array of four integers:

int myNumbers[4];
// Add elements to it

myNumbers[0] = 25;

myNumbers[1] = 50;

myNumbers[2] = 75;

myNumbers[3] = 100;

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

return 0;

Using this method, you have to know the size of the array, in order for the program to store enough memory.

You are not able to change the size of the array after creation.

C Strings
Strings
Strings are used for storing text/characters.

For example, "Hello World" is a string of characters.

Unlike many other programming languages, C does not have a String type to easily create string variables.
However, you can use the char type and create an array of characters to make a string in C:

char greetings[] = "Hello World!";

Note that you have to use double quotes.

To output the string, you can use the printf() function together with the format specifier %s to tell C that we are
now working with strings:

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

char greetings[] = "Hello World!";

printf("%s", greetings);

return 0;

Access Strings
Since strings are actually arrays in C, you can access a string by referring to its index number inside square
brackets [].

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

Example
#include <stdio.h>

int main() {

char greetings[] = "Hello World!";

printf("%c", greetings[0]);

return 0;

Note that we have to use the %c format specifier to print a single character.

Modify Strings
To change the value of a specific character in a string, refer to the index number, and use single quotes:

Example
#include <stdio.h>

int main() {

char greetings[] = "Hello World!";

greetings[0] = 'J';

printf("%s", greetings);

return 0;

Another Way Of Creating Strings


In the examples above, we used a "string literal" to create a string variable. This is the easiest way to create a
string in C.

You should also note that you can to create a string with a set of characters. This example will produce the same
result as the one above:

Example
#include <stdio.h>

int main() {

char greetings[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0'};

char greetings2[] = "Hello World!";

printf("%s\n", greetings);

printf("%s\n", greetings2);
return 0;

Why do we include the \0 character at the end? This is known as the "null termininating character", and must
be included when creating strings using this method. It tells C that this is the end of the string.

Differences
The difference between the two ways of creating strings, is that the first method is easier to write, and you do not
have to include the \0 character, as C will do it for you.

You should note that the size of both arrays is the same: They both have 13 characters (space also counts as a
character by the way), including the \0 character:

Example
#include <stdio.h>

int main() {

char greetings[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0'};

char greetings2[] = "Hello World!";

printf("%lu\n", sizeof(greetings));

printf("%lu\n", sizeof(greetings2));

return 0;

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

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

Example
Output a number entered by the user:

#include <stdio.h>

int main() {

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

int myNum;

// Ask the user to type a number

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

// Get and save the number the user types

scanf("%d", &myNum);

// Print the number the user typed

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

return 0;

}
The scanf() function takes two arguments: the format specifier of the variable (%d in the example

above) and the reference operator (&myNum), which stores the memory address of the variable. User
Input Strings
You can also get a string entered by the user:

Example
Output the name of a user:

#include <stdio.h>

int main() {

// Create a string

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;

}
Note that you must specify the size of the string/array (we used a very high number, 30, but atleast then we are
certain it will store enough characters for the first name), and you don't have to specify the reference operator (&)
when working with strings in scanf().

C Memory Address
Memory Address
When a variable is created in C, a memory address is assigned to the variable.

The memory address is the location of where the variable is stored on the computer.

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

To access it, use the reference operator (&), and the result will represent where the variable is stored:

Example
#include <stdio.h>

int main() {

int myAge = 43;

printf("%p", &myAge);

return 0;

Note: The memory address is in hexadecimal form (0x..). You probably won't get the same result in your program.

You should also note that &myAge is often called a "pointer". A pointer basically stores the memory address of a
variable as its value. To print pointer values, we use the %p format specifier.

Why is it useful to know the memory address?

Pointers are important in C, because they give you the ability to manipulate the data in the computer's memory -
this can reduce the code and improve the performance.
Pointers are one of the things that make C stand out from other programming languages, like Python and Java.

C Pointers
Creating Pointers
You learned from the previous chapter, that we can get the memory address of a variable with the reference
operator &:

Example
#include <stdio.h>

int main() {

int myAge = 43;

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

printf("%p\n", &myAge);

return 0;

In the example above, &myAge is also known as a pointer.

A pointer is a variable that stores the memory address of another variable as its value.

A pointer variable points to a data type (like int) of the same type, and is created with the * operator. The
address of the variable you're working with is assigned to the pointer:

Example
#include <stdio.h>

int main() {

int myAge = 43; // An int variable


int* ptr = &myAge; // A pointer variable, with the name ptr, that stores the address of myAge

// Output the value of myAge (43)

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

// Output the memory address of myAge (0x7ffe5367e044)

printf("%p\n", &myAge);

// Output the memory address of myAge with the pointer (0x7ffe5367e044)

printf("%p\n", ptr);

return 0;

Example explained

Create a pointer variable with the name ptr, that points to an int variable (myAge). Note that the type of the
pointer has to match the type of the variable you're working with.

Use the & operator to store the memory address of the myAge variable, and assign it to the pointer.

Now, ptr holds the value of myAge's memory address.

Dereference
In the example above, we used the pointer variable to get the memory address of a variable (used together with
the & reference operator).

However, you can also get the value of the variable the pointer points to, by using the * operator
(the dereference operator):
Example
#include <stdio.h>

int main() {

int myAge = 43; // Variable declaration

int* ptr = &myAge; // Pointer declaration

// Reference: Output the memory address of myAge with the pointer (0x7ffe5367e044)

printf("%p\n", ptr);

// Dereference: Output the value of myAge with the pointer (43)

printf("%d\n", *ptr);

return 0;

Note that the * sign can be confusing here, as it does two different things in our code:

 When used in declaration (int* ptr), it creates a pointer variable.


 When not used in declaration, it act as a dereference operator.

Why Should I Learn About Pointers? Pointers are important in C, because they give you the ability to
manipulate the data in the computer's memory - this can reduce the code and improve the performance.

Good To Know: There are three ways to declare pointer variables, but the first way is mostly used:

int* myNum; // Most used


int *myNum;
int * myNum;
C Functions
A function is a block of code which only runs when it is called.

You can pass data, known as parameters, 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.

Predefined Functions
So it turns out you already know what a function is. You have been using it the whole time while studying this
tutorial!

For example, main() is a function, which is used to execute code, and printf() is a function; used to output/print
text to the screen:

Example
#include <stdio.h>

int main() {

printf("Hello World!");

return 0;

Create a Function
To create (often referred to as declare) your own function, specify the name of the function, followed by
parentheses () and curly brackets {}:

Syntax
void myFunction() {
// code to be executed
}

Example Explained

 myFunction() is the name of the function


 void means that the function does not have a return value. You will learn more about return values later
in the next chapter
 Inside the function (the body), add code that defines what the function should do

Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be executed when they
are called.

To call a function, write the function's name followed by two parentheses () and a semicolon ;

In the following example, myFunction() is used to print a text (the action), when it is called:

Example
Inside main, call myFunction():

#include <stdio.h>

// Create a function

void myFunction() {

printf("I just got executed!");

int main() {

myFunction(); // call the function

return 0;

A function can be called multiple times:

Example
#include <stdio.h>
// Create a function

void myFunction() {

printf("I just got executed!\n");

int main() {

myFunction(); // call the function

myFunction(); // call the function

myFunction(); // call the function

return 0;

C Function Declaration and Definition


Function Declaration and Definition
You just learned from the previous chapters that you can create and call a function it the following way:

Example
#include <stdio.h>

// Create a function

void myFunction() {

printf("I just got executed!");

}
int main() {

myFunction(); // call the function

return 0;

A function consist of two parts:

 Declaration: the function's name, return type, and parameters (if any)
 Definition: the body of the function (code to be executed)

void myFunction() { // declaration


// the body of the function (definition)
}

For code optimization, it is recommended to separate the declaration and the definition of the function.

You will often see C programs that have function declaration above main(), and function definition below main().
This will make the code better organized and easier to read:

Example
#include <stdio.h>

// Function declaration

void myFunction();

// The main method

int main() {

myFunction(); // call the function

return 0;

// Function definition
void myFunction() {

printf("I just got executed!");

Another Example
If we use the example from the previous chapter regarding function parameters and return values:

Example
#include <stdio.h>

int myFunction(int x, int y) {

return x + y;

int main() {

int result = myFunction(5, 3);

printf("Result is = %d", result);

return 0;

It is considered good practice to write it like this instead:

Example
#include <stdio.h>
// Function declaration

int myFunction(int, int);

// The main method

int main() {

int result = myFunction(5, 3); // call the function

printf("Result is = %d", result);

return 0;

// Function definition

int myFunction(int x, int y) {

return x + y;

C Recursion
Recursion
Recursion is the technique of making a function call itself. This technique provides a way to break complicated
problems down into simple problems which are easier to solve.

Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it.

Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is more complicated. In the following
example, recursion is used to add a range of numbers together by breaking it down into the simple task of adding
two numbers:
Example
#include <stdio.h>

int sum(int k);

int main() {

int result = sum(10);

printf("%d", result);

return 0;

int sum(int k) {

if (k > 0) {

return k + sum(k - 1);

} else {

return 0;

Example Explained

When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and returns the
result. When k becomes 0, the function just returns 0. When running, the program follows these steps:

10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 +9+8+7+6+5+4+3+2+1+0
Since the function does not call itself when k is 0, the program stops there and returns the result.

The developer should be very careful with recursion as it can be quite easy to slip into writing a function which
never terminates, or one that uses excess amounts of memory or processor power. However, when written
correctly recursion can be a very efficient and mathematically-elegant approach to programming.

C Math Functions
Math Functions
There is also a list of math functions available, that allows you to perform mathematical tasks on numbers.

To use them, you must include the math.h header file in your program:

#include <math.h>

Square Root
To find the square root of a number, use the sqrt() function:

Example
#include <stdio.h>

#include <math.h>

int main() {

printf("%f", sqrt(16));

return 0;

Round a Number
The ceil() function rounds a number upwards to its nearest integer, and the floor() method rounds a number
downwards to its nearest integer, and returns the result:

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

int main() {

printf("%f\n", ceil(1.4));

printf("%f\n", floor(1.4));

return 0;

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

Example
#include <stdio.h>

#include <math.h>

int main() {

printf("%f", pow(4, 3));

return 0;

Other Math Functions


A list of other popular math functions (from the <math.h> library) can be found in the table below:

Function Description

abs(x) Returns the absolute value of x

acos(x) Returns the arccosine of x


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 E x

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

tan(x) Returns the tangent of an angle

C Structures (structs)
C Structures (structs)
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.

Unlike an array, a structure can contain many different data types (int, float, char, etc.).

Create a Structure
You can create a structure by using the struct keyword and declare each of its members inside curly braces:

struct MyStructure { // Structure declaration


int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; // End the structure with a semicolon

To access the structure, you must create a variable of it.

Use the struct keyword inside the main() method, followed by the name of the structure and then the name of the
structure variable:

Create a struct variable with the name "s1":

struct myStructure {
int myNum;
char myLetter;
};

int main() {
struct myStructure s1;
return 0;
}

Access Structure Members


To access members of a structure, use the dot syntax (.):

Example
#include <stdio.h>

// Create a structure called myStructure

struct myStructure {

int myNum;

char myLetter;

};

int main() {

// Create a structure variable of myStructure called s1

struct myStructure s1;

// Assign values to members of s1

s1.myNum = 13;

s1.myLetter = 'B';

// Print values

printf("My number: %d\n", s1.myNum);

printf("My letter: %c\n", s1.myLetter);

return 0;

}
Now you can easily create multiple structure variables with different values, using just one structure:

Example
struct myStructure {

int myNum;

char myLetter;

};

int main() {

// Create different struct variables

struct myStructure s1;

struct myStructure s2;

// Assign values to different struct variables

s1.myNum = 13;

s1.myLetter = 'B';

s2.myNum = 20;

s2.myLetter = 'C';

// Print values

printf("s1 number: %d\n", s1.myNum);

printf("s1 letter: %c\n", s1.myLetter);


printf("s2 number: %d\n", s2.myNum);

printf("s2 letter: %c\n", s2.myLetter);

return 0;

What About Strings in Structures?


Remember that strings in C are actually an array of characters, and unfortunately, you can't assign a value to an
array like this:

Example
#include <stdio.h>

struct myStructure {

int myNum;

char myLetter;

char myString[30]; // String

};

int main() {

struct myStructure s1;

// Trying to assign a value to the string

s1.myString = "Some text";


// Trying to print the value

printf("My string: %s", s1.myString);

return 0;

However, there is a solution for this! You can use the strcpy() function and assign the value to s1.myString, like
this:

Example
#include <stdio.h>

#include <string.h>

struct myStructure {

int myNum;

char myLetter;

char myString[30]; // String

};

int main() {

struct myStructure s1;

// Assign a value to the string using the strcpy function


strcpy(s1.myString, "Some text");

// Print the value

printf("My string: %s", s1.myString);

return 0;

Simpler Syntax
You can also assign values to members of a structure variable at declaration time, in a single line.

Just insert the values in a comma-separated list inside curly braces {}. Note that you don't have to use
the strcpy() function for string values with this technique:

Example
#include <stdio.h>

// Create a structure

struct myStructure {

int myNum;

char myLetter;

char myString[30];

};

int main() {

// Create a structure variable and assign values to it

struct myStructure s1 = {13, 'B', "Some text"};


// Print values

printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString);

return 0;

Note: The order of the inserted values must match the order of the variable types declared in the structure (13 for
int, 'B' for char, etc).

Copy Structures
You can also assign one structure to another.

In the following example, the values of s1 are copied to s2:

Example
#include <stdio.h>

struct myStructure {

int myNum;

char myLetter;

char myString[30];

};

int main() {

// Create a structure variable and assign values to it

struct myStructure s1 = {13, 'B', "Some text"};


// Create another structure variable

struct myStructure s2;

// Copy s1 values to s2

s2 = s1;

// Print values

printf("%d %c %s", s2.myNum, s2.myLetter, s2.myString);

return 0;

Modify Values
If you want to change/modify a value, you can use the dot syntax (.).

And to modify a string value, the strcpy() function is useful again:

Example
#include <stdio.h>

#include <string.h>

// Create a structure

struct myStructure {

int myNum;

char myLetter;

char myString[30];
};

int main() {

// Create a structure variable and assign values to it

struct myStructure s1 = {13, 'B', "Some text"};

// Modify values

s1.myNum = 30;

s1.myLetter = 'C';

strcpy(s1.myString, "Something else");

// Print values

printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString);

return 0;

Modifying values are especially useful when you copy structure values:

Example
#include <stdio.h>

#include <string.h>

struct myStructure {

int myNum;

char myLetter;
char myString[30];

};

int main() {

// Create a structure variable and assign values to it

struct myStructure s1 = {13, 'B', "Some text"};

// Create another structure variable

struct myStructure s2;

// Copy s1 values to s2

s2 = s1;

// Change s2 values

s2.myNum = 30;

s2.myLetter = 'C';

strcpy(s2.myString, "Something else");

// Print values

printf("%d %c %s\n", s1.myNum, s1.myLetter, s1.myString);

printf("%d %c %s\n", s2.myNum, s2.myLetter, s2.myString);

return 0;

}
Ok, so, how are structures useful?

Imagine you have to write a program to store different information about Cars, such as brand, model, and year.
What's great about structures is that you can create a single "Car template" and use it for every cars you make.
See below for a real life example.

Real Life Example


Use a structure to store different information about Cars:

Example
#include <stdio.h>

struct Car {

char brand[50];

char model[50];

int year;

};

int main() {

struct Car car1 = {"BMW", "X5", 1999};

struct Car car2 = {"Ford", "Mustang", 1969};

struct Car car3 = {"Toyota", "Corolla", 2011};

printf("%s %s %d\n", car1.brand, car1.model, car1.year);

printf("%s %s %d\n", car2.brand, car2.model, car2.year);

printf("%s %s %d\n", car3.brand, car3.model, car3.year);

return 0;
}

You might also like