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

C Data Types (2)

The document provides an overview of data types in C, detailing five main categories: basic, derived, enumerated, void, and user-defined. It explains the characteristics and memory requirements of primitive data types such as integers, characters, floats, and doubles, along with examples of variable declaration and type conversion. Additionally, it covers constants, operators, and their usage in C programming.

Uploaded by

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

C Data Types (2)

The document provides an overview of data types in C, detailing five main categories: basic, derived, enumerated, void, and user-defined. It explains the characteristics and memory requirements of primitive data types such as integers, characters, floats, and doubles, along with examples of variable declaration and type conversion. Additionally, it covers constants, operators, and their usage in C programming.

Uploaded by

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

C - Data Types

Data types in C refer to an extensive system for declaring different types of variables or
functions. The type of a variable determines how much space it occupies in storage and how the
bit pattern stored is interpreted. Each data type requires different amounts of memory and has
specific operations that can be performed over it. A data type is the kind of values a variable can
store or be assigned to. There are FIVE different data types used in C. These are:
(i) Basic or primitive
(ii) Derived
(iii) Enumerated
(iv) Void and
(v) User-defined.
The Basic or Primitive data types.
Primitive data types are the most basic data types that are used for representing simple values in
arithmetic such as integers, float, characters, and double.
Integer data type - The integer data type in C is used to store integer numbers (any number
including positive, negative, and zero without a decimal part). Octal values, hexadecimal values,
and decimal values can be stored in the int data type in C.
 Range: -2,147,483,648 to 2,147,483,647
 Size: 4 bytes
 Format Specifier: %d
Variables that take in integer values are declared as follows:
int variable name;
e.g. int x;
int y;
int number;
int counter;
You can declare an integer variable and assign a value either in one statement as:
int x = 5;
or in two statements as:
int x;
x = 5;
Integer data types has different sizes which depend on the compiler being used, as summarized in
the table below:

1
Type Storage size Value range

int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 8 bytes -9223372036854775808 to 9223372036854775807

unsigned long 8 bytes 0 to 18446744073709551615


The size of data type can be obtained from the compiler by using the operator: sizeof. e.g.:
// C Program To demonstrate
// sizeof operator
#include <stdio.h>
int main(){
printf("Size of char: %lu bytes\n", sizeof(char));
printf("Size of int: %lu bytes\n", sizeof(int));
printf("Size of float: %lu bytes\n", sizeof(float));
printf("Size of double: %lu bytes\n", sizeof(double));
printf("Size of pointer: %lu bytes\n", sizeof(void *));
return 0;
}
Character Data Type - Character data type allows its variable to store only a single character.
The size of the character is 1 byte. It is the most basic data type in C. It stores a single character
and requires a single byte of memory in almost all compilers.
 Range: (-128 to 127) or (0 to 255)
 Size: 1 byte
 Format Specifier: %c
To declare a character variable, we write:
char variable name;
When assigning characters, the value must be in single quotes.

2
e.g.
char a = ‘A’
Float Data Type - In C programming float data type is used to store floating-point values. Float
in C is used to store decimal and exponential values. It is used to store decimal numbers
(numbers with floating point values) with single precision.
 Range: 1.2E-38 to 3.4E+38
 Size: 4 bytes
 Format Specifier: %f
To declare a float variable, we write:
float variable name;
e.g.
float a;
float b = 2.5;
Double Type - A Double data type in C is used to store decimal numbers (numbers with floating
point values) with double precision. It is used to define numeric values which hold numbers with
decimal values in C.
The double data type is basically a precision sort of data type that is capable of holding 64 bits of
decimal numbers or floating points. Since double has more precision as compared to that float
then it is much more obvious that it occupies twice the memory occupied by the floating-point
type. It can easily accommodate about 16 to 17 digits after or before a decimal point.
 Range: 1.7E-308 to 1.7E+308
 Size: 8 bytes
 Format Specifier: %lf
To declare a double variable, we write
double a = 12.3123123;

Exercise 1.
Write a C program to determine the sizes of the four basic data types, showing all their possible
sizes, including signed and unsigned.

3
How to 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:
Example
#include <stdio.h>

int main() {
float myFloatNum = 3.5;
double myDoubleNum = 19.99;

printf("%f\n", myFloatNum);
printf("%lf", myDoubleNum);
return 0;
}

