Introduction To Programming by Examples
Introduction To Programming by Examples
Introduction To Programming by Examples
INTRODUCTION TO PROGRAMMING BY
EXAMPLES
OHRID, 2022
Authors:
Assoc. Prof. Atanas Hristov, PhD
Naum Tuntev, MsC
Prof. Ninoslav Marina, PhD
Reviewers:
Prof. Cvetko Andreeski, PhD
Assoc. Prof. Aneta Velkoska, PhD
Cover design:
Goran Kunovski
Technical processing:
Assoc. Prof. Atanas Hristov, PhD
Publisher:
University of Information Science and Technology
Abstract
This book contains code examples adopted for undergraduate students that explain
key structured programming concepts: variables, data structure, functions, one and
two-dimensional arrays, pointers, and strings. The code examples are written in the
C programming language.
By reading this book, students will learn techniques for designing programs
and will understand how to model real-world problems and managing complexity.
Moreover, students will gain problem-solving skills in the meaning of efficient and
elegant problem solving and will acquire debugging and other special programming
skills.
Good programming style is another skill that the students will gain by reading
this book. They will learn how to write robust, efficient, and readable code and what
is the correct way to document and comment on the code.
Finally, students will learn how to use the main data structures: variables, arrays,
matrices, strings. They will get familiar with the scope of the variables and basic
arithmetical and logical operations. Also, they will learn how to control the flow
of the program, how to use functions and will gain special programming skill -
recursion. In the end, they will learn how to work with pointers and strings.
vii
Acknowledgements
I would like to acknowledge the help of all the people involved in the writing of
this book, more specifically, the authors and reviewers that took part in the review
process. Without their support, this book would not have become a reality.
My sincere gratitude goes to the other authors who contributed their time and
expertise to this book.
I would like to acknowledge the valuable contributions of the reviewers regarding
the improvement of quality, coherence, and content presentation of chapters. The
authors also served as referees; I highly appreciate their double task.
Finally, I would like to thank the University of Information Science and
Technology "St. Paul the Apostle" - Ohrid and its administration for their support in
publishing this book.
by Atanas Hristov
ix
Contents
Abstract vii
Acknowledgements ix
Contents xi
List of Figures xv
1 Introduction 1
3 Operations 15
3.1 Arithmetic operations . . . . . . . . . . . . . . . . . . . . . . . 15
3.2 Assignment operations . . . . . . . . . . . . . . . . . . . . . . . 17
3.3 Relational operations . . . . . . . . . . . . . . . . . . . . . . . 19
3.4 Logical operations . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.5 Cast operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
4 Selection structures 23
4.1 if and if/else statements . . . . . . . . . . . . . . . . . . . . . . 24
4.2 Switch statement . . . . . . . . . . . . . . . . . . . . . . . . . . 30
5 Repetition structures 35
5.1 While loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
xi
Contents
6 Functions 55
6.1 Functions in C . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
6.2 Scope of the variables . . . . . . . . . . . . . . . . . . . . . . . 56
6.3 Defining and using functions . . . . . . . . . . . . . . . . . . . 58
6.4 Recursive functions . . . . . . . . . . . . . . . . . . . . . . . . 67
6.5 Function prototype . . . . . . . . . . . . . . . . . . . . . . . . . 71
7 Arrays 75
7.1 Arrays in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.2 Declaring and initialization of arrays . . . . . . . . . . . . . . . 76
7.3 Accessing elements of arrays . . . . . . . . . . . . . . . . . . . 77
7.4 Passing arrays as parameters to a function . . . . . . . . . . . . 81
8 Matrices 99
8.1 Matrices in C . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
8.2 Declaring and initialization of matrices . . . . . . . . . . . . . . 99
8.3 Accessing elements and passing matrices as parameters to a function 102
9 Pointers 119
9.1 Pointers in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
9.2 Operations with pointers . . . . . . . . . . . . . . . . . . . . . . 121
9.3 Using pointers to functions and arrays . . . . . . . . . . . . . . 123
10 Strings 137
10.1 Strings in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
10.2 Entering and printing strings . . . . . . . . . . . . . . . . . . . 139
10.3 String manipulation - strng.h library . . . . . . . . . . . . . . . 140
10.4 Testing and mapping characters - ctype.h library . . . . . . . . . 142
11 Files 155
11.1 Working with files in C . . . . . . . . . . . . . . . . . . . . . . 155
12 Structures 163
12.1 Structures in C . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
12.2 Accessing structure members and initialization . . . . . . . . . 164
12.3 Array of structures and nested structures . . . . . . . . . . . . . 165
12.4 Pointers to structures and structures to function . . . . . . . . . . 166
Appendices 175
xii
Contents
C C keywords 199
References 201
Copyright 205
xiii
List of Figures
xv
List of Tables
xvii
CHAPTER 1
Introduction
1
1. Introduction
2
CHAPTER 2
Data in computers are stored in a binary number system. The binary number system
is a positional numeral system with two as its base and uses only the digits 0 and
1 to represent all data types. The binary number system follows the same set of
mathematics rules as the commonly used decimal number system. The main reason
behind using a binary number system is that digits 0 and 1 are stored as two voltage
levels. On the other hand, every data can be represented with digits 0 and 1.
Each digit in the binary number system is called bit. The bits are the basic unit
for storing information in digital information systems. For example, the number
01010111 is 8 bits long or one byte. The byte is the smallest addressable unit of
memory; hence, it is the main unit to measure memory capacity.
3
2. Data types and data representation
Standard Code for Information Interchange) code table. The standard ASCII code
table is given on Figure 2.1.
1 Source: https://simple.wikipedia.org/wiki/ASCII#/media/File:ASCII-Table-wide.svg
4
2.2. Ranges
2.2 Ranges
The range in a set of numbers is the difference between the maximum and minimum
values. In the C programming language, range refers to the value stored inside the
variable of a given type. Besides the type of a variable, the range defers based on
whether the variable is unsigned or signed.
The number of numerical values that can be represented by unsigned numbers
with n-bits is 2n . The range of unsigned numbers represented by n-bit words is
calculated as follows:
0 ⩽ x ⩽ 2n − 1
For example, if the number of bits n is 8 (1 byte), the range will be from 0 to 255.
It means that there will be 28 (256) numerical values in the range.
The range of signed numbers represented by n-bit words is calculated as
follows:
−2n−1 ⩽ x ⩽ 2n−1 − 1
For example, if the number of bits n is 8 (1 byte), the range will be from -128 to
127. It means that there will be 28 (256) numerical values in the range, including 0.
In table 2.2, ranges of some commonly used datatypes in C is given.
The above ranges are approximate and depend of the platform. Different hardware
and software platforms can have different values for the datatypes ranges. There is a
predefined operator in the C programming language that returns the exact size of the
datatype on a particular platform. The operator’s structure is sizeof(type) and returns
the amount of memory allocated to that datatype in bytes.
5
2. Data types and data representation
The negative part of the range is stored in the memory as a two’s complement of
the positive value. The two’s complement is calculated in two steps as follows:
• Step 1: Find the inverse binary value of the number. The inverse number
is calculated by converting each bit into the opposite one. For example, the
inverse value of 10011101 is 01100010.
The first part of each program is the header of the program. The header usually
is optional, in which the programmer provides information about the program.
Another important part of the program is the include section. The programmer
includes all libraries with pre-defined functions that the programmer is going to use
in the program in the include section.
In a defined section, the programmer defines his own constants and data types.
The programmer also needs to define the global variables and functions used in
the program.
Each C program must have at least one function - main().
6
2.4. Constants
2.4 Constants
Constants are data that do not change their value during program execution, i.e., the
value is constant.
In the C programming language, constants can be of any of the basic datatypes
presented in Table 2.1. The compiler treats constants as a regular variable except
that their values can not be modified after their definition. Based on their datatype,
the constants can be classified as follows:
• Integer constants. In this group belongs all decimal integers data types,
including modified versions: short, long, signed, and unsigned. To specify
the modified version of an integer, the suffix L for long, U for unsigned, or
a combination of both needs to be added. Also, this group covers octal and
hexadecimal integers. The prefix 0 for Octal, or 0x or 0X for hexadecimal
integer, needs to be added to specify the octal and hexadecimal constant.
Examples:
– 189 is integer.
– 29L is long integer.
– 398U is unsigned integer.
– 199UL is unsigned long integer.
– 0361 is octal integer.
– 0x591AF7 is hexadecimal integer.
– 0x123AAL is long hexadecimal integer.
– 31.123 is double.
– 29.0L is long double.
– 127.34F is float.
– 2.435E1 is double. It is same as 24.35
– 13E-3L is long double. It is same as 0.013L.
– .05E1 is double. It is same as .5; 0.5; .005E2; 500E-3; etc.
7
2. Data types and data representation
where:
CONSTANTNAME is the name of the constant;
value is the value assigned to the constant.
When a constant is defined by using const keyword, the name, the type, and
the value of the constant should be provided. The structure of the statement with a
textbfconst keyword is as follows:
where:
type is the datatype of the constant;
CONSTANTNAME is the name of the constant;
8
2.5. Variables
Examples:
2.5 Variables
A variable provides the user with named storage that programs can manipulate. The
names of variables correspond to locations in the computer memory. Each variable
in C has a type. The type determines the size and layout of the variable’s memory,
the range of values that it can store, and the set of operations applied to it. Whenever
a new value is placed in a container (variable), the previous value is erased. Reading
values from a variable do not change its value.
In the C programming language, variables are declared by defining the name
and the type of the variable. The structure of a statement for declaring a variable is
as follows:
The structure of a statement for declaring a variable
type variableName;
where:
type is the datatype of the variable;
variableName is the name of the variable;
Multiple variables from the same type can be declared separated by comma (,),
as follows:
The name of the variable must begin with either a letter or an underscore. A
variable name can only have letters, digits and underscore. Variable names are
case-sensitive, i.e., name1 and Name1 are two different variables. The C keywords
defined in table C.1 cannot be used as a variable name.
The variable must always be declared before it is used.
Additional comment: Always define the variable at the beginning of the main
function or the beginning of a block of statements or outside a function.
9
2. Data types and data representation
variableName = value;
The assigning of the value to a variable can also be done during a declaration of
the variable, as follows:
Examples:
where:
format is a text shown on the screen
exp1, exp2,... are individual values that are shown on the screen
For better output and formatting of the text on the screen, the C language supports
several escape sequences. The escape sequences are sequences of characters that
produce some effect in the C programming language. In table 2.3, a list of some
commonly used escape sequences is given, together with a description of them.
Exercises:
1. Write a C program that will display Hello World! on the screen.
Solution:
#include <stdio.h>
int main(){
10
2.7. Data entry from the keyboard
printf("Hello World!");
return 0;
2. Write a C program that will create and initialize three variables, one real
number, one decimal point number, and one single character. Use a printf()
function to display the values of these variables on the screen.
Solution:
#include <stdio.h>
int main(){
return 0;
11
2. Data types and data representation
where:
format is a text containing the information for the data that will be entered
& mark referees that the value of the variables val1, val2, ... will be hanged by
values from the keyboard;
val1, val2, ... are variables that will store the data entered from the keyboard.
A list of some commonly used data types specifiers is given in Table 2.4.
Exercises:
1. Write a C program that read three numbers from the keyboard and print their
sum on the screen.
Solution:
#include <stdio.h>
int main(){
int a, b, c;
int sum;
sum = a + b + c;
return 0;
2. Write a C program that calculates the area of a rectangle. The sides of the
rectangle are entered from the keyboard.
12
2.7. Data entry from the keyboard
Solution:
#include <stdio.h>
int main(){
float a, b;
float area;
area = a * b;
return 0;
3. Write a C program that calculates the average of five integers entered by the
user.
Solution:
#include <stdio.h>
int main(){
return 0;
13
CHAPTER 3
Operations
In this chapter, the basic operations in the C programming language, and the rules for
creating and using them will be presented. The presented operations are as follows:
• Arithmetic operations;
• Assignment operations;
• Relational operations;
• Cast operations.
15
3. Operations
int main()
{
int whole;
float real;
real = 1.0 / 2.0;
whole = 1 / 3;
real = (1 / 2) + (1 / 2);
real = 3.0 * 2.0;
whole = real;
whole = whole +1;
return (0);
}
Exercises:
1. Write a C program that converts Celsius into Fahrenheit degrees. The Celsius
degrees are entered from the keyboard. The conversion formula is: f = 1.8C +
32
Solution:
#include <stdio.h>
int main(){
16
3.2. Assignment operations
return 0;
2. Write a C program that asks the user to enter the amount of money, debt
period (in years), and the interest rate per year. The program should tell the
user how much money he will return in total at the end of the debt period.
Solution:
#include <stdio.h>
int main(){
float result;
return 0;
int a, b, c, d;
a=b=c=d=10;
17
3. Operations
d=10 is the first operation that is executed, making the value 10 available to the next
assignment operation of assigning 10 to c, etc.
In the C programming language, the assignment operators can also be applied
to assign the result of an expression to a variable, i.e., to shorthand the operators.
Some of the most common shorthand operator used in C and their equivalence with
the corresponding mathematical operation is given in Table 3.2.
#include <stdio.h>
int main()
{
int a=1;
printf ("a = %d\n", a);
printf ("a = %d\n", ++a);
printf ("a = %d\n", a);
return 0;
}
a = 1
a = 2
a = 2
#include <stdio.h>
int main()
18
3.3. Relational operations
{
int a=1;
printf ("a = %d\n", a);
printf ("a = %d\n", a++);
printf ("a = %d\n", a);
return 0;
}
a = 1
a = 1
a = 2
Please note that there is no boolean type in the C programming language. Hence,
every nonzero value is true. The value 0 means false, including 0.0, -0, +0, etc.
Examples:
• 5>6 is false.
• 3==3 is true.
• 20!=20 is false.
• 8<8 is false.
19
3. Operations
.
A common way to present the evaluation of logical expressions is by using truth
tables. The truth table of logical AND, OR, and NOT is given in Table 3.5.
A B A && B A || B !A
true true true true false
true false false true false
false true false true true
false false false false true
.
In the C programming language, all logical expressions are evaluated from left
to right. Evaluation is performed as long as the compiler is not certain of the result.
For example, for a=50, when evaluating (a<20) && (a>5) only the first part (a<20)
will be evaluated. Since the evaluation result of the first part is false, the further
evaluation will stop, and the compiler will return 0 (false).
When we evaluate the logical expressions, the following rules regarding the
priorities of the logical operators should be taken into consideration:
• Operator ! - NOT is with the highest priority, and it is executed first. Also, its
priority is higher than multiplication and division. It has the same priority as
increment and decrement operations.
20
3.5. Cast operations
• Operator && - AND has higher priority than || - OR, and it is executed second.
Both operators, && and ||, have lower priority than relational operators.
(data type)value;
Examples:
• (char)87 will convert 87 into W (87 is ASCII code for the W character).
int i;
double d = 6.28;
i = (int) d;
Exercises:
#include <stdio.h>
int main()
{
int i = 65;
float f = 22.8;
char c;
c = (char)i + (char)f;
printf("c = %c \n",c);
return 0;
}
21
3. Operations
#include <stdio.h>
int main()
{
int a=10, b=4;
double c;
c = (double)a/b;
printf("c = %f, ",c);
c = a / (double)b;
printf("c = %f, ",c);
c = (double)a / (double)b;
printf("c = %f, ",c);
c = (double)(a/b);
printf("c = %f, ",c);
return 0;
}
22
CHAPTER 4
Selection structures
{
double temp, a=0, b=15;
temp=a;
a=b;
b=temp;
}
23
4. Selection structures
if (condition)
statement_for_a_true_condition;
else
statement_for_a_false_condition;
In case of a block of statements, the beginning and the end of the block are
marked with brackets. The general structure of the if statement in case of block of
statements is as follows:
if (condition)
{
block_of_statements_for_a_true_condition;
}
else
{
block_of_statements_for_a_false_condition;
}
The else part is not mandatory. In case the else part is not necessary, the structure
of the if statement as follows:
if (condition)
statement_for_a_true_condition;
In case of a block of statements, the beginning and the end of the block are
marked with brackets. The general structure of the if statement in case of block of
statements is as follows:
if (condition)
{
block_of_statements_for_a_true_condition;
}
24
4.1. if and if/else statements
if (condition1)
{
block_of_statements_for_a_true_condition1;
}
else
if (condition2)
{
block_of_statements_for_a_true_condition2;
}
else
{
block_of_statements_for_a_false_condition2;
}
Exercises:
25
4. Selection structures
1. Write a C program that checks whether the letter entered by the user is a
vowel.
Solution:
#include <stdio.h>
int main(){
char c;
return 0;
2. Write a C program that asks the user to enter the points that he gains on the
exam and return some message based on the input:
• If the input is in the range 51-100, print "You pass the exam."
• If the input is in the range 0-50, print "You fail the exam."
• For any other number, print "The points that you entered are not correct."
Solution:
#include <stdio.h>
int main(){
int points;
26
4.1. if and if/else statements
return 0;
3. Write a C program that checks whether a number entered from the keyboard
is even or odd.
Solution:
#include <stdio.h>
int main(){
int number;
if(number % 2 == 0){
printf("The number is even\n");
} else{
printf("The number is odd\n");
}
return 0;
4. Write a C program that asks the user to enter a number and print: “positive”
if the number is positive, “negative” if the number is negative, “zero” if the
number is zero.
Solution:
#include <stdio.h>
int main(){
int number;
27
4. Selection structures
return 0;
Solution:
#include <stdio.h>
int main(){
int year;
return 0;
6. Write a C program that finds the smallest of three numbers entered from the
keyboard.
Solution:
#include <stdio.h>
int main(){
28
4.1. if and if/else statements
} else {
printf("The smallest number is %.2f\n", n3);
}
}
return 0;
7. Write a C program that asks the user to enter three numbers and checks
whether they can be sides of a triangle or not.
Solution:
#include <stdio.h>
int main(){
float a, b, c;
return 0;
8. Write a C program that asks the user to enter the price of the product and
calculate the new discounted price based on the following criteria:
• If the price is less than 1.000 denars - 0% discount,
• If the price is in the range of 1.001-10.000 denars - 5% discount
• If the price is over 10.001 denars - 10% discount
Solution:
#include <stdio.h>
int main(){
int price;
int discount;
29
4. Selection structures
return 0;
switch(expresion)
{
case constant1: block_statements1; break;
case constant2: block_statements2; break;
...
case constantN: block_statementsN; break;
default: block_statements;
}
When a switch statement is created, the following rules and conditions must be
taken into account:
• The program continues with the evaluation after the case statement by receiving
the value of the evaluated expression from the switch statement.
• All further statements are executed until a break statement has been reached
or until the last case block.
• If there is no case statement with a given value, the default block’s statements
are executed.
• If there is no default block, then none of the statements will be executed. The
execution will continue from the end of the switch statement.
30
4.2. Switch statement
#include <stdio.h>
int main()
{
char c;
c = getchar();
switch (c)
{
case ’0’: printf("zero"); break;
case ’1’: printf("one"); break;
case ’2’: printf("two"); break;
31
4. Selection structures
Solution: This program reads a character from the keyboard, and if the input
is a digit, it will print the name of the digit. In case the input is not a digit, it
will print "not a digit" on the screen.
2. Write a C program that asks the user to enter the month number and print the
month’s name on the screen. If the number is not in the range of 1-12, print
"Incorrect number.".
Solution:
#include <stdio.h>
int main(){
int month;
char monthName[10];
switch(month){
case 1:
printf("Month name is January");
break;
case 2:
printf("Month name is February");
break;
case 3:
printf("Month name is March");
break;
case 4:
printf("Month name is April");
break;
case 5:
printf("Month name is May");
break;
case 6:
printf("Month name is June");
break;
case 7:
printf("Month name is July");
break;
case 8:
32
4.2. Switch statement
printf("\n");
return 0;
Solution:
#include <stdio.h>
int main(){
char operator;
float nr1, nr2, result = 0;
switch (operator) {
case ’+’:
result = nr1 + nr2;
printf("The result of the operation is: %.2f %c %.2f = %f"
, nr1,
operator, nr2, result);
break;
case ’-’:
result = nr1 - nr2;
printf("The result of the operation is: %.2f %c %.2f = %f"
, nr1,
operator, nr2, result);
break;
33
4. Selection structures
case ’*’:
result = nr1 * nr2;
printf("The result of the operation is: %.2f %c %.2f = %f"
, nr1,
operator, nr2, result);
break;
case ’/’:
if (nr2 == 0) {
printf("Error: Division with 0.\n");
}
else {
result = nr1 / nr2;
printf("The result of the operation is: %.2f %c %.2f =
%.2f", nr1,
operator, nr2, result);
}
break;
default:
printf("Unknown operator %c\n", operator);
break;
}
printf("\n");
return 0;
34
CHAPTER 5
Repetition structures
• While loop.
• Do-while loop.
• For loop.
While and for loop, check the boolean expression on the entry. The do-while
loop checks the boolean expression on the exit.
All three types loops are working almost similar. However, they can be used
in different scenarios. It is up to the programmer to choose the loop based on the
requirement of the program.
while (expresion)
statement;
In case of a block of statements, the beginning and the end of the block are
marked with brackets. The general structure of the while loop in case of block of
statements is as follows:
35
5. Repetition structures
while (espresion)
{
block_statements;
}
Exercises:
1. Write a C program that calculates the factorial of a number.
Solution:
#include <stdio.h>
int main(){
temp = num;
36
5.1. While loop
return 0;
2. Write a C program that counts how many dividers have a number entered by
the user.
Solution:
#include <stdio.h>
int main(){
return 0;
3. Write a C program that will find the sum of digits from a number entered by
the user.
Solution:
#include <stdio.h>
int main(){
temp = num;
37
5. Repetition structures
return 0;
4. Write a C program that from an unknown number of numbers will print the
total sum of all number’s most significant digit.
Solution:
#include <stdio.h>
int main(){
return 0;
5. Write a C program that checks if the number can be divided with its sum of
even digits.
Do not use %2 in your code, and solve the problem using a WHILE loop.
Solution:
#include <stdio.h>
int main(){
38
5.1. While loop
temp = num;
if((digit / 2) * 2 == digit){
sumOfEvenDigits += digit;
}
temp /= 10;
}
return 0;
6. Write a C program that from an unknown number of numbers will print and
count the numbers larger than 10000 that satisfy the condition: the first two
digits are smaller than the last two digits.
Solution:
#include <stdio.h>
int main(){
firstTwo = num;
39
5. Repetition structures
return 0;
7. Write a C program that, from an unknown number of numbers, will print the
total sum of all numbers factorials.
Solution:
#include <stdio.h>
int main(){
factorial = 1;
totalSum += factorial;
}
return 0;
8. Write a program that from an unknown number of numbers will print and
count all numbers greater than 100, that its sum of digits is divisible with the
number of digits.
Solution:
40
5.2. Do-while loop
#include <stdio.h>
int main(){
return 0;
do
statement;
while (expresion);
In case of a block of statements, the beginning and the end of the block are
marked with brackets. The general structure of the do-while loop in case of block of
statements is as follows:
41
5. Repetition structures
do
{
block_statements;
}
while (expresion);
Exercises:
1. Write a C program that asks the user to enter numbers until they enter
something different from a number. The program should display the largest
and smallest entered numbers.
Solution:
#include <stdio.h>
int main(){
42
5.2. Do-while loop
scanf("%d", &num);
do {
if(num < min){
min = num;
}
return 0;
Solution:
#include <stdio.h>
int main(){
temp = num;
do {
digit = temp % 10;
reversed = reversed * 10 + digit;
temp /= 10;
} while(temp > 0);
return 0;
3. Write a C program that from an unknown number of numbers will count and
print all numbers that satisfy the condition: the number is divisible by the
sum of its first and last digit.
43
5. Repetition structures
Solution:
#include <stdio.h>
int main(){
firstDigit = num;
return 0;
In case of a block of statements, the beginning and the end of the block are
marked with brackets. The general structure of the for loop in case of block of
statements is as follows:
44
5.3. For loop
The initial values of the counters are usually set in the first part - initialization.
for(i = 1; ...
In the for loop, the condition is a boolean expression tested after the initialization
part. While the condition is satisfied, the loop is incremented or decremented, and
the loop statements are repeated. The statements of the loop are repeated multiple
times, or never at all.
In each of parts, any other statement can be placed. It is also possible, some of
the parts or all parts to be left empty.
In each of three parts, various statements can be placed, but the order of their
executions and interpretation of results are strictly defined as follows:
• First, the initialization part is executed at the beginning. This part is executed
before entering the loop.
• Next, the statements in the second part - conditions are executed. They are
executed before the beginning of every new iteration of the loop. They result
in a boolean value. If the boolean value is a logical truth, it will cause another
execution of the statements in the loop. If the boolean value is a logical false,
the loop ends, and the statements after the loop are executed.
45
5. Repetition structures
46
5.3. For loop
Exercises:
1. Write a C program that calculates the sum of the first N numbers. N is entered
from the keyboard.
Solution:
#include <stdio.h>
int main(){
int n, i, sum = 0;
return 0;
2. Write a C program that checks whether a number entered from the keyboard
is a prime number.
Solution:
#include <stdio.h>
int main(){
if(isPrime){
printf("The number %d is prime number\n", num);
}
47
5. Repetition structures
else{
printf("The number is %d NOT prime number\n", num);
}
return 0;
3. Write a C program that will find and print the number of digits of a number
entered by the user.
Solution:
#include <stdio.h>
int main(){
temp = num;
return 0;
4. Write a C program that prints on the screen the multiplication table from 1 to
10. The output should be similar to:
1x1=1
1x2=2
etc.
Solution:
#include <stdio.h>
int main(){
int i, j;
48
5.3. For loop
return 0;
5. Write a C program that checks whether a number entered from the keyboard
is a palindromic number.
Solution:
#include <stdio.h>
int main(){
temp = num;
if(num == reversed){
printf("The number %d is a palindromic number\n", num);
}
else{
printf("The number %d is a NOT palindromic number\n", num);
}
return 0;
6. Write a C program that prints and counts all numbers from a certain range
divisible by 6. Do not use %6 in your code
Solution:
#include <stdio.h>
int main(){
49
5. Repetition structures
return 0;
7. Write a C program that finds all numbers in a given range that its most
significant digit is larger than the number next to the most significant digit.
Solution:
#include <stdio.h>
int main(){
return 0;
Solution:
50
5.3. For loop
#include <stdio.h>
int main(){
j = 1;
if(num == sumOfDivisors){
printf("Perfect number found %d\n", num);
}
}
return 0;
Solution:
#include <stdio.h>
int main(){
temp = num;
51
5. Repetition structures
totalSum += digit*digit*digit;
temp /= 10;
}
if(totalSum == num){
printf("%d is an Armstrong number\n", num);
}else{
printf("%d is NOT an Armstrong number\n", num);
}
return 0;
#include <stdio.h>
int main()
{
int i = 0;
for (;;++i)
{
if(i > 9999)
break;
}
printf("%d",x);
return(0);
}
The continue statement passes control to the next iteration of the loop by jumping
the remaining statements after the continue. The program control resumes at the
next iteration of the loop.
Example:
#include <stdio.h>
int main()
{
52
5.4. Statements for controlling program execution
int i;
for(i=0; i<10; i++)
{
if(i<5)continue;
printf("%d\n", i);
}
return 0;
}
5
6
7
8
9
The goto statement passes control to code location where a label of the goto
statement is put. The program control resumes at the next iteration after the label.
The basic structure of the goto statement is as follows:
goto (label);
53
5. Repetition structures
label:
54
CHAPTER 6
Functions
Function is a block of code that is used to perform a specific task. Functions usually
receive some data as an input, process it, and return some result. Once a function
is written, it can be reused multiple times. Functions make programming simpler.
Every function executes a strictly defined job, useful for other parts of the program
and other programs. The rest of the program does not need to “know” how the job is
performed.
Using functions is similar to a boss giving a task to an employee. Every worker
gets information, does the job, performs the task, and gives results back. Information
hiding: the boss does not need to know the details of how the job was performed.
Only the results are of interest to the boss.
The advantages of using functions are as follows:
6.1 Functions in C
In the C programming language, programs are combinations of user-defined functions
and predefined functions that are part of the libraries. Standard C libraries contain a
large number of various functions.
Using functions in a program is called function calls. When a function is called,
a name and arguments for the function are provided.
The format of the function call is as follows:
nameOfFunction(list of arguments)
55
6. Functions
Example:
In the example above, the function sqrt is called, calculating the square root of
the argument - 81.
In the C programming language, the arguments of the function can be:
• Constant
• Variables
• Expressions
• Global - defined outside of functions and can be used by all functions in the
program. These variables exist as long as the program runs.
• Local - exists only in functions or blocks of code where they are declared.
They didn’t exist in any other functions and blocks of code. These variables
are destroyed when the function ends or the block of code where the variable
is declared ends. They are recreated each time the function is called, or the
block of code is executed.
When variables are created, several rules should be taken into consideration:
• Global variables can be used anywhere in the program but always after they
are declared;
• Local variables declared in a block of code can be used only in that block;
• Two variables cannot have the same name in the same scope.
Local variables can be declared in any block of code. Local variables are
recreated at the beginning of every block’s repetition and are accessible in the block
and all nested blocks. Once the block ended, the local variables are destroyed. For
example, in the following code,
56
6.2. Scope of the variables
the local variable a exists only within the for loop. In each iteration of the loop,
memory is reserved, the variable is initialized and destroyed eventually.
• Temporary. Temporary variables are created and initialized when the block
of code is executed. They are terminated when the block in which they are
declared ends. Usually, local variables are temporary.
The following keywords are used to determine when and where variables will be
created and destroyed:
• static
• auto
• extern
• register
Variables declared as static are created and initialized once, with the first call of
the function. During the consecutive calls to the function, the static variables are not
recreated or reinitialized. When the function ends, the variable still exists, but the
other variables cannot access it.
The variables declared as auto behave completely differently. They are created
when the function starts and are destroyed when the function ends. Temporary
variables are called automatic because memory space is automatically allocated for
them. The auto qualifier can be used to mark this type of variable, although it is
omitted in praxis.
The variables declared as extern are variables that are only declared but not
defined. It means that there is no memory allocated for these variables.
The variables declared as register are variables that are stored in the CPU
registers instead of a memory. This allows the register variables to be faster
accessible compared to the other types of variables.
In the listing below, it is given an example of using static and auto variables.
#include <stdio.h>
void StaticAndAuto(void)
{
57
6. Functions
auto int a = 0;
static int s=0;
printf("auto = %d, static = %d\n", a, s);
a++;
s++;
}
int main()
{
for(int i=0;i<3;i++)
{
StaticAndAuto();
}
return 0;
}
"auto = 0, static = 0
auto = 0, static = 1
auto = 0, static = 2
int SomeFunction(){...}
is same as:
58
6.3. Defining and using functions
SomeFunction(){...}
type var1, type var2, ... is list of formal arguments/parameters of the function. If
there is more than one argument/parameter, they are separated by commas. Variables
are declared in a list. Functions can be without formal arguments/parameters,
i.e., the list can be empty. Variables declared in the list of arguments/parameters
can be used only in the function’s body. Theoretically, the number of formal
arguments/parameters is unlimited, but it is limited in reality. The general
recommendation is to avoid using a large number of parameters.
The body of a function contains the same elements as the main() function. It
includes variables declaration and statements. Variables that are declared in the
function are local to that function.
Example: C program that uses a function to calculates the factorial of a number.
#include <stdio.h>
void calc_factoriel(int n)
{
int i, fact_num = 1;
for( i = 1; i <= n; ++i )
fact_num *= i; printf("The factorial of %d is %d\n", n, fact_num);
}
int main()
{
int number = 0;
printf("Enter a number\n"); scanf("%d", &number); calc_factoriel(number);
return 0;
}
Enter a number
3
The factorial of 3 is 6
If the function is declared void, then the function ends when the return; statement
is met, or a closing bracket } is met. Example:
If the function is declared as returning a value, then the function ends when
return expression; statement is met. The type of expression value returned must be
59
6. Functions
Example:
#include<stdio.h>
int add_numbers(int a, int b)
{
int c=a+b;
return c;
}
int main()
{
int sum;
sum=add_numbers(3, 5);
printf("The sum is %d\n",sum);
return 0;
}
• The type of real arguments is the same as the type of formal arguments.
If they are not the same, the compiler will first try to "translate" the passed
value into the type of formal arguments. If the "translation" is possible, the
call can be made, but the result might be wrong. If the "translation" is not
possible, the compiler will give an error.
For every formal argument, when passing by value, a new variable is created.
The variable is initialized with the value of the real argument. Any change to this
variable will not affect the value of the real argument passed. This will avoid any
unwanted effects produced by the changes to the formal parameter.
It is also possible for a function to have several return statements. Example:
Exercises:
60
6.3. Defining and using functions
Solution:
#include <stdio.h>
void printHello(){
printf("My first C Function!\n");
}
int main(){
printHello();
return 0;
}
Solution:
#include <stdio.h>
int main(){
int n;
Solution:
#include <stdio.h>
61
6. Functions
int main(){
float a, b;
printf("The area of the rectangle with sides %.2f and %.2f is %.2f
\n", a, b ,area(a,b));
return 0;
Solution:
#include <stdio.h>
int main(){
char text[100];
printMessage(text);
return 0;
Solution:
#include <stdio.h>
62
6.3. Defining and using functions
int main(){
int n;
if(isDivisibleBySix(n)){
printf("The number is divisible by 6\n");
}
else{
printf("The number is NOT divisible by 6\n");
}
return 0;
6. Write a C function that checks if the number can be divided with its sum of
even digits.
Solution:
#include <stdio.h>
digit = n % 10;
if(digit % 2 == 0){
sum += digit;
}
n /= 10;
}
return sum;
}
int main(){
int n;
63
6. Functions
if(checkNumber(n)){
printf("The number can be divided with it\’s sum of even
digits\n");
}
else{
printf("The number can NOT be divided with it\’s sum of even
digits\n");
}
return 0;
7. Write a C function that determines if the number inputted from the keyboard
is larger than 500, is prime, and its last digit is 7.
Solution:
#include <stdio.h>
int y = 2;
return 1;
}
int main(){
int n;
if(checkNumber(n)){
printf("The number satisfies the condition\n");
}
else{
printf("The number does not satisfy the condition\n");
}
64
6.3. Defining and using functions
return 0;
8. Write a C program that uses a function to find all numbers in a given range that
its most significant digit is larger than the number next to the most significant
digit. Write a main() function where the user enters the start and the end of
the range and tests the previously defined function.
Solution:
#include <stdio.h>
int i;
int main(){
findNumbers(start, end);
return 0;
9. Write a C program that from an unknown number of numbers will print and
count the numbers larger than 10000 that satisfy the condition: the first two
digits are smaller than the last two digits. The checking is done by a separate
function called checkNumber(int). The program ends when the user enters
something different than a number.
65
6. Functions
Solution:
#include <stdio.h>
int main(){
int n;
while(scanf("%d", &n)){
if(checkNumber(n)){
printf("Number found %d\n", n);
}
return 0;
10. Write a C program that from an unknown number of numbers will print the
total sum of all number’s most significant digits. Use a function for extracting
the most significant digit of the number. Write a main function to test your code.
Solution:
#include <stdio.h>
66
6.4. Recursive functions
return n;
int main(){
int n, sum = 0;
while(scanf("%d", &n)){
sum += extractFirstDigit(n);
return 0;
67
6. Functions
sum(n)=n+sum(n-1)
sum(n-1)=(n-1)+sum(n-1)
.............
sum(0)=0 <---- Basic case
sum(0)=0
sum(1)=1+sum(0)=1+0=1
sum(2)=2+sum(1)=2+1=3
sum(3)=3+sum(2)=3+3=6
sum(4)=4+sum(3)=4+6=10
sum(5)=5+sum(4)=5+10=15
......
1. Every recursive algorithm MUST have a basic case, i.e., an expression that
solves the problem. In the previous example, it was sum(0)=0.
2. The other part of the algorithm is called general case, i.e., a recursive
connection. This part MUST simplify the initial algorithm.
In order to write a recursive function, firstly, the basic case and the general case
needs to be determined. Every recursive call must solve part of the problem or to
reduce the problem complexity.
Exercises:
Solution:
#include <stdio.h>
if(n == 1){
return 1;
}
else{
return n * factorial(n-1);
}
int main(){
68
6.4. Recursive functions
int n;
return 0;
Xn
Solution:
#include <stdio.h>
if(n == 1){
return x;
}
else{
return x * power(x, n-1);
}
int main(){
int n, x;
return 0;
Solution:
#include <stdio.h>
69
6. Functions
if(n == 0){
return 0;
}
else if(n == 1){
return n;
}
else{
return fibonnacci(n-1) + fibonnacci(n-2);
}
int main(){
int i, n;
return 0;
Solution:
#include <stdio.h>
int main(){
int n;
return 0;
70
6.5. Function prototype
Solution:
#include <stdio.h>
int main(){
int n;
return 0;
type nameOfFunction(listOfParameters);
where:
• type is the data type of the value returned by the function. If the type is not
defined, the default is int.
• nameOfFunction is the name of the function.
71
6. Functions
The prototype ends with a semicolon ";", and it marks that a function is only
declared and not completely defined.
Below, examples of function prototypes are given.
void printarray(void);
- No values are sent, no value is returned.
int find(void);
- No values are sent, an integer value is returned.
Exercises:
#include <stdio.h>
int main()
{
int a, b;
printf("Enter two integer numbers: ");
scanf("%d%d", &a, &b);
printf("The smaller is: %d\n", smaller(a, b) );
return 0;
}
int smaller(int a, int b)
{
if (a > b)
return b;
else
return a;
}
Solution: The function smaller is defined after the main function, i.e., after it
was used. Hence, a declaration (prototype) of a function is required before the
main function. The program should be written like this:
#include <stdio.h>
int smaller(int, int);
int main()
{
int a, b;
printf("Enter two integer numbers: ");
scanf("%d%d", &a, &b);
72
6.5. Function prototype
73
CHAPTER 7
Arrays
Arrays are homogeneous, linear data structures that can store collections of the same
type. An array is a variable containing more elements of the same type. It can be
seen as a collection of individual elements with a common name, enabling access to
the elements.
Arrays can have multiple dimensions. Therefore the arrays can be:
• One-dimensional (vectors)
• Two-dimensional (matrices)
7.1 Arrays in C
In the C programming language, an array is a structure with related data where the
number of elements is known in advance. All elements of the array are variables of
the same type. By definition, an array is a collection of variables of the same type
placed in an array of consecutive memory locations, given a unique common name.
To access an element of the array, the name and the position of the element
is used. The position is determined by an index. Each element of the array is a
variable that can be assigned with a value. Figure 7.1 presents an example of a
one-dimensional array.
75
7. Arrays
type nameOfArray[NumberOfElements];
where:
• type is the data type of the elements of the array. All elements must be of the
same type.
• nameOfArray is the name of the array.
• NumberOfElements is the number of elements of the array.
Exercises:
1. Declare: one-dimensional array consists of 50 integers; one-dimensional array
consists of 100 double-precision floating-point numbers; one-dimensional
array consists of 10 single-precision floating-point numbers, and two one-
dimensional arrays consist of 40 and 35 characters.
Solution:
int A[50];
double temp[100];
float b[10];
char c[40], temp1[35];
2. Why the declarations presented below, are not the correct way to declare an
array?
char c;
int a;
int a[i];
float b[j];
double d[];
Solution:
• char c; and int a; are valid declaration for variables, not for an array.
For array declaration we need to specify the number of elements of the
array in [ ] (square brackets).
• In int a[i]; and float b[j]; the number of elements of the array is not
defined, i.e., i and j are variables from unknown type with unknown
value. If i and j already have some integer value, this will be correct way
to declare an array.
76
7.3. Accessing elements of arrays
If the number of initialization values is less than the array’s size, the remaining
elements are initialized with 0.
During the initialization, the length of the array can be omitted. The compiler
will automatically determine it based on the number of values provided in the
initialization.
Another way to initialize an array is by using a for loop. This is the most
commonly used way to initialize an array. In the example below, the initialization of
an array with elements entered from the keyboard is presented:
#include <stdio.h>
int main()
{
int a[10], i;
nameOfArray[IndexPosition];
77
7. Arrays
where:
When accessing the elements of an array, C compilers do not check the boundaries
of the array. It is a programmer’s responsibility for the index to be in the interval of
[0] to [N-1]. For example, if this definition is given:
int a[10];
a[5] = a[-5];
a[50] = a[180] + a[-92];
But using an index outside of the boundaries of the array causes the program to
access location outside of the array.
The operator that determines the index of the array has the highest priority.
Therefore the statement a[0]++ will increase the value of the first element of the
array for 1.
Exercises:
1. Write a C program that reads an array from the keyboard. If the user enters
less than 100 numbers, fill the remaining elements with 1. Print the array to
test your code.
Solution:
#include <stdio.h>
int main(){
int a[100], i, n;
78
7.3. Accessing elements of arrays
return 0;
2. Write a C program that prints the number of days in each month of the year.
Solution:
#include <stdio.h>
int main() {
int i,
months[] = {31,28,31,30,31,30,31,31,30,31,30,31};
return 0;
3. Write a C program that calculates the sum of two arrays and puts the result in
a new array.
Solution:
#include <stdio.h>
int main() {
int i,c[5],
a[] = {1,2,3,4,5},
b[] = {1,1,1,1,1};
return 0;
79
7. Arrays
4. Write a program that calculates the average of 10 numbers. For every number
print, whether it is bigger or smaller than the average.
Solution:
#include <stdio.h>
int main() {
int num[10], n;
float avg=0;
printf("Enter numbers:\n");
for(n=0; n<10; n++)
scanf("%d",&num[n]);
avg/=n;
return 0;
5. Write a C program that checks if two arrays are completely identical. Note:
Two arrays are identical if they have the same number of elements and if
elements on identical positions in both arrays have identical values.
#include <stdio.h>
int main() {
int i, AreSame,
a[] = {1,2,3,4,5},
b[] = {1,2,3,4,5},
n1 = sizeof(a) / sizeof(a[0]), n2 = sizeof(b) / sizeof(b[0]);
if(n1 == n2) {
for(AreSame = 1, i=0; AreSame && (i<n1); i++)
if(a[i]!=b[i])
AreSame = 0;
}
else
80
7.4. Passing arrays as parameters to a function
AreSame = 0;
if (AreSame)
printf("Arrays are identical");
else
printf("Arrays are NOT identical");
return 0;
someFunction(nameOfArray[IndexPosition])
To pass the entire array to a function, the programmer needs to pass only the
array’s name as an argument. The format is as follows:
someFunction(nameOfArray)
Exercises:
Solution:
#include <stdio.h>
#define SIZE 10
81
7. Arrays
return average/SIZE;
}
int main(){
int i;
float a[SIZE];
2. Write a C program that reads elements of an array, and after that, print them
on the screen in reverse order.
Solution:
#include <stdio.h>
int i;
int i;
82
7.4. Passing arrays as parameters to a function
int main(){
int a[100], n;
enterArray(a, n);
printInReverse(a, n);
return 0;
}
3. Write a C program that finds the maximum element of an array. The size of
the array and the elements are entered from the keyboard.
Solution:
#include <stdio.h>
int i;
int i;
float max = a[0];
return max;
int main(){
int n;
float a[100];
83
7. Arrays
enterArray(a, n);
return 0;
}
Solution:
#include <stdio.h>
int i;
int i;
float maxNegative = 1;
return maxNegative;
int main(){
int n;
float a[100];
float largestNegative;
84
7.4. Passing arrays as parameters to a function
enterArray(a, n);
return 0;
}
5. Write a C program that reads from the keyboard the daily temperatures for each
day in the month. The program should print the average monthly temperature,
the hottest and the coldest day in the month. The user enters the number of
days in the month.
Solution:
#include <stdio.h>
#define SIZE 30
int i;
int i, maxI = 0;
float max = a[0];
printf("The hottest day was day %d, and it was %.1fC\n", maxI+1,
max);
85
7. Arrays
int i, minI = 0;
float min = a[0];
printf("The coldest day was day %d, and it was %.1fC\n", minI+1,
min);
int i;
float average = 0;
return average/SIZE;
}
int main(){
float a[SIZE];
enterTemperatures(a);
findColdest(a);
findHottest(a);
return 0;
}
Solution:
#include <stdio.h>
86
7.4. Passing arrays as parameters to a function
int i;
int i, j;
float temp;
int main(){
int n;
float a[100];
enterArray(a, n);
sortArray(a, n);
printArray(a, n);
return 0;
}
Solution:
#include <stdio.h>
87
7. Arrays
int i;
int i, j, k = 0, l;
int found;
float b[n];
if(a[i] == a[j]){
found = 0;
if(!found){
b[k++] = a[j];
}
}
}
}
int main(){
int n;
float a[100];
enterArray(a, n);
printDuplicates(a, n);
88
7.4. Passing arrays as parameters to a function
return 0;
}
8. Write a C program that prints all numbers from an array that are divisible with
the number before them.
Solution:
#include <stdio.h>
int i;
int main(){
int a[100], n;
enterArray(a, n);
findNumbers(a, n);
return 0;
}
9. Write a C program that reads 50 numbers. The program will print the number
that appears most frequently in the array and the number of times this number
appears.
Solution:
#include <stdio.h>
89
7. Arrays
#define SIZE 5
int i;
return -1;
}
int foundNumbers[SIZE];
int count[SIZE];
if(foundIndex == -1){
foundNumbers[k] = a[i];
count[k]++;
k++;
}
else{
count[foundIndex]++;
}
90
7.4. Passing arrays as parameters to a function
int main(){
int a[SIZE];
enterArray(a);
findAppearances(a);
return 0;
}
10. Write a C program that finds and prints all pairs of elements in an array whose
sum is greater than the smallest positive number of the array.
Solution:
#include <stdio.h>
int i;
return smallestPositive;
}
91
7. Arrays
int i;
float smallestPositive = findSmallestPositiveNumber(a, n);
if(smallestPositive == -1){
printf("There are no positive numbers in the array.\n");
}
else{
printf("Smallest positive number is %.2f\n", smallestPositive)
;
for(i = 0; i < n - 1; i++){
if(a[i] + a[i+1] > smallestPositive){
printf("Pair found: %.2f and %.2f\n", a[i], a[i+1]);
}
}
}
}
int main(){
int n;
float a[100];
float smallestPositive;
enterArray(a, n);
findAndPrintPairs(a, n);
return 0;
}
11. Write a C program that will swap the second smallest with the second biggest
number of the array. Print the result to test your code.
Solution:
#include <stdio.h>
int i;
int i, initialIndex = 0;
92
7.4. Passing arrays as parameters to a function
return secondMaxIndex;
int i, initialIndex = 0;
float initialValue = a[0];
93
7. Arrays
min1Index = i;
}
else if(a[i] < min2 && a[i] != min1){
min2 = a[i];
min2Index = i;
}
return min2Index;
int main(){
enterArray(a, n);
return 0;
}
12. Write a C program that will remove all elements in an array smaller than some
number entered by the user.
Solution:
#include <stdio.h>
94
7.4. Passing arrays as parameters to a function
int i;
int i = 0, j, p;
n--;
return n;
}
int main(){
enterArray(a, n);
n = removeElements(a, n, number);
95
7. Arrays
return 0;
}
13. Write a C program that will remove all odd elements in an array.
Solution:
#include <stdio.h>
int i;
int i = 0, j, p;
n--;
if(a[i] % 2 == 0){
i++;
}
}
else{
i++;
}
}
return n;
}
96
7.4. Passing arrays as parameters to a function
int main(){
int a[100], n;
enterArray(a, n);
n = removeOddElements(a, n);
return 0;
}
14. Write a C program that finds and prints the size of the longest consecutive
sequence of elements from a given unsorted array of integers. Sample array:
[9, 124, 13, 130, 16, 14, 179, 15]. The longest consecutive sequence of
elements is [13, 14, 15, 16]. The size is 4.
Solution:
#include <stdio.h>
#include <stdlib.h>
int i;
97
7. Arrays
tempLength = 1;
j = i;
int main(){
int a[100], n;
enterArray(a, n);
consecutiveSsequence(a, n);
return 0;
}
98
CHAPTER 8
Matrices
As described in the previous chapter, the arrays can have multiple dimensions:
one-dimension, two-dimensional, etc. Matrices are two-dimensional arrays in which
elements are arranged in a grid with rows and columns.
8.1 Matrices in C
In the C programming language, a matrix is a table with related data where the
number of elements is known in advance. All elements of the matrix are variables
of the same type. By definition, a matrix is a collection of variables of the same type
placed in an array of consecutive memory locations, given a unique common name.
To access an element of the matrix, the name and the position of the element is
used. The position is determined by the index of the row and the index of the column
(m by n elements). Each element of the matrix is a variable that can be assigned
with a value. Figure 8.1 presents an example of a two-dimensional array.
99
8. Matrices
type nameOfMatrix[NumberOfRows][NumberOfColumns];
where:
• type is the data type of the elements of the matrix. All elements must be of
the same type.
Exercises:
Solution:
int a[10][10];
float b[3][4];
double c[4][3];
2. How many elements has the matrix with a declaration: int a[10][10]?
Solution: 10 integer elements.
3. Which is the first element of the matrix with a declaration: int a[10][10]?
Solution: The first element is a[0][0].
The initialization of a matrix can be done within the declaration. For example,
the initialization can be done as follows:
When you initialize the matrix, the inner brackets are not mandatory, but some
compilers can give you a warning "missing braces around initializer" if you miss
them.
100
8.2. Declaring and initialization of matrices
int a[3][3] = { {1, 2, 3}, {5}, {4, 1} }; /* Will initialize the matrix as:
1 2 3
5 0 0
4 1 0 */
int b[3][4] = {{0}}; /* The easiest way to initialize a matrix with all 0’s.
*/
During the initialization, the first dimension (number of rows) of the matrix can
be omitted. The compiler will automatically determine it based on the number of
values provided in the initialization. The second dimension (number of columns) of
the matrix is mandatory and cannot be omitted.
Another way to initialize a matrix is by using a nested for loops. This is the most
commonly used way to initialize a matrix. In the example below, the initialization of
a matrix with elements entered from the keyboard is presented:
#include <stdio.h>
int main()
{
int a[3][5], i;
101
8. Matrices
{
printf("a[%d][%d]=", i, j);
scanf("%d", &a[i][j]);
}
}
nameOfMatrix[RowIndex][ColumnIndex];
where:
• nameOfMatrix is the name of the matrix.
• RowIndex is the row index.
• ColumnIndex is the column index.
In the C programming language, the index of the first row and column is always
0. In a matrix of N rows and M columns, the index of the last element of the row is
N-1, and of the column is M-1. The index of a matrix can only be an integer value.
For a matrix with a name a, N rows, and M columns, the elements will be as follows:
• a[0][0], a[0][1], ..., a[0][M-1], a[1][0], a[1][1], ..., a[N-1][M-1].
When accessing the elements of an array, C compilers do not check the boundaries
of the array. It is a programmer’s responsibility for the index to be in the interval of
[0][0] to [N-1][M-1]. Using an index outside of the boundaries of the array causes
the program to access location outside of the array.
The operator that determines the index of the array has the highest priority.
Therefore the statement a[0][0]++ will increase the value of the first element of the
array for 1.
C programming language allows the programmer to pass the entire matrix as
a parameter to function. It also allows passing individual elements of a matrix to
function.The individual elements are passed as arguments to a function similar to
any other variables.
The individual elements of a matrix are passed as arguments to a function by
passing the matrix name and the element’s position. The format is as follows:
someFunction(nameOfMatrix[RowIndex][ColumnIndex])
102
8.3. Accessing elements and passing matrices as parameters to a function
To pass the entire matrix to a function, the programmer needs to pass only the
matrix name as an argument. The format is as follows:
someFunction(nameOfMatrix)
Exercises:
Solution:
#include <stdio.h>
int main(){
max = a[0][0];
103
8. Matrices
return 0;
}
Solution:
#include <stdio.h>
int main(){
int i, j, n, m, count = 0;
float a[10][10], number;
return 0;
}
3. Write a C program that initializes a 10x3 matrix. The program should fill the
matrix in such a way so, the first element of each row is a number starting
from 1 to 10, the second element is the square of the number, and the third
element is the cube of the number.
104
8.3. Accessing elements and passing matrices as parameters to a function
Solution:
#include <stdio.h>
int main(){
int a[10][10], i, j;
int number, n = 10, m = 3;
printf("\n");
}
return 0;
}
4. Write a C program that computes the addition of two matrices. The matrices
are inputted from the keyboard.
Solution:
#include <stdio.h>
#define SIZE 10
int main(){
105
8. Matrices
printf("\n");
}
return 0;
}
5. Write a C program that swaps two rows of a matrix. The row numbers are
entered by the user.
Solution:
#include <stdio.h>
#define SIZE 10
int main(){
int a[SIZE][SIZE], i, j, n, m;
int row1, row2, temp;
106
8.3. Accessing elements and passing matrices as parameters to a function
row1 -= 1;
row2 -= 1;
if(row1 == row2){
printf("You entered the same number of row.\n");
return 0;
}
printf("\n");
}
return 0;
}
6. Write a C program that transposes a matrix. The matrix is input from the
keyboard.
Solution:
#include <stdio.h>
#define SIZE 10
107
8. Matrices
int main(){
printf("\n");
}
return 0;
}
7. Write a C program that converts all elements under the primary diagonal of a
matrix to 0’s.
Solution:
#include <stdio.h>
#define SIZE 10
int main(){
int a[SIZE][SIZE];
int i, j, n;
108
8.3. Accessing elements and passing matrices as parameters to a function
printf("\n");
}
return 0;
}
8. Write a C program that finds the minimum element above the secondary
diagonal of a matrix.
Solution:
#include <stdio.h>
#define SIZE 10
int main(){
int a[SIZE][SIZE];
int i, j, n, min;
109
8. Matrices
min = a[0][0];
return 0;
}
9. Write a C program that checks whether the sum of the matrix’s corner elements
is equal to the sum of the elements on the primary diagonal.
Solution:
#include <stdio.h>
#define SIZE 10
int main(){
int a[SIZE][SIZE];
int i, j, n, sumCorner = 0, sumPrimary = 0;
if(i == j){
sumPrimary += a[i][j];
}
110
8.3. Accessing elements and passing matrices as parameters to a function
sumCorner += a[i][j];
}
else if(i == n - 1 && j == n - 1){
sumCorner += a[i][j];
}
}
}
if(sumCorner == sumPrimary){
printf("The sums are identical\n");
}
else{
printf("The sums are NOT indentical\n");
}
return 0;
}
10. Write a C program that will check if a matrix is a magic square. The elements
of the matrix are entered from the keyboard, and the max dimensions are
20x20. A magic square is a matrix where the sum of each row and column’s
elements is identical. If the matrix is a magic square, check whether the
matrix is a special magic square (A matrix where the sum of the elements on
the primary and secondary diagonal is equal to the sum of each row or column).
Solution:
#include <stdio.h>
#define SIZE 20
int main(){
if(i == 0){
sumToCompare += a[i][j];
}
if(i == j){
sumPrimary += a[i][j];
}
111
8. Matrices
if(i + j == n - 1){
sumSecondary += a[i][j];
}
}
}
sum = 0;
if(sum != sumToCompare){
isMagicSquare = 0;
break;
}
}
if(isMagicSquare){
printf("The matrix is a magic sqare\n");
return 0;
}
11. Write a program that will sort the elements of each row of a floating point
number matrix in ascending order.
Solution:
#include <stdio.h>
#define SIZE 10
int main(){
112
8.3. Accessing elements and passing matrices as parameters to a function
printf("\n");
}
return 0;
}
Solution:
#include<stdio.h>
int main()
{
int i, j, n, m, k, p;
float a[100][100], b[100][100], c[100][100];
113
8. Matrices
return 0;
}
13. Write a C program that will swap the columns with the smallest and biggest
product of elements in a matrix.
Solution:
#include <stdio.h>
#define SIZE 10
int main(){
114
8.3. Accessing elements and passing matrices as parameters to a function
products[j] = product;
}
printf("\n");
}
return 0;
}
14. Write a C program that removes the row with the smallest sum of elements in
a matrix.
Solution:
#include <stdio.h>
115
8. Matrices
#define SIZE 10
int main(){
sums[i] = sum;
}
min = sums[0];
minI = 0;
n--;
116
8.3. Accessing elements and passing matrices as parameters to a function
printf("\n");
}
return 0;
}
15. Write a C program that will modify a matrix so that the row with the smallest
and biggest sum of elements are merged (sum) into one row.
Solution:
#include <stdio.h>
#define SIZE 10
int main(){
sums[i] = sum;
}
117
8. Matrices
maxI = i;
}
n--;
printf("\n");
}
return 0;
}
118
CHAPTER 9
Pointers
Pointers are special types of variables that always store addresses of other memory
locations, i.e., point to a memory location at the given address. The pointer contains
an unsigned positive integer interpreted as a memory address where another variable
is stored. Variables contain the value, i.e., direct referencing is used. The pointers
contain variable addresses, i.e., indirect referencing is used. For better understanding
the memory address concept, please see Figure 9.1.
Memory space is allocated for every variable. It holds the value of that variable.
This memory space has an address. For example, we live in a home. Our home has
an address, which helps others to find our home. Similarly, the value of the variable
is stored in a memory address, which helps the computer to find that value when is
needed.
The reason why pointers are so commonly used in programming languages is
rarely mentioned, but we can list several reasons for that, including:
• Complex data structures are easy to manipulate with pointers;
• Pointers enable efficient tools for accessing big memory sets;
• Pointers enable work with dynamically allocated memory.
9.1 Pointers in C
In the C programming language, the value of each pointer is a positive unsigned
integer (memory address). However, the interpretation of the value stored in that
memory location depends on the pointer type. Every pointer is defined with a type.
The type refers to the variable that it points to. When a pointer is declared, its data
type must be declared.
119
9. Pointers
type *pointerName;
where:
• type is the data type of the variable that the pointer will point to. Pointers can
be declared from any data type.
Exercise: Declare four pointers: two that points to integer variables, one that
points to a floating-point variable, and one that points to a variable from type character.
Solution:
Pointer declaration is read in the reverse order, i.e., first, we read the pointer’s
name, followed by the asterisk and the datatype. The asterisk is read as: is a pointer.
For example, int *ptr is read as: ptr is a pointer to an integer.
The operator * (asterisk) or dereferencing operator is a prefix operator that
returns the memory location’s contents in the pointer variable. In the code, the
dereferencing operator * is read as "the content of ..." or "the memory location that
the pointer points to ...".
The operator & (ampersand) is a prefix operator that returns the memory address
where the variable is stored. The operator & is read as "the address of ...".
The operators * and & are inverse. It means that:
A pointer can store the address of a variable of the same datatype or a special
value NULL (or 0). NULL is used to mark an invalid value for the pointer.
Exercise: What will be the output from the following program?
120
9.2. Operations with pointers
#include <stdio.h>
int main(){
return 0;
}
121
9. Pointers
type void (void *) are an exception to this rule. Void pointers or generic pointers can
point to any datatype. No CAST operation is necessary to assign the value of the
pointer into a VOID pointer.
Examples with CAST and assignment operations with pointers:
#include <stdio.h>
int main(){
int a=10, b;
int *ptr, *ptr1;
double c, *ptrD;
void *ptrV;
ptr=&a;
ptr1=ptr;
ptr1=ptr+5;
ptrV=ptr;
ptr1=(int *)ptrV;
ptrD=&c;
ptrD=(double *)ptr;
return 0;
}
Relational operations can also be used with pointers. Any relational expression
(<, <=, ==, !=, >=, >) can be performed over them.
Examples with arithmetic operations with pointers:
• ptr == ptr1;. This expression checks whether ptr and ptr1 points to the same
memory location.
• ptr1 < ptr;. This expression checks whether the element that ptr1 points to is
before the memory location that ptr points to.
The pointer must have a value before dereferencing it. An uninitialized pointer
points to a random unknown memory location. The attempt to place a value in an
uninitialized location gives the error run-time error, or worse, a logical error.
In order to change the contents of variables with a pointer, the pointer must point
to that variable.
int a, *ptr;
ptr = &a;
*ptr = 10; /* This will change the value of (initialize) a to 10. */
122
9.3. Using pointers to functions and arrays
#include <stdio.h>
int main(){
int a, b, c;
int *ptr;
ptr = &a;
*ptr = 10;
ptr = &b;
*ptr = 20;
ptr = &c;
*ptr = 30;
return 0;
}
Besides the standard pointers that we saw in the previous section, three other
types of pointers can be defined in the C programming language. Those types are:
• Constant pointer. This type of pointers cannot change the address they hold,
i.e., they always point to a constant memory location. Once the constant
pointer is initialized to point to some variable, it is impossible to change the
constant pointer to points to another variable.
The format of the statement for declaring a constant pointer is as follows:
123
9. Pointers
Example:
• Pointer to constant. This type of pointers cannot change the value of the
variable they point to, i.e., they always point to a constant. A pointer to
constant can change the address it holds but cannot change the value inside
that address.
The format of the statement for declaring a pointer to constant is as follows:
Example:
Example:
#include <stdio.h>
int main(){
124
9.3. Using pointers to functions and arrays
The name of the array is a constant pointer that points to the first element
of the array. For example, if the array is declared as int arr[100], then arr is a
constant pointer (int *const), and arr keeps the address of the first element of the
array (&arr[0]).
The expressions arr[i] and *(arr + i) are equivalent. They enable access to
the element of the array on a position i. For example, if the array is declared as int
arr[10] and a pointer is declared as int aPtr, then the following is true:
• arr+5 == &arr[5]
When access to an element of an array is made by using the name and the (arr[i]),
the compiler always internally interpreted that as *(arr+i). Therefore, for instance,
instead of arr[5], it is correct (but not recommended) to use 5[arr].
Arithmetic operations over pointers are beneficial when work with arrays. For
instance, if the pointer that points to an array is incremented for the value of 1, it
will start to point to the next element of the array.
Examples with pointers and arrays:
#include <stdio.h>
int main(){
125
9. Pointers
return 0;
}
Passing arguments to a function can be done with pointers. This enables the
function to change the contents of the argument. When a call to the function is made,
the argument’s address is passed with the & operator. Example:
product(&a);
is same as:
126
9.3. Using pointers to functions and arrays
Exercises:
1. Write a C function that swaps the values of two numbers.
Solution:
#include <stdio.h>
int main(){
float a, b;
swap(&a, &b);
2. Write a program in C that calculates the sum of two numbers using pointers.
Solution:
#include <stdio.h>
int main(){
int a, b;
int sum;
int *c = ∑
127
9. Pointers
scanf("%d", &b);
*c = a + b;
return 0;
}
3. Write a C program that copies the elements of one array to another by using
pointers.
Solution:
#include <stdio.h>
int main(){
return 0;
}
Solution:
#include <stdio.h>
int i;
128
9.3. Using pointers to functions and arrays
int i;
int main(){
swapElements(a, b, n);
return 0;
}
Solution:
129
9. Pointers
#include <stdio.h>
int i;
*min = *a;
int main(){
findSmallest(a, n, &min);
return 0;
}
Solution:
#include <stdio.h>
int i;
130
9.3. Using pointers to functions and arrays
int i;
int main(){
float a[100];
int n;
sortArray(a, n);
return 0;
}
7. Write a C function that will accept one array of real numbers and the numbers
of elements of the array. The function should modify the array so that all
numbers with more than 2 divisors are removed (Divisors 1 and the number
131
9. Pointers
#include <stdio.h>
int i;
return total;
}
int i = 0, j;
int i;
132
9.3. Using pointers to functions and arrays
int main(){
int a[100], n;
modifyArray(a, &n);
return 0;
}
8. Write a C function that accepts one array of numbers as input parameters and
the number of elements of the array. The function will remove all elements in
an array smaller than the largest negative number of the array. Use a function
for determining the largest negative number of the array. Write a main()
function to test your code.
*Note: Use pointers notation.
Solution:
#include <stdio.h>
int i;
int i;
float maxNegative = 1;
133
9. Pointers
return maxNegative;
int i = 0, j;
if(largestNegative == 1){
printf("The array does not have any negative numbers.\n\n");
}
else{
while(i < *n){
if(*(a+i) < largestNegative){
for(j = i; j < *n-1; j++){
*(a+j) = *(a+j+1);
}
*n -= 1;
}
else{
i++;
}
}
}
}
int i;
int main(){
float a[100];
int n;
modifyArray(a, &n);
134
9.3. Using pointers to functions and arrays
return 0;
}
9. Write a C function that accepts one array of numbers and the number of
elements of the array. The function will calculate the sum of each two
neighbouring elements from the array so each new element is the result of
the addition. This procedure is repeated until one number left. The function
returns this number. Write a main() function to test the previously defined
function.
*Note: Do not use [x] (squared brackets). Use only pointer notation (*).
Solution:
#include <stdio.h>
int i;
int i;
int i;
return *a;
135
9. Pointers
int main(){
return 0;
}
136
CHAPTER 10
Strings
10.1 Strings in C
In the C programming language, there is no standard data type defined for strings.
There is an agreement for strings to be stored in arrays of chars. According to the
convention, the string’s end is marked with a NULL terminator (a symbol with an
ASCII code 0).
To declare a string, an array of characters should be declared, or a pointer to be
created.
The format of the statement for declaring a string is as follows:
char nameOfString[NumberOfCharacters];
OR
char *nameOfString;
char c[100];
char *c1;
char c2[5] = "ABC";
char *c3 = c2;
char *c4 = "Test string";
char s[] = "test";
In the last example, char s[] = "test", the array will be initialized with five
elements, although only four characters are in the string. The compiler will
137
10. Strings
automatically add one extra slot for the NULL terminator and add it at the end of the
string. Figure 10.1 shows the memory allocation for this example.
The null terminator is automatically removed by the compiler when the string is
printed on the screen. Thus, all operations related to the null terminator are hidden
from the programmer with a high abstraction level.
Let’s suppose that the null terminator is not presented at the end of the string.
In that case, the printf() function will print all symbols until the symbol for null
terminator is found even outside of the array’s range, or the program will end with
an error (segment fault etc.).
Let’s suppose that we define two textual arrays as follows:
When we work with the above arrays of characters, the statement s2 = s1 doesn’t
enable copying the arrays. The reason is that both s2 and s1 are pointers to the first
element of the array. Hence only the address from s1 is copied into s2. But in a case
we print them, the output on the screen will be identical "test" for both of them. The
reason is that after the execution of s2 = s1, both of them points to the same location,
i.e. the location of s1.
Example of initialization of array of characters without null terminator:
#include <stdio.h>
int main()
{
char s[10];
s[0] = ’t’;
s[1] = ’e’;
s[2] = ’s’;
s[3] = ’t’;
printf("%s\n", s);
return 0;
}
test%z- ml3
138
10.2. Entering and printing strings
scanf("%s", str);
The address operator & is omitted because the name of the string is already the
address of the first character. The scanf() function jumps over blank spaces. It takes
all symbols and puts them in str until it found a blank space. scanf() always adds \0
(null terminator) at the end of the array. An array of characters entered with scanf()
will never contain blank spaces. It is not recommended to use %s in scanf(), fscanf(),
and sscanf() because of security reasons. The reason is that the compiler did not
check whether there is enough space to store the string in the user-defined array of
character. It is always good practice to specify the maximum number of characters
that the array can accept ex. to use %9s.
Example
#include <stdio.h>
int main()
{
char s[10];
scanf("%s",s); /* bad */
scanf("%9s",s); /* good */
printf("%s",s);
return 0;
}
Another way to enter a string is by using the getchar() function. The code below
is an example of filling an array of characters. It reads characters (including blank
spaces) until the user presses the ENTER key or enters the maximum number of
characters, i.e., nine characters.
#include <stdio.h>
#define N 10
int main() {
char c, s[N];
int i;
for(i=0; i<(N-1)&&(c=getchar())!=’\n’;i++)
s[i]=c;
s[i]=’\0’;
return 0;
}
The gets() function allows entering string by reading a line entered from the
keyboard in a buffer (memory space) that s points to until it found a \n (new line) or
139
10. Strings
the EOF (end of file) symbol. The function replaces those symbols with the null
terminator \0. It also reads the blank spaces.The general structure of the function is
as follows:
The function gets() does not check if the memory is sufficient to store all
characters entered from the keyboard. Hence, the programmer must use the function
carefully because of security reasons.
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char s[100];
int main() {
gets(s);
printf("buffer = %s\n", s);
return 0;
}
Printing strings can be done in several ways. The first way is by using the
printf() function. The format of the statement for entering string by using the printf()
function is as follow:
printf("%s",str);
Another way to enter a string is by using the puts() function. The \n (new line)
character is automatically added at the end of the string when printed with puts()
function.
Example
#include <stdio.h>
int main() {
char s[]="Test string";
puts(s); /* adds \n after s */
return 0;
}
Both functions, printf() and puts(), do not print the null terminator \0.
140
10.3. String manipulation - strng.h library
Function Description
strlen(s) Returns the length of the string s.
strcmp(s1,s2) Compares strings s1 and s2.
strncmp(s1,s2,n) Compares at most the first n characters of strings s1
and s2.
strcpy(s1,s2) Copies the content of s2 into s1.
strncpy(s1,s2) Copies up to n characters from string s2 into s1.
strcat(s1,s2) Appends string s2 to the end of s1.
strncat(s1,s2) Appends up to n characters from string s2 to the end
of s1.
strchr(s,c) Finds the first occurrence of the character c in the
string s.
strrchr(s,c) Finds the last occurrence of the character c in the string
s.
strstr(s1,s2) Finds the first occurrence of the string s2 in the string
s1.
strpbrk(s1,s2) Finds the first character in the string s1 that matches
any character specified in s2.
strspn(s1,s2) Returns the length of the first segment of s1, which
consists entirely of characters in s2.
strcspn(s1,s2) Returns the length of the first segment of s1, which
consists entirely of characters NOT in s2.
strtok(s,c) Breaks string s into a series of tokens separated by the
delimiter c.
memchr(s,c,n) Finds for the first occurrence of the character c in the
first n characters of the string s.
memcmp(s1,s2,n) Compares the first n characters of strings s1 and s2.
memcpy(s1,s2,n) Copies n characters from string s2 to s1.
memset(s,c,n) Copies the character c to the first n positions of the
string s.
141
10. Strings
Function Description
isalpha(c) Checks whether c is an alphabetic character.
isdigit(c) Checks whether c is a decimal digit character.
isalnum(c) Checks whether c is an alphanumeric character.
iscntrl(c) Checks whether c is a control character.
ispunct(c) Checks whether c is a punctuation character.
isspace(c) Checks whether c is a white-space character.
isprint(c) Checks whether c is a printable character.
isxdigit(c) Checks whether c is a hexadecimal digit character.
islower(c) Checks whether c is a lowercase letter character.
isupper(c) Checks whether c is a uppercase letter character.
tolower(c) Converts uppercase letter to lowercase.
toupper(c) Converts lowercase letters to uppercase.
Exercises:
1. Write a C program that merges two strings.
Solution:
#include <stdio.h>
#include <string.h>
int main(){
strcat(result, str1);
142
10.4. Testing and mapping characters - ctype.h library
strcat(result, str2);
return 0;
}
2. Write a C program that counts the number of dots (.), commas (,) and blank
spaces in a string entered by the user.
Solution:
#include <stdio.h>
#include <ctype.h>
return count;
}
int main(){
char str[100];
return 0;
}
Solution:
#include <stdio.h>
#include <string.h>
143
10. Strings
check = 0;
break;
}
}
return check;
}
int main(){
char str[100];
if(isPalindrome(str)){
printf("The entered string is a palindrome.\n");
}
else{
printf("The entered string is NOT a palindrome.\n");
}
return 0;
}
4. Write a C program that checks if the password entered by the user is correct.
The password is correct if the length is over 8 characters, and consists of at
least one lower case letter, one number, one special character and one upper
case letter.
Solution:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
length = strlen(str);
while(str[i] != ’\0’){
if(isalnum(str[i])){
if(isdigit(str[i])){
hasNumber = 1;
}
else{
if(isupper(str[i])){
hasUpper = 1;
144
10.4. Testing and mapping characters - ctype.h library
}
else{
hasLower = 1;
}
}
}
else{
hasSpecial = 1;
}
i++;
}
int main(){
char str[100];
if(checkPassword(str)){
printf("The entered password is correct.\n");
}
else{
printf("The entered string is NOT correct.\n");
}
return 0;
}
Solution:
#include <stdio.h>
#include <string.h>
char temp;
145
10. Strings
}
}
int main(){
char str[100];
sortString(str);
return 0;
}
Solution:
#include <stdio.h>
#include <string.h>
while(str[i] != ’\0’){
if(str[i++] == ch){
return 1;
}
}
return 0;
}
str1[length] = 0;
146
10.4. Testing and mapping characters - ctype.h library
int main(){
removeCharacters(str1, str2);
return 0;
}
Solution:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
while(str[i] != ’\0’){
upper += isupper(str[i]);
lower += islower(str[i]);
int main(){
147
10. Strings
char str[100];
return 0;
}
Solution:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char newString[length];
while(str[i] != ’\0’){
if(isalnum(str[i])){
newString[j] = islower(str[i]) ? toupper(str[i]) : tolower
(str[i]);
j++;
}
else if(isspace(str[i])){
spaces++;
}
i++;
}
newString[j] = 0;
strcpy(str, newString);
return spaces;
}
int main(){
148
10.4. Testing and mapping characters - ctype.h library
char str[100];
return 0;
}
Solution:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
str[length] = 0;
int main(){
char str[100];
149
10. Strings
removeCharacters(str);
return 0;
}
10. Write a C function that accepts one array of characters as an input parameter.
The function should replace all non-alphanumeric characters with the character
*, and it will return the number of characters that were replaced from the
original. Write a main() function that will use this function.
Example:
Input: Some@# Exaˆmp&le Te#xt 123%456
Result: Some** Exa*mp*le Te*xt 123*456, and the returned value is 6.
Solution:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
while(str[i] != ’\0’){
if(!isalnum(str[i])){
str[i] = ’*’;
count++;
}
i++;
}
return count;
int main(){
char str[100];
return 0;
}
150
10.4. Testing and mapping characters - ctype.h library
11. Write a C function that accepts one array of characters as an input parameter.
The function should format and print the phone number “0038970123456” in
this format:
“+389 (0) 70 123-456”
Write main() function where the user enters the phone number, and the
function should print the formatted telephone number. If the entered number
is not valid, the program will warn the user with this message “Invalid phone
number”.
Solution:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
// 0038970123456
// 0123456789
if(length != 13){
printf("Invalid phone number.\n");
}
else{
char formattedPhone[20] = "+";
char tempStr[100] = "";
}
printf("The formatted phone number is: %s\n", formattedPhone);
}
}
int main(){
151
10. Strings
char str[100];
printFormattedPhoneNumber(str);
return 0;
}
12. Write a C program that performs coding of a text message. The coding is
performed as follows: it starts from the left and takes one letter from each
side of the string. The program should stop when the middle letter is reached.
Example:
Input: Test string
Result: Tgensitr ts
Solution:
#include <stdio.h>
#include <string.h>
// test string
// tg
int i, j = 0;
int length = strlen(str);
char newString[length];
if(length % 2){
newString[j++] = str[length/2];
}
newString[j] = 0;
printf("%s\n", newString);
strcpy(str, newString);
int main(){
char str[100];
152
10.4. Testing and mapping characters - ctype.h library
gets(str);
codeString(str);
return 0;
}
153
CHAPTER 11
Files
A file represents a sequence of bytes that are used to store a large volume of data.
The operations described in the previous chapters produce results stored only in the
computer’s temporary memory. Usually, the program users need these results to be
fetched again, which means they need to be written on permanent storage. Using
files is a common way for permanent storage of data.
• Creation of a file.
• Opening a file.
• Writing to file.
• Closing a file.
The first step in the process of working with files in C is to declare a pointer
of type FILE. This pointer will help in communication between the file and the
program. The format of the statement for declaring a file pointer is as follows:
FILE *nameOfFilePointer;
where:
155
11. Files
Table 11.1 describes the commonly used functions for file management in C.
These functions are part of the stdio.h library.
Function Description
fopen() Creates a new file or opens an existing file.
fscanf() Reads a set of data from a file.
fprintf() Writes a set of data to a file.
getc() Reads a character from a file.
putc() Writes a character to a file.
getw() Reads an integer from a file.
putw() Writes an integer to a file.
fclose() Closes a file.
fseek() Sets the file pointer to a specified location.
rewind() Sets the file pointer at the beginning of a file.
ftell() Returns the position of the file pointer.
The function fopen() is used to open a file. If the file can not be found in the
system, the function will create a new file and then open it. The syntax of fopen()
function is as follows:
fopen("FileName", "Mode");
where:
• FileName is the name of the file.
• Mode is the access mode.
The second argument of the fopen() function specifies the access mode. A file,
in the C programming language, can be opened for reading or writing. Figure 11.2
describes the different types of file access modes in C.
Mode Description
r Open a file for reading.
w Open a file for writing. Content is overwritten.
a Open a file for appending. The new content is added to the
end of the file.
r+ Open a file for reading and writing.
w+ Open a file for reading and writing.
a+ Open a file for reading and appending.
Based on the selected access mode during file opening, we can perform certain
operations on the file, i.e., reading or writing, using the functions for that purpose
156
11.1. Working with files in C
described in Table 11.1. Both r+ and w+ open a file for reading and writing. The
difference between these two modes is that in case the file doesn’t exist, w+ will
create a new file and open it, while r+ will not create a new file. In the same manner,
if the file exists, w+ will open the file and delete the existing content, while r+ will
not delete the existing content. Similarly to r+, r also doesn’t create a new file if the
file doesn’t exist.
After finishing with all file operations, the file needs to be close. It will release
any memory that the compiler reserve for the file and prevent accidental damage.
The fclose() function closes the open file. The function returns 0 if the file is closed
successfully or EOF if there is an error during the closing. The EOF (End Of File) is
a constant defined in the stdio.h library. The syntax of fclose() function is as follows:
fclose("FileName");
where:
Exercises:
1. Write a simple C Program that opens a file, write in it, and close the file.
Solution:
#include <stdio.h>
int main(){
char userInput[1000];
FILE *file;
if (file == NULL) {
printf("Error!");
return -1;
}
return 0;
2. Write a C program that compares two files. The program should return "Files
are same" if the files are identical or the position of the first difference if the
157
11. Files
Solution:
#include <stdio.h>
if (ch1 != ch2){
return 0;
}
ch1 = getc(file1);
ch2 = getc(file2);
}
return 1;
}
int main(){
if (compareFiles(file1, file2)){
printf("The files are identical.\n");
}
else{
printf("The files are NOT identical.\n");
}
fclose(file1);
fclose(file2);
return 0;
158
11.1. Working with files in C
3. Write a C program that counts the number of words in a given text file. A
word consists of alphanumeric characters and is separated by the other word
with at least one space.
Solution:
#include <stdio.h>
#include <ctype.h>
int main(){
char c;
int nrWords = 0, inWord = 0;
FILE *file;
if(inWord)
nrWords++;
Solution:
#include <stdio.h>
#include <ctype.h>
int main(){
char c;
int totalNumbers = 0, totalLetters = 0;
FILE *file;
159
11. Files
return 0;
5. Write a C program that will print all words composed of at least three letters
from a given file. The user enters the name of the file.
Solution:
#include <stdio.h>
#include <ctype.h>
int main(){
char c;
int inWord = 0;
int count = 0, charsCount = 0;
FILE *file;
charsCount++;
}
else if(inWord){
inWord = 0;
160
11.1. Working with files in C
return 0;
6. Write a C program that will count the number of paragraphs with more than
five words. A paragraph is a group of words ending with a new line.
Solution:
#include <stdio.h>
#include <ctype.h>
int main(){
FILE *file;
i = 0;
ch = str[0];
nrWords = 0;
inWord = 0;
i++;
ch = str[i];
}
if(inWord)
nrWords++;
if(nrWords > 5)
161
11. Files
count++;
}
return 0;
162
CHAPTER 12
Structures
12.1 Structures in C
In the C programming language, a structure is a group of data elements grouped
under one name. These data elements, known as members, can have different types
and lengths. Structures can be declared using the struct keyword. The statement for
declaring a structure has the following syntax:
struct [structureName] {
memberType1 memberName1;
memberType2 memberName2;
memberType3 memberName3;
...
} [structureVariables];
where:
• structureName is the name of the structure. Structure name is optional but
recommended to be used.
• memberType is the datatype of the member element.
• memberName is the name of the member element.
• structureVariables declares variables from structure data type. Declaration
is also optional in this part.
Examples of structure declaration:
struct animal {
char name[50];
int age;
float weight;
163
12. Structures
} cat, dog;
The above structure type is called animal and defines three members: name,
age and weight, each of a different datatype. In the end, this declaration directly
creates two variables of this newly defined type: cat and dog. Another way to create
variables from this newly defined type is as follows:
struct animal {
char name[50];
int age;
float weight;
};
........
Note that once the animal structure is declared, it is used just like any other
datatype. It is important to make difference between the structure type name (animal)
and a variable of this type (dog and cat). Many variables (such as dog and cat) can
be declared from a single structure type (animal).
structureVariable.memberName
where:
For example, to access the member elements in the animal structure defined in
the previous chapter, the syntax will be as follows:
cat.name dog.name
cat.age dog.age
cat.weight dog.weight
Similar to a variable of any other datatype, the structure variable can also be
initialized within the declaration. For example, the initialization can be done as
follows:
164
12.3. Array of structures and nested structures
struct animal {
char name[50];
int age;
float weight;
};
struct animalColor {
char head[50];
char body[50];
char tail[50];
};
struct animal {
char name[50];
int age;
float weight;
struct animalColor color;
} cat, dog;
struct animal {
char name[50];
int age;
float weight;
165
12. Structures
struct animalColor {
char head[20];
char body[20];
char tail[20];
} color;
} cat, dog;
The following example shows how to access the elements of nested structure
color and how to initialize it.
cat.color.body = "Black";
where:
• structureName is the name of the structure.
• pointerName is the name of the pointer.
• * (asterisk) is dereferencing operator.
The pointer to a structure stores the address of a structure variable. The address
of the structure variable is assigned by using the ’&’ operator. The format of the
statement for assigning an address is as follows:
pointerName = &structureVariable;
where:
• structureVariable is the name of the structure variable.
The arrow (->) operator is used to access the structure member elements using a
pointer. The format of the statement for accessing the structure member elements
using a pointer is as follows:
where:
• memberName is the name of the member element.
The example below demonstrates a simple program for using a pointer to
structure.
166
12.4. Pointers to structures and structures to function
#include <stdio.h>
struct animal {
char name[50];
int age;
float weight;
};
int main() {
struct animal cat = { "Tom" , 7, 2.5 };
struct animal *catPtr;
catPtr = &cat;
printf( "The name of the cat is : %s\n", catPtr -> name);
return 0;
}
The return value of the function can be a structure. In the example below, the
readData function returns a structure.
return dog;
}
167
12. Structures
Exercises:
1. Write a C program that stores information about students using structure. The
structure keeps information about the student name (array of characters), ID
number (integer) and marks (float).
Solution:
#include <stdio.h>
struct student{
char firstName[50];
int roll;
float marks;
};
int main(){
int i;
student s[10];
printf("Displaying Information:\n\n");
2. Write a C function that calculates the sum of two complex numbers. The
function should accept two structures and return a structure. Write a main()
function to test the previously defined function.
Solution:
168
12.4. Pointers to structures and structures to function
#include <stdio.h>
int main() {
complex n1, n2, result;
return 0;
}
3. Write a C program that keeps information and performs analysis for a class of
15 students. The structure consists of information about Student ID, Name,
mid-term scores (2 mid-term per semester), total score, and final grade.
Create an interactive menu for:
1. Add a new student
2. Delete student
3. Update student info
4. Print all students
5. Calculate the final grade from student’s points.
6. Show student who gets the max total score
7. Show student who gets the min total score
8. Find student by ID
9. Sort students by total scores
Note: You need to create an array of structures.
Solution:
#include <stdio.h>
169
12. Structures
struct student{
int id, midTerm1, midTerm2;
int totalScore, finalScore;
char name[100];
};
temp.id = 0;
return temp;
}
int found = 0;
int i, j;
if(found){
printf("Student with ID=%d is updated\n", id);
}
else{
printf("Student with ID=%d cannot be found\n", id);
}
170
12.4. Pointers to structures and structures to function
int i, j;
int found = 0;
if(found){
printf("Student with ID=%d is removed\n", id);
}
else{
printf("Student with ID=%d cannot be found\n", id);
}
171
12. Structures
int i = 0;
struct student max = s[i];
return max;
}
return min;
}
int main(){
int i = 0, n = 0, selection = 0;
char name[100];
while(selection != 10){
printf("\nSelect action:\n");
printf("\t1: Add a new student\n");
printf("\t2: Delete a student\n");
printf("\t3: Update student info\n");
printf("\t4: Print all students\n");
printf("\t5: Calculate the final grade from student points\n")
172
12.4. Pointers to structures and structures to function
;
printf("\t6: Show student who gets the max total score\n");
printf("\t7: Show student who gets the min total score\n");
printf("\t8: Find student by ID\n");
printf("\t9: Sort students by total scores\n");
printf("\t10: Exit menu.\n");
scanf("%d", &selection);
switch (selection){
case 1:
printf("Enter the info about the student:\n\n");
printf("Enter the name: ");
gets(s[n].name);
n++;
break;
case 2:
break;
case 3:
updateStudent(s, n, id);
break;
case 4:
for(i = 0; i < n; i++){
print(s[i]);
}
break;
case 5:
printf("Enter the studnet’s ID: ");
scanf("%d", &id);
if(temp.id){
int grade = calculateFinalGrade(temp);
173
12. Structures
if(grade){
temp.finalScore = grade;
printf("The final grade is: %d\n", grade);
}
}
break;
case 6:
print(findMax(s, n));
break;
case 7:
print(findMin(s, n));
break;
case 8:
if(temp.id){
print(temp);
}
break;
case 9:
sortStudents(s, n);
break;
case 10:
break;
}
}
return 0;
}
174
Appendices
APPENDIX A
This appendix provides implementation and a full description of the commonly used
C library functions, with some simple examples.
#include <stdio.h>
#include <string.h>
int main() {
char str[50] = "Hello World!";
int len;
len = strlen(str);
printf("Length of %s is %d\n", str, len);
return 0;
}
177
A. Commonly used C library functions
#include <stdio.h>
#include <string.h>
int main() {
char s1[10] = "abba", s2[10] = "aba";
if(strcmp(s1,s2) < 0) {
printf("s1 is less than s2");
} else if(strcmp(s1,s2) > 0) {
printf("s1 is greater than s2");
} else {
printf("s1 is equal to s2");
}
return 0;
}
s1 is greater than s2
#include <stdio.h>
#include <string.h>
int main() {
char s1[10] = "abba", s2[10] = "aba";
return 0;
}
178
A.1. Implementation of the functions from string.h library
s1 is equal to s2
The function copies the string pointed by s2 (including the null terminator) to
the s1 and does not check if there is enough space to store the content of s2. The
function returns the copied string.
#include <stdio.h>
#include <string.h>
int main() {
char s1[10] = "Hello", s2[10];
strcpy(s2, s1);
printf("%s", s2);
return 0;
}
Hello
#include <stdio.h>
#include <string.h>
int main() {
char s1[10] = "Hello", s2[10];
return 0;
}
179
A. Commonly used C library functions
He
int main() {
char s1[50] = "Hello ", s2[50] = "world!";
strcat(s1, s2);
printf("%s", s1);
return 0;
}
int main() {
char s1[50] = "Hello ", s2[50] = "world!";
printf("%s", s1);
return 0;
}
180
A.1. Implementation of the functions from string.h library
The function searches for the first occurrence of the character c in the string s.
The function returns a pointer to the first occurrence of the character c in the string s,
or (null) if the character is not found.
#include <stdio.h>
#include <string.h>
int main() {
char s[20] = "Hello world!";
char c = ’l’;
return 0;
}
llo world!
The function searches for the last occurrence of the character c in the string s.
The function returns a pointer to the last occurrence of the character c in the string s,
or (null) if the character is not found.
#include <stdio.h>
#include <string.h>
int main() {
char s[20] = "Hello world!";
char c = ’l’;
return 0;
}
ld!
181
A. Commonly used C library functions
The function searches for the first occurrence of the string s2 in the string s1.
The function returns a pointer to the first occurrence of the string s2 in the string s1,
or (null) if the character is not found.
#include <stdio.h>
#include <string.h>
int main() {
char s1[20] = "Hello world!";
char s2[20] = "wor";
return 0;
}
world!
The function finds the first character in the string s1 that matches any character
from s2. The function returns a pointer to the character in s1 that matches one of the
characters from s2, or (null) if the character is not found.
#include <stdio.h>
#include <string.h>
int main() {
char s1[20] = "Hello world!";
char s2[20] = "wor";
return 0;
}
o world!
182
A.1. Implementation of the functions from string.h library
The function returns the length of the first segment of s1, which consists entirely
of characters in s2.
#include <stdio.h>
#include <string.h>
int main() {
char s1[20] = "Hello world!";
char s2[20] = "Hel";
int len;
return 0;
}
The function returns the length of the first segment of s1, which consists entirely
of characters NOT in s2.
#include <stdio.h>
#include <string.h>
int main() {
char s1[20] = "Hello world!";
char s2[20] = "wow";
int len;
return 0;
}
183
A. Commonly used C library functions
• int isalpha(int c)
The function checks whether c is an alphabetic character. It returns non-zero
value (true) if c is an alphabetic character, else it returns 0 (false).
#include <stdio.h>
#include <ctype.h>
int main() {
int c = ’a’;
if(isalpha(c) ) {
printf("%c is an alphabetic character\n", c );
} else {
printf("%c is not an alphabetic character\n", c);
}
return 0;
}
a is an alphabetic character
• int isdigit(int c)
The function checks whether c is a decimal digit (0 1 2 3 4 5 6 7 8 9). It returns
non-zero value (true) if c is a decimal digit, else it returns 0 (false).
#include <stdio.h>
#include <ctype.h>
int main() {
int c = ’3’;
if(isdigit(c) ) {
printf("%c is a decimal digit\n", c );
} else {
printf("%c is not a decimal digit\n", c);
}
return 0;
}
3 is a decimal digit
184
A.2. Implementation of the functions from ctype.h library
• int isalnum(int c)
#include <stdio.h>
#include <ctype.h>
int main() {
int c = ’3’;
if(isdigit(c) ) {
printf("%c is an alphanumeric character\n", c );
} else {
printf("%c is not an alphanumeric character\n", c);
}
return 0;
}
3 is an alphanumeric character
• int ispunct(int c)
#include <stdio.h>
#include <ctype.h>
int main() {
int c = ’?’;
if(ispunct(c) ) {
printf("%c is a punctuation character\n", c );
} else {
printf("%c is not a punctuation character\n", c);
}
return 0;
}
? is a punctuation character
185
A. Commonly used C library functions
• int isspace(char c)
The function checks whether c is a white-space character. In C, standard
white-space characters are: space (’ ’); tab (’\t’); newline (’\n’); vertical tab (’\v’);
feed (’\f’) and return (’\r’). The function returns non-zero value (true) if c is a
white-space character, else it returns 0 (false).
#include <stdio.h>
#include <ctype.h>
int main() {
char c = ’A’;
if(isspace(c) ) {
printf("%c is a white-space character\n", c );
} else {
printf("%c is not a white-space character\n", c);
}
return 0;
}
• int isprint(int c)
The function checks whether c is a printable character. Printable characters are
all characters except the control characters. The function returns non-zero value
(true) if c is a printable character, else it returns 0 (false).
#include <stdio.h>
#include <ctype.h>
int main() {
int c = ’A’;
if(isprint(c) ) {
printf("%c is a printable character\n", c );
} else {
printf("%c is not a printable character\n", c);
}
return 0;
}
A is a printable character
186
A.2. Implementation of the functions from ctype.h library
• int islower(int c)
The function checks whether c is a lowercase letter. The function returns
non-zero value (true) if c is a lowercase letter, else it returns 0 (false).
#include <stdio.h>
#include <ctype.h>
int main() {
int c = ’z’;
if(islower(c) ) {
printf("%c is a lowercase letter\n", c );
} else {
printf("%c is not a lowercase letter\n", c);
}
return 0;
}
z is a lowercase letter
• int isupper(int c)
The function checks whether c is an uppercase letter. The function returns
non-zero value (true) if c is an uppercase letter, else it returns 0 (false).
#include <stdio.h>
#include <ctype.h>
int main() {
int c = ’Q’;
if(isupper(c) ) {
printf("%c is an uppercase letter\n", c );
} else {
printf("%c is not an uppercase letter\n", c);
}
return 0;
}
Q is an uppercase letter
• int tolower(int c)
187
A. Commonly used C library functions
#include <stdio.h>
#include <ctype.h>
int main() {
int c = ’Q’;
if(isupper(c) ) {
printf("The lowercase equivalent of %c is %c\n", c, tolower(c));
} else {
printf("%c is not an uppercase letter\n", c);
}
return 0;
}
• int toupper(int c)
#include <stdio.h>
#include <ctype.h>
int main() {
int c = ’a’;
if(islower(c) ) {
printf("The uppercase equivalent of %c is %c\n", c, toupper(c));
} else {
printf("%c is not a lowercase letter\n", c);
}
return 0;
}
188
A.3. Functions for numeric conversions and random number generation -
stdlib.h library
A.3 Functions for numeric conversions and random
number generation - stdlib.h library
The stdlib.h C standard library contains prototypes of various functions for numeric
conversions and random number generation. Table A.1 describes the commonly
used functions from the stdlib.h library.
Function Description
atoi(s) Converts the string s to an integer number.
atof(s) Converts the string s to a floating-point number (double).
atol(s) Converts the string s to a long integer number.
strtod(s, &p) Converts the string s to a floating-point number and returns
a pointer &p to the first character after the number.
strtol(s, &p, base) Converts the string s to a long integer number according to
the given base and returns a pointer &p to the first character
after the number.
strtoul(s, &p, base) Converts the string s to an unsigned long integer number
according to the given base and returns a pointer &p to the
first character after the number.
rand() Returns an integer value between 0 and RAND_MAX.
srand(a) Sets the starting point for the random number generator
used by the function rand().
The function converts the string s to an integer number. It returns the converted
number as an int type. If the conversion could not be performed, the function returns
zero.
The function converts the string s to a long integer number. It returns the
converted number as an long int type. If the conversion could not be performed, the
function returns zero.
189
A. Commonly used C library functions
#include <stdio.h>
#include <stdlib.h>
int main () {
char s[10] = "229463";
char s1[10] = "hello";
return(0);
}
The function converts the string s to a floating-point number and returns a pointer
**p to the first character after the number if **p is not NULL. If the conversion
could not be performed, the function returns zero.
The function converts the string s to a long integer number according to the
given base and returns a pointer **p to the first character after the number. The base
must be between 2 and 36 inclusive, or 0. If the conversion could not be performed,
the function returns zero.
• unsigned long int strtol(const char *s, char **p, int base)
The function converts the string s to an unsigned long integer number according
to the given base and returns a pointer **p to the first character after the number.
The base must be between 2 and 36 inclusive, or 0. If the conversion could not be
performed, the function returns zero.
Example with strtod(s, &p); strtol(s, &p, base) and strtoul(s, &p, base):
#include <stdio.h>
#include <stdlib.h>
int main () {
char s[30] = "223.131234 Test double";
190
A.3. Functions for numeric conversions and random number generation -
stdlib.h library
char s1[40] = "1176 Test long integer";
char s2[40] = "1176 Test unsigned long integer";
char *p;
return(0);
}
• int rand(void)
The function returns an integer value between 0 and RAND_MAX. RAND_MAX
is a constant whose default value may vary, but it is always at least 32767.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main () {
int i;
return(0);
}
191
A. Commonly used C library functions
90
79
13
98
4
41
3
70
68
55
Function Description
sqrt(a) Returns the square root of a.
pow(a, n) Returns the result of a to the power n.
fabs(a) Returns the absolute value of a.
ceil(a) Returns the smallest integer value greater than or equal to a.
floor(a) Returns the largest integer value less than or equal to a.
fmod(a, b) Returns the remainder of the dividing of a by b.
exp(n) Returns the result of exponential e to the power n.
log(a) Returns the natural logarithm of a (base-e).
log10(a) Returns the common logarithm of a (base-10).
sin(a) Returns the sine of angle a. The angle a is in radians.
cos(a) Returns the cosine of angle a. The angle a is in radians.
tan(a) Returns the tangent of angle a. The angle a is in radians.
sinh(a) Returns the hyperbolic sine of a.
cosh(a) Returns the hyperbolic cosine of a.
tanh(a) Returns the hyperbolic tangent of a.
asin(a) Returns the arc sine of a. The result is in radians.
acos(a) Returns the arc cosine of a. The result is in radians.
atan(a) Returns the arc tangent of a. The result is in radians.
192
A.4. Commonly used functions from math.h library
#include <stdio.h>
#include <math.h>
int main() {
double a = 2.2, n = 2.0, b = 0.9;
return 0;
}
193
A. Commonly used C library functions
The time.h library contains prototypes of various functions for manipulating date and
time. Table A.3 describes the commonly used datatypes (line 1 to 3) and functions
(line 4 to 11) from the time.h library.
Datatype(1-3) Description
Function(4-11)
time_t Datatype capable of storing the calendar time.
clock_t Datatype capable of storing the processor time.
struct tm Structure used to store the time and date.
clock() Returns the processor clock time used since the start of the
program in clock_t format.
time(*t) Calculates the current calendar time and encodes it in time_t
format.
mktime(*t) Returns a value corresponding to the calendar time passed
as structure struct tm.
*asctime(*t) Returns a pointer to a string containing the date and time
information in a human-readable format.
*ctime(*t) Returns a string representing the local date and time
information in a human-readable format.
difftime(t1, t2) Returns the difference of two times in seconds.
*gmtime(*t) Returns a pointer to a tm struct structure with the time
information, expressed in GMT timezone.
*localtime(*t) Returns a pointer to a tm struct structure with the time
information, expressed in local timezone.
struct tm {
int tm_sec; /* seconds */
int tm_min; /* minutes */
int tm_hour; /* hours */
int tm_mday; /* day of the month */
int tm_mon; /* month */
int tm_year; /* year */
int tm_wday; /* day of the week */
int tm_yday; /* day in the year, 0 to 365 */
int tm_isdst; /* daylight saving time */
};
194
A.5. Functions for manipulating date and time - time.h library
• clock_t clock(void)
The function returns the number of clock ticks elapsed since the start of the
program.
The function returns the time since the Epoch (January 1, 1970, 00:00:00 UTC),
measured in seconds.
The function converts the structure pointed to by t into a time_t value according
to the local time zone.
The function returns a pointer to a string containing the date and time information
in a human-readable format. The information is in the following format: Www
Mmm dd hh:mm:ss yyyy, where Www is the weekday name, Mmm is the month
name, dd is the day of the month, hh:mm:ss is the time (hh hour, mm minutes, ss
seconds) and yyyy is the year.
The function returns a string representing the local date and time information in
a human-readable format. The information is in the following format: Www Mmm
dd hh:mm:ss yyyy, where Www is the weekday name, Mmm is the month name, dd
is the day of the month, hh:mm:ss is the time (hh hour, mm minutes, ss seconds) and
yyyy is the year.
The function returns the difference of two times, t1 and t2, in seconds. The two
times are specified in calendar time.
The function returns a pointer to a tm struct structure with the time information
field with the values representing the corresponding time, expressed in Coordinated
Universal Time (UTC) or Greenwich Mean Time (GMT) timezone. The definition
of the tm struct structure is given in the listing above.
195
A. Commonly used C library functions
The function returns a pointer to a tm struct structure with the time information
field with the values representing the corresponding time, expressed in local timezone.
The definition of the tm struct structure is given in the listing above.
Example with functions from time.h library:
#include <stdio.h>
#include <time.h>
int main () {
time_t t, start_t, end_t;
clock_t start_c, end_c;
struct tm *local_time, *gm_time;
start_c = clock();
time(&start_t);
time(&t);
local_time = localtime(&t);
printf("Current local time: %2d:%02d\n", local_time->tm_hour,
local_time->tm_min);
time(&t);
gm_time = gmtime( &t );
printf("Current GM day and time: %s\n", asctime(gm_time));
time(&end_t);
printf("Program execution took: %f seconds\n", difftime(end_t,
start_t));
end_t = clock();
printf("Total CPU time: %f seconds\n", ((double)(end_c - start_c) /
CLOCKS_PER_SEC));
return(0);
}
196
APPENDIX B
C programming language allows user to pass some values from the command line
to the programs when they are executed. These values are called command line
arguments. The command line arguments in the main() function are a simple way of
passing information in the program (names of files, options, etc.). They are specified
in the main() function as follows:
#include <stdio.h>
printf("Hello, world!\n");
return 0;
}
where:
• argc is an integer number that refers to the number of arguments passed to the
program.
• **argv is a pointer array that points to each argument passed to the program.
The first element of the array is the name of the program. The command line
arguments are passed separated by whitespace. If the argument has whitespace,
then such argument is passed by putting it inside double quotes "" or single
quotes ”.
Example:
#include <stdio.h>
int i;
for(i = 0; i < argc; i++) {
printf("%s\n", argv[i]);
}
197
B. Using command-line arguments in C
return 0;
}
In the above example, the loop is iterated for every argument in the command
line. When the above example is compiled and executed from the command line, it
produces the following result:
During compiling of the example with the parameters given above, argc=5 and
argv[0]=“Hello”, argv[1]=“world!”, argv[2]=“This”, argv[3]=“is”, argv[4]=“a
test.”.
198
APPENDIX C
C keywords
A short description of the C keywords is given below. The syntax and application
of the keywords are discussed in the respective chapters of this book.
199
References
201
Short excerpts from the reviewers
203
Short excerpts from the reviewers
204
Copyright
©All rights reserved, including the right to reproduce this book or portions thereof
in any form whatsoever. For information, address the authors.
205
Copyright
!!
004.438C:004.42(075.8)
ISBN 978-608-66225-1-0
COBISS.MK-ID 56827653
206