0% found this document useful (0 votes)
4 views42 pages

C Programming Language

These lecture notes on C programming provide a comprehensive overview of the language, covering topics such as basic syntax, control structures, modular programming, arrays, strings, structures, pointers, files, and system calls. The notes serve as a supplementary resource for students, detailing essential programming concepts, examples, and exercises to reinforce learning. The document emphasizes the importance of understanding both the theoretical and practical aspects of C programming.

Uploaded by

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

C Programming Language

These lecture notes on C programming provide a comprehensive overview of the language, covering topics such as basic syntax, control structures, modular programming, arrays, strings, structures, pointers, files, and system calls. The notes serve as a supplementary resource for students, detailing essential programming concepts, examples, and exercises to reinforce learning. The document emphasizes the importance of understanding both the theoretical and practical aspects of C programming.

Uploaded by

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

C PROGRAMMING LANGUAGE

LECTURE NOTES
Halil Özmen

Purpose: These lecture notes are intended for the instructor. It is not a replacement for the notes
taken by the students in the classroom. The students can use these notes as a
complement to their own notes and to the text-book.

Table of Contents
1. C Programming Language Basics.............................................................................................. 2
2. Control Structures ...................................................................................................................... 4
2.1. Selection Structures .............................................................................................................. 5
2.2. Loop Statements................................................................................................................... 8
2.2.1. for loops ..................................................................................................................... 8
2.2.2. Conditional loops: while loops, do ... while loops ........................................................ 9
3. Modular Programming and Functions ...................................................................................... 12
3.1. Basics of Modular Programming ......................................................................................... 12
3.2. Function Definitions and Calling Functions ......................................................................... 12
3.3. Functions with no parameters ............................................................................................. 13
3.4. Functions with parameters .................................................................................................. 13
3.5. Functions that does not return value ................................................................................... 13
3.6. Functions that return value.................................................................................................. 14
3.7. Scope of variables .............................................................................................................. 15
4. Arrays ...................................................................................................................................... 16
4.1. One dimensional arrays ...................................................................................................... 16
4.2. Utilization of array elements ................................................................................................ 16
4.3. Input/Output of Arrays ......................................................................................................... 17
4.4. Array manipulation .............................................................................................................. 17
4.5. Arrays as function parameters ............................................................................................ 18
4.6. Two or more dimensional arrays ......................................................................................... 19
5. Strings ..................................................................................................................................... 21
5.1. String Basics ....................................................................................................................... 21
5.2. String Functions .................................................................................................................. 22
5.3. Character Analysis and Conversion: ................................................................................... 24
6. Structures ................................................................................................................................ 28
7. Pointers ................................................................................................................................... 33
7.1. Pointer Basics ..................................................................................................................... 33
7.2. Dynamic Memory Allocation................................................................................................ 34
7.3. Linked Lists......................................................................................................................... 35
8. Files ......................................................................................................................................... 37
9. Bit Manipulation ....................................................................................................................... 40
10. System Calls ............................................................................................................................ 41
10.1. Directory and File Manipulation System Calls.................................................................. 41
10.2. Date and Time System Calls ........................................................................................... 42
1. C Programming Language Basics

Building Blocks of a C Program:


• comments:
/* Comments */
// C++ comments, can also be used in C programs
• preprocessor directives,
#include <stdlib.h>
#include <stdio.h>
#define KMS_PER_MILE 1.609
• main function:
int main(void)
{
declarations...
executable statements...
}
• statements:
• declarations,
• assignment statements,
• input/output statements,
• control statements,
• function calls.
Except control statements, all statements ends with semi-colon ";".

Data types: int, char, float, double

Data representation:
• constants
• variables

Constants:
• Integer constants: 7 248 -74 0 4 -1444
• Character constants: 'A' 'k' '.' '+' '4' '?' '\t' '\n'
• Float and double constants: 3.14159 0.00508 12345.0 15.0e4 15.0e-4 3.24e-04
Constant Definitions: #define PI 3.14159265358979323846264338
#define MAXSIZE 100

Variables:
Variables in programming languages are entities that hold values. The value that variables hold
may be changed.
Variable names must start with a-z, A-Z, and underscore "_", followed by a-z A-Z 0-9 _.
Valid variable names: a k total a6y x45_t4 ali ankara city06 _err
Invalid variables: 2abc ali-top abba.go pi3.14

Declaration:
int a;
char c1;
double x;

C Programming Language 2 Halil Özmen


int count, j, j2, b;
char first_letter, last_digit;

Assignment Statement:
a = 12;
ali = count;
a_0 = j2 + 16;
x = (j2 * 4) + (count / (j - 1) );

Arithmetic Operators:
+ - * / %

Precedence of arithmetic operators: (p. 150)


1. (...)
2. * / %
3. + -

Arithmetic Expressions:
j2 * 4 + count / (j - 1)
a + b * c / d - e / f * g (what is the sequence of operations)
a + b * c / (d - e / f) * g (what is the sequence of operations)

Input / Output:
To use input and output functions, stdio.h must be included. The following line has to be put in
source file:
#include <stdio.h>

Input:
scanf("%d", &n); // Scanf reads things separated by whitespaces
scanf("%c", &c); // Input character
scanf("%f", &x); // Input float (or double)
scanf("%lf", &dist); // Input double
scanf("%d %c", &a, &b); // the 2 values can be on different
lines!

Output
printf("Enter a number: "); // Output just a string
printf("Total is %d\n", total); // Output string and an integer

Formatted Input/Output,
printf("Today is %02d/%02d/%4d\n", day, month, year);
printf("Height: %5.2f m., Weight: %10.4f gr.\n", height, weight);

Placeholders
Data type Placeholder Input example Output example
int %d scanf("%d", &val); printf("%d", val);
char %c scanf("%c", &letter1); printf("%c", letter1);
float %f scanf("%f", &kms); printf("%f", kms);
double %lf %f scanf("%lf", &height); printf("%f", height);
%d %4d %04d %-4d
%f %.4f %10.6f %lf %.4lf %10.2lf
C Programming Language 3 Halil Özmen
Built-in Functions
printf, scanf
other input and output functions
mathematical functions (sqrt, abs, sin, etc.), string functions, date and time functions, etc...

Exercises:
• Input an integer, output its square, cube and square-root.
• Input a distance (int km) and a speed (int), output duration in terms of hour:minute (hh:mm).

2. Control Structures

Control structures:
Control structures control the flow of execution in a program or function.

Compound statement:
Compound statement is a group of statements bracketed by { and } that are executed
sequentially.
{
statement1;
statement2;
. . .
statementn;
}

Conditions:
Condition is an expression that is either true (usually represented by 1) or false (represented by
0).

A condition or logical expression is an expression that can only take the values true or false.
A simple form of logical expression is the relational expression.

Relational operators:
Relational Operator Meaning Example
== equal to a == 7
!= not equal to b != total
> greater than height > 200.0
>= greater than or equal to points >= 20
< less than uptime < 99.5
<= less than or equal to quantity <= 100

Relational expressions (examples):


(x > y) (a == 10) (a >= (b+c) ) (gender == 'F')
(a >= 100) (xyz <= 4*www) (qq*2.78 <= r*PI-8.4)

Logical operators:
Logical Operator Meaning Example
&& and a > 4 && x == 20.7
|| or a > 4 || x == 20.7
! not !(a > 4 && x == 20.7)

C Programming Language 4 Halil Özmen


Truth table for logical operators:
AND OR NOT
a b a && b a b a || b a !a
F F F F F F F T
F T F F T T T F
T F F T F T
T T T T T T

Precedence of Operators (from high to low):


1) a[...] f(...) . ->
2) postfix ++ postfix --
3) prefix ++ prefix -- sizeof ~ !
unary + unary - unary & unary *
4) casts
5) * / %
6) binary + binary -
7) << >>
8) < > <= >=
9) == !=
10) binary &
11) binary ^
12) binary |
13) &&
14) ||
15) ? :
16) = += -= *= /= %= <<= >>= &= ^= |=

Logical expressions (examples):


(a > 14 && b == 0) (aqil == 'J' || aqil == 'j') (dist >= 200 && dist < 300)

2.1. Selection Structures

Simple if statement: if (condition)


{
Syntax: statement1;
if (condition) statement2;
{ . . .
statement(s)...; statementn;
} }

if (condition) if (condition)
{ {
statement(s)...; statement1;
} statement2;
else . . .
{ statementn;
statement(s)...; }
} else
{
Examples: statement1;
if (height > 200) statement2;
{ . . .
printf("Tall\n"); statementm;
n_tall++; }
}

C Programming Language 5 Halil Özmen


if ()
{
statement(s)...;
}
else
{
statement(s)...;
}