If you want to remove the extra zeros (set decimal precision), you can use a dot (.) followed by a
number that specifies how many digits should be shown after the decimal point:

Example
#include <stdio.h>

int main() {
float myFloatNum = 3.5;

printf("%f\n", myFloatNum); // Default will show 6 digits after the decimal point
printf("%.1f\n", myFloatNum); // Only show 1 digit
printf("%.2f\n", myFloatNum); // Only show 2 digits
printf("%.4f", myFloatNum); // Only show 4 digits
return 0;
}

Real-Life Example
Here's a real-life example of using different data types to calculate and output the total cost of a
number of items:

Example
// Create variables of different data types
#include <stdio.h>

int main() {
// Create variables of different data types
int items = 50;
float cost_per_item = 9.99;
float total_cost = items * cost_per_item;
char currency = '$';

4
// Print variables
printf("Number of items: %d\n", items);
printf("Cost per item: %.2f %c\n", cost_per_item, currency);
printf("Total cost = %.2f %c\n", total_cost, currency);

return 0;
}

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:

Example
// 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.
This can be risky, as you might lose control over specific values in certain situations.
Especially if it was the other way around - the following example automatically converts the
float value 9.99 to an int value of 9:

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

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

What happened to .99? We might want that data in our program! So be careful. You must know
how the compiler works in these situations to avoid unexpected results.
As another example, if you divide two integers, 5 by 2, you know that the sum is 2.5. And as you
know from the beginning of this page, if you store the sum as an integer, the result will only
display the number 2. Therefore, it would be better to store the sum as a float or a double, right?

Example
float sum = 5 / 2;

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

Why is the result 2.00000 and not 2.5? Well, it is because 5 and 2 are still integers in the
division. In this case, you need to manually convert the integer values to floating-point values.
(see below).

Explicit Conversion - Explicit conversion is done manually by placing the type in parentheses ()
in front of the value.
Considering our problem from the example above, we can now get the right result:
Example
// Manual conversion: int to float
float sum = (float) 5 / 2;

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

You can also place the type in front of a variable:

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

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

And since you learned about "decimal precision" in the previous chapter, you could make the
output even cleaner by removing the extra zeros (if you like):

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

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

6
Real-Life Example
Here's a real-life example of data types and type conversion where we create a program to
calculate the percentage of a user's score to the maximum score in a game:

Example
// Set the maximum possible score in the game to 500
int maxScore = 500;

// The actual score of the user


int userScore = 423;

/* Calculate the percantage of the user's score to the maximum available score.
Convert userScore to float to make sure that the division is accurate */
float percentage = (float) userScore / maxScore * 100.0;

// Print the percentage


printf("User's percentage is %.2f", percentage);

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:

Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'

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

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

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:

7
const int minutesPerHour;
minutesPerHour = 60; // error

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
const int BIRTHYEAR = 1980;

C Operators

Operators are used to perform operations on variables and values. In the example below, we use
the + operator to add together two values:
int myNum = 100 + 50;
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:
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
C provides five types of operators:
 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 1 ++x
-- Decrement Decreases the value of a variable by 1 --x

Program examples for each of the above arithmetic operators are shown:

8
+ - * /
#include <stdio.h> #include <stdio.h> #include <stdio.h> #include <stdio.h>
int main() int main() { int main() { int main() {
{ int x = 5; int x = 5; int x = 12;
int x = 5; int y = 3; int y = 3; int y = 3;
int y = 3; printf("%d", x - y); printf("%d", x * y); printf("%d", x / y);
printf("%d", x + y) return 0; return 0; return 0;
return 0; } } }
}

