0% found this document useful (0 votes)
229 views48 pages

C Programing Language

The document provides an overview of the C programming language including how to install an IDE, write a simple Hello World program, understand the syntax and structure of a C program, use variables, data types, comments, and print output. It covers basic concepts like variables, data types, comments, input/output functions and more to get started with C programming.

Uploaded by

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

C Programing Language

The document provides an overview of the C programming language including how to install an IDE, write a simple Hello World program, understand the syntax and structure of a C program, use variables, data types, comments, and print output. It covers basic concepts like variables, data types, comments, input/output functions and more to get started with C programming.

Uploaded by

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

C PROGRAMING LANGUAGE

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

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

OUR COLLEGE IS USING DEVC++

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

QUICK START OF THE PROGRAM


1. HOW TO WRITE HELLO WORLD PROGRAM IN C LANGUAGE
CODE:-
#include <stdio.h>

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

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

SYNTAX OF C LANGUAGE

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.

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 (using Print Text keyword)

Code:-
#include <stdio.h>

int main() {
printf("Hello World!");
printf("I am learning C.");
return 0;
}
O/P:-
Hello World!I am learning C.
--------------------------------
Process exited after 0.06446 seconds with return value 0
Press any key to continue . . .

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

#include <stdio.h>

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

o/p:-

Hello World!

I am learning C.

--------------------------------

Process exited after 0.05858 seconds with return value 0

Press any key to continue . . .

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

#include <stdio.h>

int main() {
printf("Hello World!\nI am learning C.\nAnd it is awesome!");
return 0;
}

O/P:-
Hello World!
I am learning C.
And it is awesome!
--------------------------------
Process exited after 0.05912 seconds with return value 0
Press any key to continue . . .

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

1. \t Creates a horizontal tab

2. \\ Inserts a backslash character (\)

3. \" Inserts a double quote character

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

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

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

Example 3
/* The code below will print the words Hello World!
to the screen, and it is amazing */
printf("Hello World!");

C Variables
Variables are containers for storing data values, like numbers and characters.

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


for example:

int - stores integers (whole numbers), without decimals, such as 123 or -123

Float - stores floating point numbers, with decimals, such as 19.99 or -19.99

Char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes

Syntax
type variableName = value;

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

int myNum = 15;

Example
// Declare a variable
int myNum;
// Assign a value to the variable
myNum = 15;

Output Variables
You can output values/print text with the printf() function:

printf("Hello World!");

Example
int myNum = 15;
printf(myNum); // Nothing happens

Example
int myNum = 15;
printf("%d", myNum); // Outputs 15

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


// Create variables
int myNum = 15; // 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);

To combine both text and a variable, separate them with a comma inside
the printf() function:
Example
int myNum = 15;
printf("My favorite number is: %d", myNum);

Example
int myNum = 15;
char myLetter = 'D';
printf("My number is %d and my letter is %c", myNum, myLetter);

Change Variable Values


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

int myNum = 15; // myNum is 15


myNum = 10; // Now myNum is 10

You can also assign the value of one variable to another:

Example
int myNum = 15;

int myOtherNum = 23;

// Assign the value of myOtherNum (23) to myNum


myNum = myOtherNum;

// myNum is now 23, instead of 15


printf("%d", myNum);

Add Variables Together


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

Declare Multiple Variables


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

Example
int x = 5, y = 6, z = 50;
printf("%d", x + y + z);

(or)
int x, y, z;
x = y = z = 50;
printf("%d", x + y + z);

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

These unique names are called identifiers.

Note: It is recommended to use descriptive names in order to create


understandable and maintainable code:
// Good
int minutesPerHour = 60;

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


int m = 60;

The general rules for naming variables are:

• Names can contain letters, digits and underscores


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

Real-Life Example
Often in our examples, we simplify variable names to match their data type
(myInt or myNum for int types, myChar for char types etc). This is done to
avoid confusion.