Nested if statements:
Sample cases:
Concept: if statements within if statements
Example-1 for Case:
Male, <20 years of age
Examples:
if (condition1) Male, >=20 years of age
{ Female, <20 years of age
statement(s)...; // optional Female, >=20 years of age
if (condition2)
{ Example-2 for Case:
statement(s)...; Temperature < -10
} -10 <= Temperature < 0
else 0 <= Temperature < 10
{ 10 <= Temperature < 20
statement(s)...; Temperature >= 20
}
statement(s)...; // optional
}
else
{
statement(s)...; // optional
if (condition3) // may be: if (condition2)
{
statement(s)...;
}
else
{
statement(s)...;
}
statement(s)...; // optional
}

Example:
if (gender == 'M')
{
if (age > 20)
{
...
}
else
{
...
}
}
else
{
if (age > 20)
{
...
}
C Programming Language 6 Halil Özmen
else
{
...
}
}

Most used form of nested if statements: Example:


if (condition1) if (distance < 100)
{ {
statement(s)...; statement(s)...;
} }
else if (condition2) else if (distance < 500)
{ {
statement(s)...; statement(s)...;
} }
else if (condition3) else if (distance < 2000)
{ {
statement(s)...; statement(s)...;
} }
.... (more else if blocks if necessary) else
else {
{ statement(s)...;
statement(s)...; }
}

Dangling else:
if a then if b then s1 else s2
which can be understood in two ways.
Either as or as
if a then if a then
{ {
if b then if b then
{ {
s1 s1
} }
else }
{ else
s2 {
} s2
} }
"Dangling else" may occur when {...} is not used.

switch statement

switch ( variable )
{
case const:
statements...;
default:
statements...;
}

C Programming Language 7 Halil Özmen


Example:
switch(betty)
{
case 1:
printf("betty=1\n");
case 2:
printf("betty=2\n");
break;
case 3:
printf("betty=3\n");
break;
default:
printf("Not sure.\n");
}

Exercises:
• Input two (or three) numbers, output them in ascending order.
• Input two integer numbers, output if 1st number is a multiple of the second.

2.2. Loop Statements

2.2.1. for loops


Syntax:
for( expression1 ; expression2 ; expression3 )
{
statement(s)...;
}

expression1 and expression3 are assignment expressions.


expression2 is a boolean expression (relational or logical) that evaluates to either true (1) or false (0).

1) expression1 is evaluated only once and before the loop starts.


2) expression2 is evaluated (at each iteration of the loop),
3) if expression2 is false the loop is terminated (program continues below the for loop)
4) if expression2 is true,
a) statements inside the loop are executed,
b) then expression3 is executed,
c) then continues the loop with step 2.

Examples:
Add numbers from 41 to 100:
sum = 0; // sum must be initialized before the loop
for (k = 41; k <= 100; k++)
{
sum += k; // add number to the sum
}
printf ("Sum: %d\n", sum); // result must be processed after the loop
Count numbers divisible by 7 among the numbers from 200 to 400:
count = 0; // count must be initialized before the loop
for (k = 200; k <= 400; k++)
{
if ( (k % 7) == 0 )
{

C Programming Language 8 Halil Özmen


count++; // increment the count
}
}
printf ("Count: %d\n", count); // result processed after the loop
Exercise:
• Input an integer number (n), output its first 20 multiples (n, 2n, 3n, 4n, 5n, ..., 20n)

2.2.2. Conditional loops: while loops, do ... while loops

while loops
Syntax:
while( expression )
{
statement(s)...;
}

Examples:
Count numbers divisible by 7 among the numbers from 200 to 400:
count = 0; // count must be initialized before the loop
k = 200;
while (k <= 400)
{
if ( k % 7 == 0 )
{
count++;
}
k++;
}
printf ("Count: %d\n", count);

do ... while loops


Syntax:
do
{
statement(s)...;
} while( expression );

Examples:
• Input y or Y (yes) or n or N (no).
• Input integer values between 0 and 8 (e.g. input selection of a menu).

Usage of sentinel value:


printf ("Enter a number: ");
scanf ("%d", &num);
while (num != SENTINEL_VALUE)
{
....statements....
printf ("Enter a number: ");
scanf ("%d", &num);
}

Exercise:
• Input integer numbers until -999 is entered, output the number of even numbers.
C Programming Language 9 Halil Özmen
Algorithm templates: finding total, average, minimum, maximum.
Rules:
(1) Total (sum), count, max and min must be initialized before the loop starts.
(2) Average must be computed after the loop.
(3) Total, average, count, max and min must be used or output after the loop is
terminated.

Total (sum), count and average:


sum = 0; // sum must be initialized before the loop starts
cnt = 0; // counter must be initialized before the loop starts
printf ("Enter a number: ");
scanf ("%d", &num); // input first number
while (num != SENTINEL_VALUE)
{
cnt++; // counter is incremented inside the loop
sum += num; // add number to total
printf ("Enter a number: ");
scanf ("%d", &num); // input next number
}
ave = 1.0 * sum / cnt; // average must be computed after
the loop
printf ("Total: %d\n", sum); // sum must be used after the
loop
printf ("Count: %d\n", cnt); // counter must be used after
the loop
printf ("Average: %.2f\n", ave); // average must be used after
the loop

Maximum:
printf ("Enter a number: ");
scanf ("%d", &num); // input first number
max = num; // max must be initialized before the
loop
while (num != SENTINEL_VALUE) // while number is not sentinel
value
{
if (num > max) // if number is greater than previous
max,
{ max = num; } // then this number is new max.
printf ("Enter a number: ");
scanf ("%d", &num); // input next number
}
printf ("Max: %d\n", max); // max must be used/output after the
loop

Usage of flag:
In some cases, the termination of a loop may depend on a condition that can be sensed in the
loop. In those cases, the loop condition may depend on a flag that is changed in an "if"
statement in the loop.
The following is a sample template for the usage of flag in loops:
flag = 1;
while (flag == 1 && some_other_condition)
{
statement(s)....
if (....)
{
C Programming Language 10 Halil Özmen
statement(s)....
flag = 0;
}
statement(s)....
}

Displaying a menu for tasks to be performed:


printf ("Menu\n");
printf ("1. Do this ....\n");
printf ("2. Do that ....\n");
printf ("3. Perform this ....\n");
printf ("0. Exit\n");
do
{
printf ("Select: );
scanf ("%d", &select);
} while(select < 0 || select > 3);

A menu where selection is a character:


printf ("Menu\n");
printf ("S. Square ....\n");
printf ("R. Rectangle ....\n");
printf ("C. Circle ....\n");
printf ("X. Exit\n");
do
{
printf ("Select: );
scanf (" %c", &select);
} while(select != 'S' && select != 'R' && select != 'C' &&
select != 'X');

C Programming Language 11 Halil Özmen


3. Modular Programming and Functions

3.1. Basics of Modular Programming

Top-down design
To apply top-down design, the programmer starts with the broadest statement of the problem
solution and works down to more detailed subproblems.

C Library Functions (Built-in Functions):


Some of the C library functions:
Standard Header
Function Purpose, Example Argument(s) Return type
File
sqrt(x) <math.h> double double
abs(a) <stdlib.h> int int
fabs(x) <math.h> double double
exp(x) <math.h> ex (e = 2.71828) double double
pow(x, y) <math.h> xy double, double double
floor(x) <math.h> double double
ceil(x) <math.h> double double

Modular programming:
• understanding modularity:
instead of writing long code segments that performs many differnet tasks, it is much beter
to have shorter code segment where functions are called to perform specific tasks.
• parameter passing,
• returning values.

3.2. Function Definitions and Calling Functions

function call

A standard library function call: y = sqrt (x);

function name argument (parameter)

Assume we have a function that computes the area of a circle given the radius:
function call

Calling this function: area = circlearea (radius);

function name argument (parameter)


The definition of the circlearea function:
// Compute and return the area of a circle where the radius is given.
double circlearea (double r)
{
double area;
area = r * r * PI; // e.g.: #define PI 3.1415926535
return (area);
} // end circlearea

C Programming Language 12 Halil Özmen


Definition:
datatype functionname (parameters...)
{
statements...
}

Calling function (examples):


functionname (arguments...);
variable = functionname (arguments...);
printf ("...%f...", functionname (arguments...) );
if (functionname (arguments...) > value)
while (functionname (arguments...) <= value)

3.3. Functions with no parameters


Sometimes we may need to have functions that perform some task, and to perform this task, the
function does not need any data/value (argument).
In these cases, functions that do not have any arguments (parameters) may be used.
Example:
int displaymenu () // or: int displaymenu (void)
{
int select;

printf ("Menu\n");
printf ("1. Do this ....\n");
printf ("2. Do that ....\n");
printf ("3. Perform this ....\n");
printf ("0. Exit\n");
do
{
printf ("Select: );
scanf ("%d", &select);
} while(select < 0 || select > 3);
return (select);
} // end displaymenu

3.4. Functions with parameters


Most of the time, there is necessity to use function that has arguments, In other words, these functions
need to get some data / input(s) [not input from keyboard!], and/or to have some results/outputs.
Example:
// Display the given number of asterisks.
// This function need to get the number of asterisks to be displayed.
void dispAsterisk (int n)
{
int j;
for (j = 0; j < n; j++)
{
print ("*");
}
} // end dispAsterisk

3.5. Functions that does not return value


If a function does not return a value, than its data type is void. See the above dispAsterisk function.

C Programming Language 13 Halil Özmen


3.6. Functions that return value
Sometimes, after a function performs some task(s), they may produce a result, and give the result
back.

Functions that return a single value:


Example 1: the "circlearea" function given above.
Example 2:
// Gets a integer number as argument.
// Returns 1 if the number is prime, returns 0 otherwise.
int is_prime (int num)
{
int prime = 1;
int k = 2;
while (k <= sqrt(num) && prime == 1) // while (k <= num/2 && prime
== 1)
{
if (num % k == 0) // if num is divisible by k,
{
prime = 0; // then, num is not prime number.
}
k++;
}
return (prime);
} // end is_prime

Calling this function:


int main (void)
{
int num;
printf ("Enter a number: ");
scanf ("%d", &num);
if (is_prime (num) == 1)
{ printf ("%d is a prime number.\n", num); }
else
{ printf ("%d is not a prime number.\n", num); }
return (0);
} // end main

Functions that need to return multiple values:


Sometimes we may need to have a function that returns more than one result. Since in C a
function can only return one object, in these cases, the results can not be returned by function
name, but as parameters. For this purpose, "by reference" parameter passing technique is used.
Example with standard library function: scanf ("%d %d %lf", &num1, &num2, &x);
Example: write a function that gets a double number as argument, returns its square and cube.
void squarecube (double x, double *square, double *cube)
{
*square = x * x;
*cube = x * x * x;
} // end squarecube
Calling this function:
squarecube (y, &sq, &cu); // where y, sq and cu are double variables.

C Programming Language 14 Halil Özmen


Parameter passing techniques:
• By value: this parameter passing technique is used if the value of the parameter will not be
changed after the function call.
Example: printf ("Sum is: %d", total);
The value of total is not changed after the printf function is executed.

• By reference: this parameter passing technique is used if the value of the parameter will be
changed after the function call.
Example: scanf ("%d %d %lf", &num1, &num2, &x);
The values of num1, num2 and x are changed after the above function call is executed.

3.7. Scope of variables


If a variable is declared within a function (main function or any other function), than it is only available
in the function where it is declared.

// Function protoype:
int is_prime (int num);

//==================== main ====================


int main (void)
{
int k;

// Display the prime numbers between 1000 and 2000


for (k = 1000; k <= 2000; k++)
{
if (is_prime (k) == 1)
{
printf ("%d is a prime number.\n", k);
}
}
return (0);
} // end main

//==========================================================
// Gets a integer number as argument.
// Returns 1 if the number is prime, returns 0 otherwise.
int is_prime (int num)
{
int prime = 1;
int k;
if (num < 2)
{ return (0); }
for (k = 2; k <= sqrt(num); k++)
{
if (num % k == 0) // if num is divisible by k,
{
prime = 0; // then, num is not prime number.
break;
}
}
return (prime);
} // end is_prime

The variable k in the function is_prime is a completely different variable than the variable k in the
main function. They have different locations in memory.

C Programming Language 15 Halil Özmen


4. Arrays
Until now, we have used simple data types. Simple data types use a single memory cell to store a
variable.
To solve many programming problems, it is more effective to group data items together in main
memory than to allocate an individual memory cell for each variable.
There are several ways to group related data items together into a single composite data structure.
One such data structure is the array.

Introduction to arrays:
An array is a collection of two or more adjacent memory cells, called array elements, that are
associated with a particular symbolic name.
In C, the array indices starts from 0 (zero). Therefore an array of 100 elements has indices from
0 to 99.

4.1. One dimensional arrays


• Declaration: a constant must be used when declaring the dimension of arrays.
int ar[10]; // an array of 10 integer numbers
double x[XSIZE]; // an array of XSIZE double numbers
char name[NAMESIZE]; // an array of NAMESIZE characters
index: 0 1 2 3 4 5 6 7 8 9
ar:
elements: ar[0] ar[1] ar[2] ar[3] ar[4] ar[5] ar[6] ar[7] ar[8] ar[9]
Note: Char arrays are usually called "string"s. In that case, the char array contains a null
character '\0' that shows the end of the string. The strings will be covered in the next
chapter.

• Initialization during declaration: (values must be written between { and }, and separated by
comma.)
int v[10] = {12, 4, 52, 21, 40, -8, 10}; // last 3 are not initialized
index: 0 1 2 3 4 5 6 7 8 9
v: 12 4 52 21 40 -8 10
elements: v[0] v[1] v[2] v[3] v[4] v[5] v[6] v[7] v[8] v[9]

4.2. Utilization of array elements


Assume we have the following arrays and variables:
int ar[100]; // an array of 100 integer numbers
double x[XSIZE]; // an array of 8 double numbers
char name[20]; // an array of 40 characters
int j, k, n; // variables to be used as array indices.
Examples of array element usages:
ar[0] = 7; // assign 7 to the first element (element 0) of array ar
x[XSIZE-1] = PI; // assign PI to the last element of array x
printf ("%d ", ar[j]); // output the element with index j of array ar
scanf ("%lf", &x[k]); // input to the element with index k of array x
a = ar[j] * 2; // assign to a the value of ar[j] multiplied by 2
ar[j] = ar[j+1] - ar[j+2]; // assign to the element with index j of array ar
ar[j] = floor(x[k] + 0.5); //
if (ar[j] > ar[j+1]) .... // perform if ar[j] is > than ar[j+1]
while (ar[j] < 1000) .... // continue loop while ar[j] is less than 1000

C Programming Language 16 Halil Özmen


while (name[k] != ' ') .... // continue loop while name[k] is not space char.

4.3. Input/Output of Arrays


Examples:
// Input 20 numbers and store in an array:
for (j = 0; j < 20; j++)
{
printf ("Enter a number: ");
scanf ("%d", &(ar[j]) );
}

// Input numbers until 0 is entered and store these numbers in an array:


n = 0;
printf ("Enter a number: ");
scanf ("%d", &num);
while (num > 0) // or: while (num > 0 && n < MAXSIZE)
{
ar[n] = num;
n++;
printf ("Enter a number: ");
scanf ("%d", &num);
}

// Output elements of an array that contains "n" numbers:


for (j = 0; j < n; j++)
{
printf (" %d", ar[j]);
}

Exercises:
• Output the even numbers of an array containing n values. (Attention: numbers have to be even, not
indices.)
• Output the numbers that are divisible by 7 of an array containing n values.
• Output elements with indices 0, 4, 8, 12, ... (multiples of 4) of an array containing n values.

4.4. Array manipulation


Examples:
// Add 12 to all the elements of an array v of 100 elements:
for (k = 0; k < 100; k++)
{
v[k] += 12;
}

// Store the first 20 Fibonacci numbers in an array:


fibo[0] = 1;
fibo[1] = 2;
for (k = 2; k < 20; k++)
{
fibo[k] = fibo[k-1] + fibo[k-2];
}

// Check if a value (val) exists in an array or not:


j = 0;
while (j < numar && val != ar[j])
{

C Programming Language 17 Halil Özmen


j++;
}
if (j < numar)
{ // value is found in j'th element.
...
}
else
{ // value is not found.
...
}

Exercises:
• Store the first 20 triangular numbers in an array. (A number is triangular if it is equal to
1+2+3+4+...+n.)
• Store the first 100 prime numbers in an array. Use a function is_prime that returns 1 if the number
in parameter is a prime number, returns 0 otherwise.

4.5. Arrays as function parameters


When an array is passed as parameter to a function, any changes to the array done in the
function is done in reality directly to the array in the calling function.

Example:
int main (void)
{
int ar[MAXSIZE];
int nar; // number of elements used in ar
. . .
sum = arrtotal (ar, nar);
. . .
doublearray(ar, nar);
. . .
} // end main

//=====================================
// This function returns the sum of numbers in the array.
// It does not change the array.
int arrtotal (int arr[], int numar)
{
int tot = 0, j;
for (j = 0; j < numar; j++)
{
tot += arr[j];
}
return (tot);
} // end arrtotal

//=====================================
// This function double every number in the array.
// It changes the array.
void doublearray (int arr[], int numar)
{
int j;
for (j = 0; j < numar; j++)
{
arr[j] = arr[j] + arr[j]; // or: arr[j] *= 2;
}
} // end doublearray
C Programming Language 18 Halil Özmen
Rule for arrays as function parameters:
If an array does not contain sentinel value (stopping value), then together with the array, the
number of used elements of the array must also be passed as parameter.

Exercises:
• Write a function that returns the maximum value in an array of numbers.
• Write a function that returns the average value of the numbers in an array.
• Write a function that returns the number of upper case letters in an array of characters.
• Write a function that returns the number of even numbers in an array.
• Write a function that changes numbers in an array, so that for odd numbered indices it stores the
squareroot of the number in that element, for even numbered indices it stores the square of the
number in that element.

4.6. Two or more dimensional arrays


Declaration:
int mat[ROWSIZE][COLUMNSIZE];
char names[MAXNAMES][NAMESIZE];

Usage: both the first and the second indexes have to be specified to use the elements of a two
dimensional array.
mat[row][col] = a * 7; // here row and col are integer variables
if (names[n][j] != NULLCHAR) // the j'th char of the n'th string in names.

Examples:
// Fill an 8 by 8 matrix with 10.
for (r = 0; r < 8; r++)
{
for (c = 0; c < 8; c++)
{
ar[r][c] = 10;
}
}

// Make a 10 by 10 multiplicaton table.


for (r = 0; r < 10; r++)
{
for (c = 0; c < 10; c++)
{
ar[r][c] = (r+1) * (c+1);
}
}

// Fill a 10 by 4 matrix with sum of squares of index numbers.


for (r = 0; r < 10; r++)
{
for (c = 0; c < 4; c++)
{
ar[r][c] = r * r + c * c;
}
}

C Programming Language 19 Halil Özmen


Exercises:
• Fill the primary diagonal of a square matrix with 1, and all other elements with 0 (unit matrix).
• Create matrixes as below using nested for loops:
2 3 4 5 6 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
3 4 5 6 7 0 2 3 4 5 0 1 2 3 4 5 4 3 2 1
4 5 6 7 8 0 0 3 4 5 -1 0 1 2 3 1 2 3 4 5
5 6 7 8 9 0 0 0 4 5 -2 -1 0 1 2 5 4 3 2 1
6 7 8 9 10 0 0 0 0 5 -3 -2 -1 0 1 1 2 3 4 5

Two or more dimensional arrays as function parameters:


Like one dimensional arrays, when a multi-dimensional array is passed as parameter to a
function, any changes to the array done in the function is done in reality to the array in the calling
function.

Rule for multi-dimensional arrays as function parameters:


In the function definition, except the first dimension, all the dimensions must be specified.

Example:
int main()
{
int ar2[MAXROW][MAXCOL];
. . .
s = f1(ar2, nrow, ncol);
. . .
} // end main

//===========================================
// 1st dimension of the array parameter is not specified.
// Other dimensions are specified!
int f1 (int ar[][MAXCOL], int nrow, int ncol)
{
. . .
} // end f1

C Programming Language 20 Halil Özmen


5. Strings

5.1. String Basics

What is string? String is a data type to represent "textual data", like name or address.

Declaration:
char str1[11]; // Character string with at most 10 characters

Initialization:
char dept[] = "Computer Science"; // Valid declaration: size = 17

Character strings are null ( '\0' ) terminated. #define NULLCHAR '\0'


0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
C o m p u t e r S c i e n c e \0

ATTENTION: 'Q' and "Q": 'Q' is a single character, and "Q" is a string. (see page 443)

String Constants: Surrounded by double-quotes. Example:


#define INSUFF_DATA "Insufficient Data"

String Assignment:
char string1[20]; /* use eg. MAXLEN instead of 20 */
string1 = "Test string"; /* ERROR: not a valid C statement */
strcpy(string1, "Test string");
strncpy(string1, "Test string", 20);
strncpy(string1, "Test string", 8);

String Copy Library Functions (from library string.h):


Function
Description Parameters Returns
Name
strcpy Copies the contents of the source string into the target string, char *
target string. source string
strncpy Copies up to n characters from the contents of the target string, char *
source string into the target string. source string,
Does not null terminate! number of
characters

Attention about overflow:


strcpy(string1, "A very long test string"); /* ing\0 not stored and
following variables change!! */

Input/Output:
Character scanf("%c", &chr1);
Input chr1 = getchar();
chr1 = getc(stdin);
Output printf("%c", chr1);
putchar(chr1);
putc(chr1, stdout);
Word scanf("%s", string1); // ATTENTION: not &string1 but only string1
Input scanf("%s%s%d", last_name, first_name, &age); // separated by spaces
Output printf("%s", last_name);
printf("%s", str1); // Prints whole str1 even if it contains more than 1 words
Line gets(string1); // Gets a line from keyboard and stores in str1 (without \n)
Input fgets(str1, MAXLEN, stdin);
Output puts(string1);
printf("%s", string1);
C Programming Language 21 Halil Özmen
Input/Output String Format Qualifiers: "%ns" where n is the space allocated for the string.

Exercises:
1. Write a program that inputs a line of text, counts the number of blanks, and displays the number
of blanks.
2. Write a program that inputs a line of text, counts the number of blanks by using a function, and
displays the number of blanks. Perform this by modifying the above program.
3. Write a program that inputs a line of text and a symbol (character), counts the number of the
specific symbol by using a function, and outputs the count. Perform this by modifying the above
program.
4. Write a program that inputs a character and an unknown number of lines of text, counts the
number of the specific symbol in a line of text by using a function, and outputs the overall count.
Perform this by modifying the above program.
5. Write a program that inputs a line of text and two characters, replaces all the occurences of the
first character by the second character by using a function, and outputs the new string.

String Manipulation:
Data operations related with strings. With integers: add, subtract, multiply, divide.
With strings: ...

First, let's write some functions without using string manipulation library functions.
• Write a function which copies a string to another (char by char).
• Write a function that counts a character in a string. (a) ' ' Space (fixed); (b) A given char
(parameter).
• Write a function that checks if a string begins with another string. Then solve with "strstr" function.
Solutions of these three examples are on page 6.

String Length:
Number of characters in a string up to but not including null character '\0' at the end. (strlen())

String Comparison:
Comparison of characters: based on ASCII code of characters.
'A' < 'B' 'a' < 'b' '0' < '1' '0' < 'A' 'A' < 'a' 'Z' < 'a' '!' < '$'
String comparison is based on the character comparison in respective positions in the two
strings.
If two strings has identical characters for the length of shorter string, the longer string is greater
(after).
"ABCDEF" < "ABCDEG" "ZAA" < "a0" "Veli" < "ali" "Vali" < "Veli"
"VELI" < "Vali" "AX4520" < "AX94" "10" < "2" "Ali Veli" < "Ali"

5.2. String Functions


Some of the String Manipulation Library Functions (from library string.h):
Function
Description Parameters Returns
Name
strlen Returns the number of characters in string, not string int
counting the terminating null character.
strcat Appends source string to the end of target string. target string, char *
source string
strncat Appends n characters from source to the end of target string, char *
target string. source string,
number of
characters

C Programming Language 22 Halil Özmen


strcmp Compares string1 and string2; returns a negative string1, string2 int
value if string1 precedes string2, returns 0 if the
strings are equal, a positive value if string2
precedes string1.
strncmp Compares up to n characters string1 and string2; string1, string2, int
returns a negative value if str1 precedes str2, 0 if number of
the strings are equal, a positive value if str2 characters
precedes str1.
strstr Searches if string2 occurs in string 1. If found, string1, string2 char
returns address of location in string1 where pointer to
string2 occurs, if not found returns NULL. the found
location

Concatenation:
Concatenation is joining two strings (putting strings one after the other) to make a longer string.

Substring: Substring is a part (portion) of a string. Usually substring is defined by 3 elements: the
source string, the starting position and the length of substring.
strncpy(string2, string1+5, 8); /* Copies 8 chars starting from 5th char of
string1 */
strncpy(string2, &string1[5], 8); /* Copies 8 chars starting from 5th char of
string1 */
Substring Search: (See example function - long implementation without strstr.)
strptr = strstr(str1, str2);
if (strptr != NULL)
printf("Small string is in position %d in large string.\n", strptr-str1);
else
printf("Small string does not occur in large string.\n");

Insertion: This is the insertion of a string into a given position of another string. See the example
function.

Arrays of Strings:
#define NUM_PEOPLE 40
#define NAME_LEN 21
char names[NUM_PEOPLE][NAME_LEN];
char days[7][10] = {"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"};
M o n d a y \0 ? ? ?
T u e s d a y \0 ? ?
W e d n e s d a y \0
T h u r s d a y \0 ?
F r i d a y \0 ? ? ?
S a t u r d a y \0 ?
S u n d a y \0 ? ? ?

Using a string from Array of strings:


scanf("%s", names[j]);
strcpy(names[4], "Halil Ozmen");
if(strcmp(names[j], names[j+1] > 0)
strcat(longname, names[k]);

Using a character from Array of strings:


scanf("%c", &names[j][k]);
chr1 = names[j][0]; /* First char of names[j] string */
names[j][n] = NULLCHAR;

Example: Find the earliest occurrence of a character in an array of strings.

C Programming Language 23 Halil Özmen


Strings as Function Parameters:
The address of string variable is passed.
char name[NAME_LEN];
char str_arr[20][NAME_LEN];
Parameter in Prototype Arguments in Function Call Explanation
char <str-var>[] name Start address of name is passed.
Eg: char name[] &name[0] Same as above.
&name[j] Address of string at j'th position is passed.
name+j Same as above (&name[j])
char str1[] str_arr[4] Address of 4th string (str_arr[4]) is passed.
&str_arr[4][0] Same as above.
&str_arr[4][j] Address of string at j'th position of str_arr[4]
str_arr[4]+j Same as above
char str_arr Address of whole string array
s_arr[][NAME_LEN] str_arr[4] Address string array starting from the 4th

Pointers to strings:
Frequently, there are needs to define pointers to strings in order to perform some string
manipulation functions.
Pointer is a data type which shows the address of data types.
In char name[20], when used alone "name" is a pointer to beginning of the char array which forms the
string.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

name &name[8] or name+8

char line[MAX_LINE_LEN];
char *strptr;
. . .
gets(line);
for (strptr = line; *strptr != '\0'; strptr++)
{
....
}

5.3. Character Analysis and Conversion:


Frequently in string manipulation, there may be need to know what type of character we have.
Character Analysis and Conversion Library Functions (from library ctype.h):
Function Description Parameters Returns
Name
isalpha Checks if character is alphabetic or not. Returns 0 if not. character int
isdigit Checks if character is digit or not. Returns 0 if not. character int
islower, Checks if character is lower/upper case or not. Returns 0 character int
isupper if not
ispunct Checks if character is punctuation or not. Returns 0 if character int
not.
isspace Checks if character is whitespace or not. Returns 0 if character int
not.
tolower, Converts the alphabetic character to lower/upper. character character
toupper

C Programming Language 24 Halil Özmen


String-to-Number and Number-to-String Conversions
Sometimes programmers need to convert a given string which contains digits to a number data
type.
Eg: "1234" string to int which has the value 1234. Or, "624.234" to double with the value
624.234.

Also, even more frequently, programmers need to make a string from number data types (int,
double, etc.). Eg: int day=2, month=10, year=2001, create a string as "02/10/2001".

The sscanf and sprintf can be used for string/number conversion purposes.
strcpy(line1, "1234");
sscanf(line1, "%d", &numint);

strcpy(line2, "624.234");
sscanf(line2, "%lf", &numdbl);

strcpy(line3, "14678 Halil 3.25");


sscanf(line3, "%ld %s %lf", &id, name, &cgpa);

sprintf(string1, "%02d/%02d/%04d", day, month, year);

Other String-to-Number and Number-to-String Conversion Functions (from library stdlib.h):

Function Description Prototype


Name
atoi, atol Converts string to integer (long integer) int atoi(const char *s);
long atol(const char *s);
atof Converts string to double. double atof(const char *s);
itoa, ltoa Converts integer (long integer) to string. char *itoa(int value, char *string, int radix);
ATTENTION: NOT in ANSI C. char *ltoa(long value, char *string, int radix);

String Manipulation Examples:

• Write a function which copies a string to another (char by char).

#define NULLCHAR '\0'


void stringcopy (char str1[], // Target/destination String
const char str2[]) // Source String
{
int j = 0; // index var for characters

/* Process characters of the strings until NULLCHAR */


while(str2[j] != NULLCHAR)
{
str1[j] = str2[j]; // Copy char from source string to target
j++; // Increment character index
}
str1[j] = NULLCHAR; // NULL terminate target string
} // end stringcopy

• Write a function that counts a character in a string. (a) ' ' Space (fixed); (b) A given char
(parameter).

#define NULLCHAR '\0'


int countchar (char str1[], /* String to be scanned */
char chr1) /* Char to be counted */
{

C Programming Language 25 Halil Özmen


int j = 0; /* index var for characters */
int count = 0; /* Counter for character */

/* Process characters of the string until NULLCHAR */


while(str1[j] != NULLCHAR)
{
/* Check character if it is wanted one or not */
if(str1[j] == chr1)
{ count++; } /* Increment counter */
j++;
}
return(count);
} // end countchar

• Write a function that checks if a string begins with another string.

int checkbegin (char str1[], /* Main String */


char str2[]) /* String to be checked */
{
if(strstr(str1, str2) == str1)
{ return(1); }
else
{ return(0); }
} /* end checkbegin */

Concatenation:

Example: Concatenation of strings.


char last_name[20]; /* use NAME_LEN instead of 20 */
char first_name[20];
char name[41]; /* Shall contain: "Last Name, First Name" */

//len1 = strlen(last_name);
strcpy (name, last_name);
strcat (name, ", ");
strcat (name, first_name);
//name[len1+2+len2] = '\0'; /* NULL terminate the string */

Insertion: This is the insertion of a string into a given position of another string.

Example: Insert a string after the nth character in a string:


void insert_string(char str1[], char str2[], int pos)
{
int len1;
char temp1[MAXLEN];

len1=strlen(str1);
if(pos <= 0 || pos > len1)
printf("Error, Position is out of bounds");
else
{
strcpy(temp1, &str1[pos]); /* Save 2nd part of str1 */
strcpy(&str1[pos], str2); /* Copy str2 to pos in str1 */
strcat(str1, temp1); /* Append the 2nd part of str1 */
}
} /* end insert_string */

Example input: str1=dement


str2=part
C Programming Language 26 Halil Özmen
pos=1

Substring: Substring is a part (portion) of a string. Usually substring is defined by 3 elements: the
source string, the starting position and the length of substring.
strncpy(string2, string1+5, 8); // Copies 8 chars starting from 5th char of string1
strncpy(string2, &string1[5], 8); // Copies 8 chars starting from 5th char of string1

Substring Search: (See strstr library function!!)

char str1[] = "'It belongs to me' said the long John.";


char str2[] = "long";
char *ptr;

ptr = strstr(str1, str2);


if (ptr!= NULL)
printf("String-2 is in position %d in string-1.\n ", ptr-str1);
else
printf("String-2 does not occur in string-1.\n");

Count number of occurences of a string in another string:

char str1[....], str2[....];


char *ptr;
.... ....
count = 0;
ptr = strstr(str1, str2);
while (ptr != NULL)
{
count++;
ptr = strstr(ptr + strlen(str2), str2);
}
printf("String-2 occurs %d times in string-1.\n ", count);

C Programming Language 27 Halil Özmen


6. Structures

What is a structure in C?
What data is related with e.g. cars, students, courses, meals, planets, etc.? Think about various
data items. Each thing has data items like: name, size, weight, speed, color, address, location,
length, duration, etc.

"Structure in C" is a data structure which is a collection of various data elements that can be of
different data types.

Structure Type Definition: Simple Structure Example:


typedef struct typedef struct person
{ { /* description of a person */
<type1> <id_list1>; char name[41];
<type2> <id_list2>; int birthyear;
. . . } person_t;
<typen> <id_listn>;
} <struct_type>;

Example Structures: Declaration of a book_t entity:


#define MAXLEN 41 book_t book1;

typedef struct book_s title author publisher pages price


{ // description of a book
char title[61]; or:
char author[41]; book1
char publisher[21]; title
int pages; author
double price; publisher
} book_t; pages
price
typedef struct
{
int id; // ID of the student
char name[MAXLEN]; // Name of the student
int quiz1; // Quiz-1 grade of the student
int quiz2; // Quiz-1 grade of the student
int midterm; // Midterm grade of the student
int final; // Final grade of the student
double overall; // Overall grade of student
char letter_grade[3]; // Letter grade of the student
} student_t;

typedef struct // Example with an array in the structure


{
char name[MAXLEN]; // Name of the student
int grade[10]; // Grades of the student
double overall; // Overall grade of student
} student2_t;

Structure Declaration:
book_t book1, book2, new_book;
student_t student1, student2;
student2_t std1, std2;

C Programming Language 28 Halil Özmen


Initialization:
student_t student1 = {20021248, "Fatma", 54, 47, 61, 52, 56.7, "C+"};
book_t book1 = {"Problem Solving and Program Design in C",
"J. R. Hanly and E. B. Koffman",
"Addison Wesley", 458, 29.95},
new_book = {"", "", "", 0, 0};

Accessing Structure Members:


Selection operators
. direct member selector
-> indirect member selector (to be explained below in pointers to structures.)

Individual members of a structure is accessed by the use of a structure member selection


operator.
structure variable name member name

cs_stu.gpa = 2.40;

direct selection operator (.)

Assignment to Elements of Structures:


The elements of structures are processed as single variables of that type.

strcpy(student1.name, "Ayhan");
student1.quiz1 = 64;
student1.overall = student1.quiz1 * 0.1 + student1.quiz2 * 0.1 +
student1.midterm * 0.3 + student1.final * 0.5;
student1.name[nlen] = NULLCHAR;

total = 0;
for(j = 0; j < 10; j++)
total += std1.grade[j]; // Example of array within structure
std1.overall = total / 10.0;

Assignment to Structures as a whole: (Example: swap two structure contents.)


student_t student1, student2, tempstd;
tempstd = student1; // Copies the all elements to target structure
student1 = student2; // Copies the all elements to target structure
student2 = tempstd; // Copies the all elements to target structure

Input and Output of Structure Elements: As with normal variables or arrays.


scanf("%d", &student1.final);
scanf("%s %lf", book1.name, &book1.price);
printf("Name: %s, Overall: %6.2f, Letter: %s\n", student1.name,
student1.overall, student1.letter_grade);

Input and Output of Whole Structures:


Whole structures can be written to and read from binary files.
fwrite(&student1, sizeof(student1), 1, outfp);
fread(&student1, sizeof(student1), 1, infp);

Example Programs:
1. Write a program that reads student information (id, name, birthyear) entered by the user into a
structure and display its contents. Write a function to read student info into a structure. Write a
function to display info in a given student structure.

C Programming Language 29 Halil Özmen


Function that reads information and returns a structure:
typedef struct
{
int id; /* ID of the student */
char name[MAXLEN]; /* Name of the student */
int birthyear; /* Year of birth of the student */
} student_t;

/*------------------------------------------------------------------*/
/* Function that reads student information entered by the user and */
/* returns a structure. */
/*------------------------------------------------------------------*/
student_t read_student ()
{
student_t std;
char dummy[10];

printf ("Enter student id: ");


scanf ("%ld", &std.id);
gets (dummy); /* To clear remaining newline */
printf ("Enter student name: ");
gets(std.name);
printf ("Enter student birth year: ");
scanf ("%d", &std.birthyear);
gets (dummy); /* To clear remaining newline */

return(std);
} /* end read_student */

Comparing Two Structures:


typedef struct
{
int id; /* ID of the student */
char name[MAXLEN]; /* Name of the student */
int birthyear; /* Year of birth of the student */
} student_t;

/* Function to check if two structures are equal or not. */


/* Returns non-zero if structures are equal, */
/* returns 0 if the structures are NOT equal */
int student_equal (student_t std1, student_t std2)
{
return (std1.id == std2.id &&
strcmp(std1.name, std2.name) == 0 &&
std1.birthyear == std2.birthyear );
} /* end student_equal */

Arrays of Structures:
student_t students[MAX_STUDENT];

strcpy(students[j].name, "Halil"); // Assign "name" of a student


students[j] = students[k]; // Copy whole of students[k] to students[j]
students[j].quiz1 = 0;

C Programming Language 30 Halil Özmen


Nested Structures:
typedef struct
{
char name[MAXLEN]; /* Name of the person */
int birthyear; /* Birthyear of the person */
int height; /* Height in cm of the person */
double weight; /* Weight in kg of the person */
} person_t;

#define MAXCHILD 10

typedef struct
{
person_t father; /* Father's information */
person_t mother; /* Mother's information */
int num_children; /* Number of children */
person_t child[MAXCHILD]; /* Children's information */
} family_t;

Usage of Nested Structures:


family_t family1;
. . .
strcpy(family1.father.name, "Mustafa");
family1.mother.birthyear = 1960;
for(jchild = 0; jchild < family1.num_children; jchild++)
totalweight += family1.child[jchild].weight;

Pointers to Structures:

book_t text_book;
book_t ref_book;
book_t *book_ptr; /* pointer to a book structure */
book_ptr = &text_book; // assignment to book_ptr pointer

book_ptr
title author publisher pages price

strcpy((*std_p).name, "Halil"); // Assign "Halil" to name of a student


strcpy(std_p->name, "Halil"); // Assign "Halil" to name of a student
std_p->final = 100; // Assign 100 to final
scanf("%d", &(std_p->midterm) ); // Read midterm value

Structures as Function Parameters:

Elements of Structures as Function Parameters: Like other variables.

/* A structure element passed by address */


scanf ("%d", &student1.midterm);

/* A structure element passed by value */


printf ("Quiz1: %d Quiz2: %d Midterm: %d\n",
student1.quiz1, student1.quiz2, student1.midterm);

/* Several structure elements passed by value */


student1.overall = compute_overall (student1.quiz1, student1.quiz2,
student1.midterm, student1.final);
C Programming Language 31 Halil Özmen
/* Function Prototype */
double compute_overall(int q1, int q2, int mt, int fin);

/* Function */
double compute_overall(int q1, int q2, int midterm, int final)
{
return(q1 * 0.1 + q2 * 0.1 + midterm * 0.3 + final * 0.5);
}

Structures (as whole) as Function Parameters:

A) Structure is passed (by value)


. . .
func1(student1);
. . .

/* Function */
void func1(student_t std)
{
. . .
printf("Final grade: %d\n", std.final);
. . .
} /* end func1 */

B) Address of structure (pointer to structure) is passed (by address).


. . .
func2(&student1);
. . .

/* Function */
void func2(student_t *std_p)
{
. . .
scanf("%d", &(std_p->final) );
. . .
} /* end func2 */

C Programming Language 32 Halil Özmen


7. Pointers

7.1. Pointer Basics


A pointer is a variable that contains the address of a variable. Pointers are much used in C, partly
because they are sometimes the only way to express a computation, and partly because they usually
lead to more compact and efficient code than can be obtained in other ways. Pointers are frequently
used with arrays, and strings (which are char arrays).
Pointers sometimes can be used to contain the address of a function.

Pointer Operators:
& operator: Address operator, gives the address of its operand.
&a  address of variable a.
&aPtr  address of aPtr.
* operator: It gives the content in an address.
*aPtr  the content in the address aPtr.
aPtr = &a; // address of a is assigned to aPtr.
printf("%d\n", *aPtr); // prints content in address aPtr

NULL Pointer:
Sometimes a pointer may point to nothing, in this case is value is NULL. These are called NULL
pointer.

Relations among pointers and arrays:


An array name is the starting address of that array, so in a sense it is a pointer that does not change.
int a = 77;
int arr[100]; // arr is the start address of this array
int j;
int *aPtr = &a;
int *arrPtr;
arrPtr = arr;
According to the above declarations, the followings are equivalent or produce same value.
a ≡ *aPtr *aPtr is the value of a
arr ≡ &arr[0] arr is the start address of array, so address of arr[0]
arr[j] ≡ *(arr + j) Both gives the value (content) of j'th element of arr
*arrPtr ≡ arrPtr[0]
*(arrPtr+j) ≡ arrPtr[j]
arrPtr+j ≡ &(arrPtr[j])

Arithmetic operation on pointers:


If a pointer points an element of an array, then when it is incremented by one, it points to next element
of that array.

Example pointer declarations:


#define NULLCHAR '\0'

int k, *i_p;
double x, *d_p;
char c, *c_p;
char str[80] = "Foundation, Dune and The Lord Of The Rings";

i_p = &k; // address of k is stored in i_p


d_p = &x; // address of x is stored in d_p
c_p = &c; // address of c is stored in c_p
c_p = str; // str (which is the start address) is stored in c_p

C Programming Language 33 Halil Özmen


while(*c_p != NULLCHAR)
{
....
c_p++;
}

Function that copies even numbers in array (a1) to another array (a2):
// copyEven: copies even numbers of a1 to a2.
int copyEven(int *a1, int n1, int *a2)
{ int copyEven(int *a1, int n1,
int n2 = 0; int *a2)
int j; {
for(j = 0; j < n1; j++) int n2 = 0;
{ int j;
if (*a1 % 2 == 0) for(j = 0; j < n1; j++)
{ {
*a2 = *a1; if (a1[j] % 2 == 0)
a2++; {
n2++; a2[n2] = a1[j];
} n2++;
a1++; }
} }
return (n2); return (n2);
} // end copyEven } // end copyEven

Function that copies alphabetic characters in a string (s1) to another string (s2):
// copyAlpha: copies alphabetic chars in s1 to s2.
void copyAlpha(char *s1, char *s2)
{
while(*s1 != NULLCHAR)
{
if(isalpha(*s1))
{
*s2 = *s1;
s2++;
}
s1++;
}
*s2 = NULLCHAR;
} // end copyAlpha

7.2. Dynamic Memory Allocation

The C programming language provides several functions for memory allocation and management.
These functions can be found in the <stdlib.h> header file.
Function Description
void *malloc(int num); This function allocates an array of num bytes and leave
them uninitialized.
void *calloc(int num, int size); This function allocates an array of num elements each of
which is "size" bytes long.
void free(void *address); This function releases a block of memory block specified
by address.
void *realloc(void *address, int newsize); This function re-allocates memory extending it upto
newsize.

C Programming Language 34 Halil Özmen


Sample program that uses dynamic memory allocation:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRSIZE 100

int main()
{
char name[STRSIZE] = "Amadeus Mozart";
char *sptr; // will point to dynamically allocated memory

// allocate memory dynamically:


sptr = malloc( 200 * sizeof(char) );

if(sptr == NULL) // means malloc could not allocate memory.


{
fprintf(stderr, "Error - unable to allocate required memory\n");
return(EXIT_FAILURE);
}
else
{
strcpy(sptr, "Mozart is one of the best classical music compositors.");
}

printf("Name = %s\n", name);


printf("Description: %s\n", sptr);
free(strptr); // release memory using free() function.
return(EXIT_SUCCESS);
} // end main

7.3. Linked Lists

Introduction
A linked list is a set of dynamically allocated nodes, arranged in such a way that each node contains
one value and one pointer. The pointer always points to the next member of the list. If the pointer is
NULL, then it is the last node in the list.
Linked lists have a few advantages over arrays:
1. Linked lists are dynamic. There is no need to define an initial size.
2. Items can be added to or removed from anywhere in the list.
However, linked lists also have a few disadvantages:
1. There is no "random" access - it is impossible to reach the nth item in the list without first iterating
over all items up until that item. This means we have to start from the beginning of the list and
count how many times we advance in the list until we get to the desired item.
2. Dynamic memory allocation and pointers are required, which complicates the code and
increases the risk of memory leaks and segment faults.
3. Linked lists have a much larger overhead over arrays, since linked list items are dynamically
allocated (which is less efficient in memory usage) and each item in the list also must store an
additional pointer.

Linked List Typedefs:


typedef struct
{
char brand[BRANDLEN]; // brand of car, e.g. "Toyota"
char model[MODELLEN]; // model of car, e.g. "Corona"

C Programming Language 35 Halil Özmen


int year; // year of car, e.g. 2012
int km; // kilometer of car, e.g. 15000
double price; // price of car, e.g. 72500
} data_t;

typedef struct node_s


{
data_t item; // Data part of the node
struct node_s * next; // Link to next node
} node_t;
typedef node_t* nodeptr; // Pointer type to node_t

Basic Linked List Functions:


// create a node, store data in it, add node to beginning of LL.
void add_begin(nodeptr *head, // head of the list
data_t item ) // data of the list
{
nodeptr newptr, ptr;
newptr = malloc(sizeof(node_t)); // Get a new node
newptr -> item = item; // Store data into new node
newptr -> next = *head; // Set next of new node to old 1st node
*head = newptr; // head points to this new node.
} // end add_begin
//add_end: create a node, store data in it, add node to end of LL.
void add_end(nodeptr *head, // head of the list
data_t item ) // data to be added to the list
{
nodeptr newptr, ptr;
newptr = malloc(sizeof(node_t)); // Get a new node
newptr -> item = item; // Store data into new node
newptr -> next = NULL; // Set next of new node to NULL

if (*head == NULL) // If Linked list is empty


{
*head = newptr; // add to beginning
}
else
{ // Linked List was not empty. Find last node.
ptr = *head; // point to beginning of list
while(ptr -> next != NULL) // While it is not the last node,
{ ptr = ptr -> next; } // Move to the next node
ptr -> next = newptr; // old last node is followed by new node
}
} // end add_end
// display_list: Display the information in LL on screen.
void display_list (nodeptr head)
{
nodeptr ptr = head; // Ptr to current node
while ( ptr != NULL ) // Traverse until end of list
{ // Display data
printf ("%-16s %-16s %4d %6d %10.2lf\n",
ptr->item.brand, ptr->item.model, ptr->item.year,
ptr->item.km, ptr->item.price);
ptr = ptr -> next; // Move to next node
}
} // end display_list

C Programming Language 36 Halil Özmen


8. Files

What is a file?
A collection of data or information that has a name, called the filename. Almost all information
stored in the secondary storage of a computer must be in a file. There are many different types
of files: data files, text files, program files, directory files, and so on. Different types of files store
different types of information. For example, program files store programs, whereas text files
store text. The file extensions are important to distinguish among various file types: .txt -> text
files, .bin binary files, .c and .cpp program code files, .exe executable files etc.

Creating Text Files:


It is possible to create, access and update a text file using an editor (including the editor you are
using for writing your program code.) as well as from a program.

End-of-File (EOF)
EOF is a special character that marks the end of the file. It is a defined constant in stdio.h.

Declaration:
FILE * fileptr; /* a pointer pointing to a file definition */

stdio.h contains a definition of type FILE which is used to store the information necessary for file
processing. For each file a separate FILE * must be declared.

FILE * infile, /* input file – file to read from */


* outfile; /* output file – file to write into */

Opening a file: In order to read from or to write into a file, the file must be opened (opening a file is
accessing to the file information and getting ready to make operations on that file). The fopen
function is used to open a file and returns the file pointer on success and NULL on error. (NULL
is a pointer pointing to nowhere; defined in standard libraries like stdio.h, stdlib.h

infile = fopen("e:\\myfile.txt", "r");

fopen has two parameters, both are strings (pointers to characters)


• first parameter: pointer to a string containing a valid file name (including path specification)
• second parameter: mode

char filename[40]="c:\\cs101\\lab06\\names.txt";
infile = fopen(filename, "r");
outfile = fopen("newdata.txt","w");

Always check for existence when opening for reading:

if (infile == NULL)
{
printf("\n**** File does not exist! ****");
exit(EXIT_FAILURE);
}

exit is a standard function defined in stdlib.h and terminates a program. It causes all files to be
closed before terminating. A zero as a parameter to exit indicates a normal exit and a non-zero
indicates an error.
EXIT_SUCCESS and EXIT_FAILURE are constants defined in stdlib.h

Always close a file at the end of your program! Failure to close a file may cause trouble including
lost data, destroyed files and possible errors in your program!
fclose(infile);
C Programming Language 37 Halil Özmen
Functions related with files:
Function Description Parameters Returns on Returns on
Name success error
fopen opens a file string containing file name, FILE * NULL
string containing mode
fclose closes a file file pointer 0 EOF
fgetc reads a single character file pointer the character EOF
getc
fputc writes a single character character to write, file the character EOF
putc into an output file pointer
fgets reads a string from the string, number of string NULL
input file (keeps the characters, file pointer on end of file
newline, adds null ch)
fputs writes a string into the string, file pointer last character EOF
output file (does not place written
newline)
feof checks for end of file file pointer zero if end of file -
is reached,
non-zero if not
fscanf reads formatted data from a file pointer, format string, number of values EOF
text file variable list read on end of file
fprintf writes formatted data into a file pointer, format string,
text file variable list

Modes in Opening Files:


Mode Meaning
r Open for reading starting from the beginning of the file. The file must already exist.
w Open for writing starting at the beginning; content is destroyed for existing files;
a Open for writing to the end of an existing file (adding text to an existing file) starting writing
at the end of the existing data.
r+ Open for reading and writing; reading starts at the beginning; may write when the end of the
file is reached
w+ Open for writing and reading; writing starts at the beginning; content is destroyed for
existing files; may rewind to the beginning and read
a+ Open for adding text to the end of an existing file and reading after rewinding to the
beginning of the file

Reading from an input text file:


Character by character: ch = fgetc(infile);
Line by line: fgets(str, MAXLEN, infile);
Formatted: fscanf(infile, "%d%s", &number, name);

Writing into an output text file:


Character: fputc(ch, outfile);
String: fputs(str, outfile);
Formatted: fprintf(outfile, "\nName: %s Age: %d\n", name, age);

Examples:
• Write a program that reads and display the contents of a text file.
• Write a program that reads characters from a text file and displays each character on a new line.
• Write a program that counts and displays the number of lines in a text file. Uses a function for
counting lines of a given file.
• Write a program that uses a function for counting the number of blanks in a text file and displays
the result.

C Programming Language 38 Halil Özmen


Binary file:
A binary file, unlike a text (an ASCII) file, contains more than plain text. It may contain additional
code information for photos, sounds, videos, a spreadsheet, or formatted word-processing text.
Like a text file, a binary file is made up of machine-readable symbols that represent 1s and 0s.
Binary files include sound files, graphics files, and software, and are frequently called binaries.
If you want to transmit a file over the Internet, such as downloading a piece of software, a sound
or picture file, or a formatted word-processing document, choose the "binary" option. If the file is
simply unformatted text, choose the "ASCII" or "text" option.

Creating Binary Files:


Binary files can be created by a program that writes the binary form of information into the file.

Opening a binary file:


binp = fopen("info.bin", "rb");
boutp = fopen("newinfo.bin", "wb");

Modes in Opening Binary Files:All the modes of text files are valid, only a 'b' is appended to the end
of the mode string. I.e.: "rb", "wb", "ab", "r+b", "w+b", "a+b".

Functions related with binary files: (Requires stdio.h)


Function Description Parameters Returns on Returns
Name success on error
fread Reads a specified number ptr: address to a block into which number of 0 on end-
of equal-sized data items data is read; items (not of-file (or
from an input stream (a size: Length of each item read, in bytes) error)
binary file) into a block. bytes; actually
n: Number of items read; read
fileptr: File pointer.
fwrite Writes to a binary file. ptr: Pointer to any object; the data number of 0 on error.
appends a specified written begins at ptr; items (not
number of equal-sized size: Length of each item of data; bytes)
data items to an output n: Number of data items to be actually
file. The total number of appended; written.
bytes written is (n * size) fileptr: Pointer to output file.

Reading from an input binary file:


int number;
fread(&number, sizeof(int), 1, inp);

sizeof is an operator that returns the size in bytes of a type or a variable or an expression.
sizeof(char) sizeof(int) sizeof(double) sizeof(string1) sizeof(numarr) sizeof(struct car_s)

Writing into an output binary file:


int number;
fwrite(&number, sizeof(number), 1, outp);

Examples:
1. Write a program that creates a binary file named "int.bin" containing all integers between 1 and 50.
2. Write a function that reads integers form a binary file and use it to display contents of int.bin.
3. Read integers from a binary file and store the positive values in an array, negative values in another array.
4. Write a program that reads student information (id, name, birthyear) from text file (stu02.txt) into a structure
and display its contents. Name is enclosed between double-quotes in the input text file. Write a function to
read student info from a text file into a structure. Write a function to display info in a given student structure.
5. Write a program that reads student information (id, name, birthyear) from text file (stu02.txt) into a structure
and write into a binary file. Name is enclosed between double-quotes in the input text file. Write a function to
read student info from a text file into a structure.
6. Write a program that reads fast food information from text file into structure and writes into a binary file. Write
another program that reads this binary file and displays on screen.

C Programming Language 39 Halil Özmen


9. Bit Manipulation

Bitwise Operators:
Bitwise operators work on bits and perform bit by bit operations.

Operator Description Example


Binary AND Operator copies a bit to the result if it exists in n = n & 0x000000FF;
&
both operands. n = n & 0xAAAAAAAA;
n = n | 0x000000FF;
| Binary OR Operator copies a bit if it exists in eather operand. n = n | 0xFFFF0000;
Binary XOR Operator copies the bit if it is set in one operand n = n ^ 0x0000FFFF;
^
but not both.
Binary Ones Complement Operator is unary and has the
~ n = ~n;
efect of 'flipping' bits.
Binary Left Shift Operator. The left operands value is moved n = n << 4;
<<
left by the number of bits specified by the right operand.
Binary Right Shift Operator. The left operands value is moved n = n >> 8;
>>
right by the number of bits specified by the right operand.

Assume: char A = 60, B = 13; Now in binary format they will be as follows:
A = 0011 1100 60
B = 0000 1101 13
---------------
A&B = 0000 1100 12 in decimal
A|B = 0011 1101 61 in decimal
A^B = 0011 0001 49 in decimal
~A = 1100 0011 -61.

y = x & 1 // Bitwise AND x with 1 (1 == 0b00000001).


x = x & 255 // Bitwise AND x with 255 (clear except lower byte).
z = x | 15 // Bitwise OR x with 15 (1 == 0b00001111).
a = 12345678;
printf("a = %d Hex= %08x\n", a, a); // Print a both in decimal and hexadecimal
n = 0x04F67C8D;
n = n | 0x000000FF; // Bits of lower byte are set to 1
n = n | 0x0000FF00; // Bits of 3rd byte are set to 1
n = n | 0xAAAAAAAA; // Bits 0 2 4 8 10 12 .... are set to 1
n = n & 0x000000FF; // Bits of bytes 1 to 3 are set to 0
n = n & 0xFFFF0000; // Bits of bytes 3-4 are set to 0
n = n & 0x55555555; // Bits 0 2 4 8 10 12 .... are set to 0
printf(" a | 0x000000FF = %08x\n", a | 0x000000FF);
printf(" a | 0x0000FF00 = %08x\n", a | 0x0000FF00);
printf(" a & 0x000000FF = %08x\n", a & 0x000000FF);
printf(" a & 0xFFFF0000 = %08x\n", a & 0xFFFF0000);
printf(" ~a = %08x\n", ~a); // 1's complement of a

if (n & 1) // if n is odd.

a = a >> 1; // Shift right a by 1 bit. Same as: (a >>= 1)


a = a << 1; // Shift left a by 1 bit. Same as: (a <<= 1)
// Count number of bits equal to 1 in the variable x.
for (count = 0; x != 0; x >>= 1) // x >>= 1 is equivalent to x = x >> 1
{
if ( x & 1 )
{ count++; }
}

C Programming Language 40 Halil Özmen


10. System Calls

10.1. Directory and File Manipulation System Calls

Function Prototype Description Include File


DIR *opendir(const char *dirname); Open a directory dirent.h
struct dirent *readdir(DIR *dirp); Read directory dirent.h
int closedir(DIR *dirp); Close directory dirent.h
void rewinddir(DIR *dirp); Reset position of directory stream to the dirent.h
beginning of a directory
int unlink (const char *filename); Delete file unistd.h
int remove (const char *filename); This is the ISO C function to remove a file. It stdio.h
works like unlink for files and like rmdir for
directories.
int rmdir (const char *filename); Deletes a directory. The directory must be unistd.h
empty before it can be removed; in other
words, it can only contain entries for . and .. .
int rename (const char *oldname, Renames file. stdio.h
const char *newname);
int mkdir (const char *filename, Create directory sys/stat.h
mode_t mode)

See: https://www.gnu.org/software/libc/manual/html_node/File-System-Interface.html

struct dirent
{
long d_ino; /* Always zero. */
unsigned short d_reclen; /* Always zero. */
unsigned short d_namlen; /* Length of name in d_name. */
char d_name[FILENAME_MAX]; /* File name. */
};

Simple Program to List a Directory:


#include <stdio.h>
#include <sys/types.h>
#include <dirent.h> // Directory definitions

int main (void)


{
DIR *dp; // Directory pointer
struct dirent *ep; // Directory entry pointer

dp = opendir ("./"); // Open current directory.


if (dp != NULL)
{
while (ep = readdir(dp)) // Read a directory entry, while it exists
{ puts (ep->d_name); }
(void) closedir (dp); // Close directory
}
else
perror ("Couldn't open the directory");

return 0;
}

C Programming Language 41 Halil Özmen


10.2. Date and Time System Calls

See: https://www.gnu.org/software/libc/manual/html_node/Date-and-Time.html
• Time Basics: Concepts and definitions.
• Elapsed Time: Data types to represent elapsed times
• Processor and CPU Time: Time a program has spent executing.
• Calendar Time: Manipulation of “real” dates and times.
• Setting an Alarm: Sending a signal after a specified time.
• Sleeping: Waiting for a period of time.
https://www.gnu.org/software/libc/manual/html_node/Calendar-Time.html
https://www.gnu.org/software/libc/manual/html_node/Formatting-Calendar-Time.html

#include <stdio.h>
#include <time.h>

#define SIZE 256

int main (void)


{
char buffer[SIZE];
time_t curtime;
struct tm *loctime;

/* Get the current time. */


curtime = time (NULL);

/* Convert it to local time representation. */


loctime = localtime (&curtime);

/* Print out the date and time in the standard format. */


printf("Date and time in the standard format: ");
fputs (asctime (loctime), stdout);

/* Print it out in a nice format. */


strftime (buffer, SIZE, "Today is %A, %d %B %Y.\n", loctime);
fputs (buffer, stdout);
strftime (buffer, SIZE, "Today is %a, %d/%m/%Y.\n", loctime);
fputs (buffer, stdout);
strftime (buffer, SIZE, "The time is %H:%M.\n", loctime);
fputs (buffer, stdout);
strftime (buffer, SIZE, "The time is %I:%M %p.\n", loctime);
fputs (buffer, stdout);
strftime (buffer, SIZE, "Date Time is %Y-%m-%d %I:%M:%S\n", loctime);
fputs (buffer, stdout);

return 0;
}

C Programming Language 42 Halil Özmen

You might also like