% ++ --
#include <stdio.h> #include <stdio.h> #include <stdio.h>
int main() { int main() { int main() {
int x = 5; int x = 5; int x = 5;
int y = 2; printf("%d", ++x); printf("%d", --x);
printf("%d", x % y); return 0; return 0;
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:
int x = 10;
The addition assignment operator (+=) adds a value to a variable:
int x = 10;
x += 5;
A list of all assignment operators is shown below:
Operator Example Same As
= x=5 x=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

9
^= x=x^3 x ^= 3
>>= x = x >> 3 x >>= 3
<<= x = x << 3 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 Description Try it
== Equal to x == y Returns 1 if the values are equal
!= Not equal x != y Returns 1 if the values are not equal
Returns 1 if the first value is greater than the
> Greater than x>y
second value
Returns 1 if the first value is less than the
< Less than x<y
second value
Greater than or Returns 1 if the first value is greater than, or
>= x >= y
equal to equal to, the second value
Returns 1 if the first value is less than, or equal
<= Less than or equal to x <= y
to, the second value

Logical Operators
You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values by combining
multiple conditions:

Operator Name Example Description


Returns 1 if both statements are
&& AND x < 5 && x < 10
true
Returns 1 if one of the
|| OR x < 5 || x < 4
statements is true
Reverse the result; returns 0
! NOT !(x < 5 && x < 10)
if the result is 1

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

11
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
From the example above, you can see that the return value is a boolean value (1).
You can also compare two variables:
Example
int x = 10;
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
You are not limited to only compare numbers. You can also compare boolean variables, or even
special structures, like arrays (which you will learn more about in a later chapter):
Example
bool isHamburgerTasty = true;
bool isPizzaTasty = true;

// Find out if both hamburger and pizza is tasty


printf("%d", isHamburgerTasty == isPizzaTasty);
Remember to include the <stdbool.h> header file when working with bool variables.
C Boolean Examples
Real Life Example
Let's think of a "real-life example" where we need to find out if a person is old enough to vote.
In the example below, we use the >= comparison operator to find out if the age (25) is greater
than OR equal to the voting age limit, which is set to 18:

12
Example
int myAge = 25;
int votingAge = 18;

printf("%d", myAge >= votingAge); // Returns 1 (true), meaning 25 year olds are allowed to
vote!
Cool, right? An even better approach (since we are on a roll now), would be to wrap the code
above in an if...else statement so we can perform different actions depending on the result:
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.");
}
Booleans are the basis for all comparisons and conditions.

C 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, and make sure all values are
of the same data type:
int myNumbers[] = {25, 50, 75, 100};
We have now created a variable that holds an array of four integers.
How to 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:

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

14
myNumbers[2] = 75;
myNumbers[3] = 100;
Using this method, you should know the number of array elements in advance, in order for the
program to store enough memory.
You are not able to change the size of the array after creation.
Avoid Mixing Data Types
It is important to note that all elements in an array must be of the same data type.
This means you cannot mix different types of values, like integers and floating-point numbers, in
the same array:
Example
int myArray[] = {25, 50, 75, 3.15, 5.99};
In the example above, the values 3.15 and 5.99 will be truncated to 3 and 5. In some cases it
might also result in an error, so it is important to always make sure that the elements in the array
are of the same type.
Array Size
To get the size of an array, you can use the sizeof operator:
Example
int myNumbers[] = {10, 25, 50, 75, 100};
printf("%lu", sizeof(myNumbers)); // Prints 20
Why did the result show 20 instead of 5, when the array contains 5 elements?
- It is because the sizeof operator returns the size of a type in bytes.
You learned from the Data Types chapter that an int type is usually 4 bytes, so from the example
above, 4 x 5 (4 bytes x 5 elements) = 20 bytes.
Knowing the memory size of an array is great when you are working with larger programs that
require good memory management.
But when you just want to find out how many elements an array has, you can use the following
formula (which divides the size of the array by the size of the first element in the array):
Example
int myNumbers[] = {10, 25, 50, 75, 100};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);

printf("%d", length); // Prints 5

15
Making Better Loops
In the array loops section in the previous chapter, we wrote the size of the array in the loop
condition (i < 4). This is not ideal since it will only work for arrays of a specified size.
However, by using the sizeof formula from the example above, we can now make loops that
work for arrays of any size, which is more sustainable.
Instead of writing:
Example
int myNumbers[] = {25, 50, 75, 100};
int i;

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


printf("%d\n", myNumbers[i]);
}
It is better to write:
Example
int myNumbers[] = {25, 50, 75, 100};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
int i;

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


printf("%d\n", myNumbers[i]);
}
Real-Life Example
To demonstrate a practical example of using arrays, let's create a program that calculates the
average of different ages:
Example
#include <stdio.h>
int main() {
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
float avg, sum = 0;
int i;
// Get the length of the array

16
int length = sizeof(ages) / sizeof(ages[0]);
// Loop through the elements of the array and accumulate the sum
for (i = 0; i < length; i++) {
sum += ages[i];
}
// Calculate the average by dividing the sum by the length
avg = sum / length;
// Print the average
printf("The average age is: %.2f", avg);
return 0;
}
// Calculate the average by dividing the sum by the length
avg = sum / length;