// Student data
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25;
char studentGrade = 'B';

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

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
// 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);

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 bytes Stores whole numbers, without decimals
float 4 bytes Stores fractional numbers, containing one or more
decimals. Sufficient for storing 6-7 decimal digits
double 8 bytes Stores fractional numbers, containing one or more decimals.
Sufficient for storing 15 decimal digits
char 1 byte Stores a single character/letter/number, or ASCII
values

Basic Format Specifiers


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

Format Data Type


Specifier
%d or %i int
%f float
%lf double
%c char
%s Used for strings (text),

Set Decimal Precision


You have probably already noticed that if you print a floating point number,
the output will show many digits after the decimal point:
float myFloatNum = 3.5;
double myDoubleNum = 19.99;

printf("%f\n", myFloatNum); // Outputs 3.500000


printf("%lf", myDoubleNum); // Outputs 19.990000

Example
float myFloatNum = 3.5;
printf("%f\n", myFloatNum); // Default will show 6 digits after the
decimal point
printf("%.1f\n", myFloatNum); // Only show 1 digit
printf("%.2f\n", myFloatNum); // Only show 2 digits
printf("%.4f", myFloatNum); // Only show 4 digits

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:

Example
int x = 5;
int y = 2;
int sum = 5 / 2;

printf("%d", sum); // Outputs 2

To get the right result, you need to know how type conversion works.

There are two types of conversion in C:

• Implicit Conversion (automatically)


• Explicit Conversion (manually)

Implicit Conversion
Implicit conversion is done automatically by the compiler when you assign a
value of one type to another.

For example, if you assign an int value to a float type:


// Automatic conversion: int to float
float myFloat = 9;

printf("%f", myFloat); // 9.000000

As you can see, the compiler automatically converts the int value 9 to a float
value of 9.000000.

Example
// Automatic conversion: float to int
int myInt = 9.99;

printf("%d", myInt); // 9

Example
float sum = 5 / 2;

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

Explicit Conversion
Example
// Manual conversion: int to float
float sum = (float) 5 / 2;

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

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

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

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

printf("%.1f", sum); // 2.5


Constants
If you don't want others (or yourself) to change existing variable values, you
can use the const keyword.

This will declare the variable as "constant", which


means unchangeable and read-only:

const int myNum = 15; // myNum will always be 15


myNum = 10; // error: assignment of read-only variable 'myNum'

Example
const int minutesPerHour = 60;
const float PI = 3.14;

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
int myNum = 100 + 50;

Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)

Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two values x+y


- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

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

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

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
int x = 10;

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

Example
int x = 10;
x += 5;

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

Comparison Operators
Comparison operators are used to compare two values (or variables). This is
important in programming, because it helps us to find answers and make
decisions.

The return value of a comparison is either 1 or 0, which means true (1)


or false (0). These values are known as Boolean values, and you will learn
more about them in the Booleans and If..Else chapter.

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

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

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

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

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

C Booleans
Booleans
Very often, in programming, you will need a data type that can only have
one of two values, like:

• YES / NO
• ON / OFF
• TRUE / FALSE
For this, C has a bool data type, which is known as booleans.

Booleans represent values that are either true or false.

Boolean Variables
In C, the bool type is not a built-in data type, like int or char.

It was introduced in C99, and you must import the following header file to
use it:

#include <stdbool.h>
A boolean variable is declared with the bool keyword and can only take the
values true or false:
bool isProgrammingFun = true;
bool isFishTasty = false;

Before trying to print the boolean variables, you should know that boolean
values are returned as integers:

• 1 (or any other number that is not 0) represents true


• 0 represents false

Therefore, you must use the %d format specifier to print a boolean value

Example
// Create boolean variables
bool isProgrammingFun = true;
bool isFishTasty = false;

// Return boolean values


printf("%d", isProgrammingFun); // Returns 1 (true)
printf("%d", isFishTasty); // Returns 0 (false)
However, it is more common to return a boolean value by comparing values
and variables.

Comparing Values and Variables


Comparing values are useful in programming, because it helps us to find
answers and make decisions.
For example, you can use a comparison operator, such as the greater
than (>) operator, to compare two values:

Example
printf("%d", 10 > 9); // Returns 1 (true) because 10 is greater than 9

Example
int x = 10; // 2 varibales
int y = 9;
printf("%d", x > y);

In the example below, we use the equal to (==) operator to compare


different values:

Example
printf("%d", 10 == 10); // Returns 1 (true), because 10 is equal to 10
printf("%d", 10 == 15); // Returns 0 (false), because 10 is not equal
to 15
printf("%d", 5 == 55); // Returns 0 (false) because 5 is not equal to
55

Example
Output "Old enough to vote!" if myAge is greater than or equal to 18.
Otherwise output "Not old enough to vote.":

int myAge = 25;


int votingAge = 18;

if (myAge >= votingAge) {


printf("Old enough to vote!");
} else {
printf("Not old enough to vote.");
}

C If ... Else
Conditions and If Statements
You have already learned that C supports the usual logical conditions from
mathematics:
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• Equal to a == b
• Not Equal to: a != b

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

C has the following conditional statements:

• Use if to specify a block of code to be executed, if a specified condition


is true
• Use else to specify a block of code to be executed, if the same
condition is false
• Use else if to specify a new condition to test, if the first condition
is false
• Use switch to specify many alternative blocks of code to be executed

The if Statement
Use the if statement to specify a block of code to be executed if a condition
is true.

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

Example
if (20 > 18) {
printf("20 is greater than 18");
}

We can also test variables:

Example
int x = 20;
int y = 18;
if (x > y) {
printf("x is greater than y");
}

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
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
// Outputs "Good evening."

Another Example
This example shows how you can use if..else to find out if a number is
positive or negative:

int myNum = 10; // Is this a positive or negative number?

if (myNum > 0) {
printf("The value is a positive number.");
} else if (myNum < 0) {
printf("The value is a negative number.");
} else {
printf("The value is 0.");
}

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
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}

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

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

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

This is how it works:

• The switch expression is evaluated once


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

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

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

// Outputs "Thursday" (day 4)


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.

The default Keyword


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

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

// Outputs "Looking forward to the Weekend"

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

Loops are handy because they save time, reduce errors, and they make code
more readable.
While Loop
The while loop loops through a block of code as long as a specified condition
is true:

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

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

Example
int i = 0;

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

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
int i = 0;

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

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
int i;

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


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

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

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

Statement 3 increases a value (i++) each time the code block in the loop has
been executed.
Another Example
This example will only print even values between 0 and 10:

Example
for (i = 0; i <= 10; i = i + 2) {
printf("%d\n", i);
}

Nested Loops
It is also possible to place a loop inside another loop. This is called a nested
loop.

The "inner loop" will be executed one time for each iteration of the "outer
loop":

Example
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)
}
}

C Break and Continue


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

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

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


Example
int i;

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


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

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
int i;

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


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

Break and Continue in While Loop


You can also use break and continue in while loops:

BREAK Example
int i = 0;

while (i < 10) {


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

while (i < 10) {


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

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
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);

// Outputs 25

Change an Array Element


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

Example
myNumbers[0] = 33;

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

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

// Now outputs 33 instead of 25

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
int myNumbers[] = {25, 50, 75, 100};
int i;

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


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

Set Array Size


Another common way to create arrays, is to specify the size of the array, and
add elements later:
Example
// Declare an array of four integers:
int myNumbers[4];

// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;

C Multidimensional Arrays
Multidimensional Arrays
In the previous chapter, you learned about arrays, which is also known
as single dimension arrays. These are great, and something you will use a
lot while programming in C. However, if you want to store data as a tabular
form, like a table with rows and columns, you need to get familiar
with multidimensional arrays.

A multidimensional array is basically an array of arrays.

Arrays can have any number of dimensions. In this chapter, we will introduce
the most common; two-dimensional arrays (2D).

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 matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

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:
Access the Elements of a 2D Array
To access an element of a two-dimensional array, you must specify the index
number of both the row and column.

This statement accesses the value of the element in the first row
(0) and third column (2) of the matrix array.

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

printf("%d", matrix[0][2]); // Outputs 2

Change Elements in a 2D Array


To change the value of an element, refer to the index number of the element
in each of the dimensions:

The following example will change the value of the element in the first row
(0) and first column (0):

Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;

printf("%d", matrix[0][0]); // Now outputs 9 instead of 1

Loop Through a 2D Array


To loop through a multi-dimensional array, you need one loop for each of the
array's dimensions.

The following example outputs all elements in the matrix array:


Example
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]);
}
}

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. Instead, you must 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
char greetings[] = "Hello World!";
printf("%s", greetings);

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
char greetings[] = "Hello World!";
printf("%c", greetings[0]);

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