// Print the average


printf("The average age is: %.2f", avg);
In the following example, we create a program that finds the lowest age among different ages:
Example
#include <stdio.h>
int main() {
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
int i;
// Get the length of the array
int length = sizeof(ages) / sizeof(ages[0]);
// Create a 'lowest age' variable and assign the first array element of ages to it
int lowestAge = ages[0];
// Loop through the elements of the ages array to find the lowest age
for (i = 0; i < length; i++) {
// Check if the current age is smaller than current the 'lowest age'

17
if (lowestAge > ages[i]) {
// If the smaller age is found, update 'lowest age' with that element
lowestAge = ages[i];
}
}

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

18
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


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

ADVERTISEMENT

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

19
C 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]);
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
char greetings[] = "Hello World!";
greetings[0] = 'J';
printf("%s", greetings);
// Outputs Jello World! instead of Hello World!

20
ADVERTISEMENT

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]);
}
And like we specified in the arrays chapter, you can also use the sizeof formula (instead of
manually write the size of the array in the loop condition (i < 5)) to make the loop more
sustainable:
Example
char carName[] = "Volvo";
int length = sizeof(carName) / sizeof(carName[0]);
int i;

for (i = 0; i < length; ++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);
Why do we include the \0 character at the end? This is known as the "null terminating
character", and must be included when creating strings using this method. It tells C that this is
the end of the string.
21
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

Real-Life Example
Use strings to create a simple welcome message:
Example
char message[] = "Good to see you,";
char fname[] = "John";

printf("%s %s!", message, fname);

22
5.3 Math Library Functions
Math library functions allow you to perform certain common mathematical calculations. We use
some of them here to introduce the concept of functions. Later in the book, we’ll discuss many of
the other functions in the C standard library. Functions are normally used in a program by
writing the name of the function followed by a left parenthesis followed by the argument (or a
comma-separated list of arguments) of the function followed by a right parenthesis. For example,
to calculate and print the square root of 900.0, you might write
printf( "%.2f", sqrt( 900.0 ) );
When this statement executes, the math library function sqrt is called to calculate the square root
of the number contained in the parentheses (900.0). The number 900.0 is the argument of the sqrt
function. The preceding statement would print 30.00. The sqrt function takes 5.3 Math Library
Functions 161 an argument of type double and returns a result of type double. All functions in
the math library that return floating-point values return the data type double. Note that double val
ues, like float values, can be output using the %f conversion specification.
Function arguments may be constants, variables, or expressions. If c1 = 13.0, d = 3.0 and f = 4.0,
then the statement
printf( "%.2f", sqrt( c1 + d * f ) );
calculates and prints the square root of 13.0 + 3.0 * 4.0 = 25.0, namely 5.00. Figure5.2
summarizes a small sample of the C math library functions. In the figure, the variables x and y
are of type double. The C11 standard adds a wide range of floating point and complex-number
capabilities. Error-Prevention Tip 5.1 Include the math header by using the preprocessor
directive #include when using functions in the math library. printf( "%.2f", sqrt( c1 + d * f ) );
Function Description Example

23
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0 cbrt( x ) cube root of x (C99
and C11 only) cbrt( 27.0 ) is 3.0 cbrt( -8.0 ) is -2.0 exp( x ) exponential function ex exp( 1.0 ) is
2.718282 exp( 2.0 ) is 7.389056 log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0 log10( x ) logarithm of x (base 10) log10( 1.0 ) is 0.0 log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0 fabs( x ) absolute value of x as a floating-point number fabs( 13.5 ) is 13.5
fabs( 0.0 ) is 0.0 fabs( -13.5 ) is 13.5 ceil( x ) rounds x to the smallest integer not less than x
ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 floor( x ) rounds x to the largest integer not greater than x
floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0 pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128.0
pow( 9, .5 ) is 3.0 fmod( x, y ) remainder of x/y as a floating-point number fmod( 13.657, 2.333 )
is 1.992 sin( x ) trigonometric sine of x (x in radians) sin( 0.0 ) is 0.0 cos( x ) trigonometric
cosine of x (x in radians) cos( 0.0 ) is 1.0 tan( x ) trigonometric tangent of x (x in radians)
tan( 0.0 ) is 0.0 Fig. 5.2|Commonly used math library functions. 162 Chapter 5 C Function

24

You might also like