Example
char greetings[] = "Hello World!";
greetings[0] = 'J';
printf("%s", greetings);
// Outputs Jello World! instead of Hello World!

Loop Through a String


You can also loop through the characters of a string, using a for loop:

Example
char carName[] = "Volvo";
int i;

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


printf("%c\n", carName[i]);
}

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 create a string with a set of characters.
This example will produce the same result as the example in the beginning of
this page:

Example
char greetings[] = {'H', 'e', 'l', 'l', 'o', '
', 'W', 'o', 'r', 'l', 'd', '!', '\0'};
printf("%s", greetings);

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
char greetings[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l',
'd', '!', '\0'};
char greetings2[] = "Hello World!";

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


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

C Special Characters
Strings - Special Characters
Because strings must be written within quotes, C will misunderstand this
string, and generate an error:

char txt[] = "We are the so-called "Vikings" from the north.";

The solution to avoid this problem, is to use the backslash escape


character.

The backslash (\) escape character turns special characters into string
characters:

Escape character Result Description

\' ' Single quote

\" " Double quote


\\ \ Backslash

Escape character Result Description

The sequence \" inserts a double quote in a string:

Example
char txt[] = "We are the so-called \"Vikings\" from the north.";

The sequence \' inserts a single quote in a string:

Example
char txt[] = "It\'s alright.";

The sequence \\ inserts a single backslash in a string:

Example
char txt[] = "The character \\ is called backslash.";

Other popular escape characters in C are:

Escape Character Result

\n New Line

\t Tab

\0 Null

C String Functions
String Functions
C also has many useful string functions, which can be used to perform
certain operations on strings.

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

#include <string.h>

String Length
For example, to get the length of a string, you can use the strlen() function:

Example
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet));

In the Strings chapter, we used sizeof to get the size of a string/array. Note
that sizeof and strlen behaves differently, as sizeof also includes
the \0 character when counting:

Example
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet)); // 26
printf("%d", sizeof(alphabet)); // 27
It is also important that you know that sizeof will always return the memory
size (in bytes), and not the actual string length:

Example
char alphabet[50] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet)); // 26
printf("%d", sizeof(alphabet)); // 50

Concatenate Strings
To concatenate (combine) two strings, you can use the strcat() function:

Example
char str1[20] = "Hello ";
char str2[] = "World!";

// Concatenate str2 to str1 (result is stored in str1)


strcat(str1, str2);
// Print str1
printf("%s", str1);

Copy Strings
To copy the value of one string to another, you can use the strcpy() function:

Example
char str1[20] = "Hello World!";
char str2[20];

// Copy str1 to str2


strcpy(str2, str1);

// Print str2
printf("%s", str2);

Compare Strings
To compare two strings, you can use the strcmp() function.

It returns 0 if the two strings are equal, otherwise a value that is not 0:

Example
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "Hi";

// Compare str1 and str2, and print the result


printf("%d\n", strcmp(str1, str2)); // Returns 0 (the strings are
equal)

// Compare str1 and str3, and print the result


printf("%d\n", strcmp(str1, str3)); // Returns -4 (the strings are not
equal)

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:

// 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: \n");

// Get and save the number the user types


scanf("%d", &myNum);

// Output the number the user typed


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

Multiple Inputs
The scanf() function also allow multiple inputs (an integer and a character in
the following example):

Example
// 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);

Take String Input


You can also get a string entered by the user:
Example
Output the name of a user:

// 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);
However, the scanf() function has some limitations: it considers space
(whitespace, tabs, etc) as a terminating character, which means that it can
only display a single word (even if you type many words).
For example:

Example
char fullName[30];

printf("Type your full name: \n");


scanf("%s", &fullName);

printf("Hello %s", fullName);

// Type your full name: John Doe


// Hello John

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 represents where
the variable is stored:
Example
int myAge = 43;
printf("%p", &myAge); // Outputs 0x7ffe5367e044

Note: The memory address is in hexadecimal form (0x..). You will probably
not get the same result in your program, as this depends on where the
variable is stored on your computer.

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.

You will learn much more about pointers in the next chapter.

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
int myAge = 43; // an int variable

printf("%d", myAge); // Outputs the value of myAge (43)


printf("%p", &myAge); // Outputs the memory address of myAge
(0x7ffe5367e044)

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 are working with is assigned to the pointer:

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

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 (int in our example).

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

You can also get the value of the variable the pointer points to, by using
the * operator (the dereference operator):

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

C Pointers and Arrays


Pointers & Arrays
You can also use pointers to access arrays.

Consider the following array of integers:


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

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

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


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

Result:

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

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


printf("%p\n", &myNumbers[i]);
}

Result:

How Are Pointers Related to Arrays


Ok, so what's the relationship between pointers and arrays? Well, in C,
the name of an array, is actually a pointer to the first element of the
array.
Confused? Let's try to understand this better, and use our "memory address
example" above again.

The memory address of the first element is the same as the name of the
array:

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

// Get the memory address of the myNumbers array


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

// Get the memory address of the first array element


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

Result:

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

// Get the value of the first element in myNumbers


printf("%d", *myNumbers);

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

// Get the value of the second element in myNumbers


printf("%d\n", *(myNumbers + 1));

// Get the value of the third element in myNumbers


printf("%d", *(myNumbers + 2));

// and so on..

Or loop through it:


Example
int myNumbers[4] = {25, 50, 75, 100};
int *ptr = myNumbers;
int i;

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


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

Result:

It is also possible to change the value of array elements with pointers:

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

// Change the value of the first element to 13


*myNumbers = 13;

// Change the value of the second element to 17


*(myNumbers +1) = 17;

// Get the value of the first element


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

// Get the value of the second element


printf("%d\n", *(myNumbers + 1));

Result:
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
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():

// Create a function
void myFunction() {
printf("I just got executed!");
}

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

// Outputs "I just got executed!"


A function can be called multiple times:

Example
void myFunction() {
printf("I just got executed!");
}

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

// I just got executed!


// I just got executed!
// I just got executed!
C Function Parameters
Parameters and Arguments
Information can be passed to functions as a parameter. Parameters act as
variables inside the function.

Parameters are specified after the function name, inside the parentheses.
You can add as many parameters as you want, just separate them with a
comma:

Syntax
returnType functionName(parameter1, parameter2, parameter3) {
// code to be executed
}

The following function that takes a string of characters with name as


parameter. When the function is called, we pass along a name, which is used
inside the function to print "Hello" and the name of each person.

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

int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}

// Hello Liam
// Hello Jenny
// Hello Anja
Multiple Parameters
Inside the function, you can add as many parameters as you want:

Example
void myFunction(char name[], int age) {
printf("Hello %s. You are %d years old.\n", name, age);
}

int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}

// Hello Liam. You are 3 years old.


// Hello Jenny. You are 14 years old.
// Hello Anja. You are 30 years old.

Pass Arrays as Function Parameters


You can also pass arrays to a function:

Example
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
printf("%d\n", myNumbers[i]);
}
}

int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}

You might also like