IT104 Discrete Structures
IT104 Discrete Structures
IT104 Discrete Structures
COMPILATION OF TOPICS
Table of Contents
Topic
Page
1. Arrays
2. Statistical Array
3. Pointers
4. Functions
5. Relationship Between Pointers and Arrays
6. Passing Pointers to Functions
7. Pointers to Functions
8. Array of Functions
9. Enumeration
4
8
10
14
18
20
21
23
25
27
Introduction
This project aims to create a simplified description of the topics discussed in our IT104
2
Discrete Structures class. Using C programming, data structures and algorithms are particularly
tackled wherein logic and theory are needed in order to create programs. Topics such as Array,
Pointers, and Functions will be discussed. Arithmetical and logical operators such +, +=, ++,
&, ~ are frequently used to solve various equations.
For each topic, the theory and the application of theory will be presented. Under the
application of theory the following will be shown: 1) problem, 2) program code, and 3) sample
output.
Arrays
Array in C programming is a data structure that can store a fixed size sequential
3
collection of elements of the same type. An array is used to store a collection of data. Thus, it is
a collective name given to a group of similar quantities. These similar quantities could be the
number of students enrolled in a university, the grades of 100 students enrolled in a class, or
the ages of employees in a company.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
First Element
Last Element
age[0]
age[1]
age[2]
age[3]
Arrays and pointers have a special relationship because arrays use pointers to reference
memory locations.
Declaration of an Array
Arrays must be declared first before they can be used in a program. The standard array
declaration is as follows:
type arrayname[arraysize];
Type specifies the variable type of the element that is going to be stored in the array. The
following are the basic variable types in C Language:
Type
char
int
Description
Typically a single octet (one byte). This is
an integer type.
The most natural size of integer for the
machine.
float
double
void
Single-dimensional Array
The single-dimensional array in C is the simplest form of array that contains only one row for
storing data. It has a single set of square brackets ([]).
type arrayName[arraySize];
Multi-dimensional Array
The C language supports multi-dimensional arrays. The simplest data structure for organizing
tabular data is a two-dimensional array. C compilers treat a two-dimensional array as an array
of arrays. To declare a two-dimensional integer array size x,y you would write something as
follows:
type arrayName[x][y];
Where type can be any valid C data type and arrayName will be a valid C identifier. A twodimensional array can be think as a table which will have x number of rows and y number of
columns. A 2-dimensional array a, which contains three rows and four columns can be shown
as below:
Thus, every element in array a is identified by an element name of the form a[i][j], where
a is the name of the array, and i and j are the subscripts that uniquely identify each element in
a.
Example Problem
Problem
Forty Students were asked to rate the quality of the food in the student cafeteria on a scale of 1
to 10 (1 means awful and 10 means excellent). Place the 40 responses in an integer array and
summarize the results of the poll.
Code
#include <stdio.h>
#define RESPONSE_SIZE 40
#define FREQUENCY_SIZE 11
int main()
{
6
Output
Rating
Frequency
11
10
Statistical Arrays
7
Example Problem
Problem
Find maximum and minimum element in an array of 10 elements.
Code
#include<stdio.h>
int main()
{
int i;
int a[10] = { 10, 55, 9, 4, 234, 20, 30, 40, 22, 34 };
int max = a[0];
int min = a[0];
for (i = 0; i < 10; i++)
{
if (a[i] > max)
{
max = a[i];
}
else if (a[i] < min)
{
min = a[i];
}
}
printf ("Maximum element in an array: %d\n", max);
printf ("Minimum element in an array: %d\n", min);
return 0;
}
Output
Pointers
9
A pointer is a programming language object, whose value refers directly to (or "points
to") another value stored elsewhere in the computer memory using its address. A pointer
references a location in memory, and obtaining the value stored at that location is known as
dereferencing the pointer. A pointer is a simple, more concrete implementation of the more
abstract reference data type.
The basic syntax to define a pointer is as follows:
int *ptr;
This declares ptr as the identifier of an object of the following type:
location of 0x8130 then the value of ptr will be 0x8130 after the assignment. To dereference
the pointer, an asterisk is used again:
*ptr = 8;
This means take the contents of ptr (which is 0x8130), locate that address in memory and
set its value to 8. If a is later accessed again, its new value will be 8.
This example may be clearer if memory is examined directly. Assume that a is located at
address 0x8130 in memory and ptr at 0x8134; also assume this is a 32-bit machine such that
an int is 32-bits wide. The following is what would be in memory after the following code
snippet is executed:
int a = 5;
int *ptr = NULL;
Address Contents
0x8130
0x00000005
0x8134
0x00000000
(The NULL pointer shown here is 0x00000000.) By assigning the address of a to ptr:
ptr = &a;
yields the following memory values:
Address Contents
0x8130
0x00000005
0x8134
0x00008130
11
Address Contents
0x8130
0x00000008
0x8134
0x00008130
Clearly, accessing a will yield the value of 8 because the previous instruction modified the
contents of a by way of the pointer ptr.
In C, array indexing is formally defined in terms of pointer arithmetic; that is, the language
specification requires that array[i] be equivalent to *(array + i). Thus in C, arrays
can be thought of as pointers to consecutive areas of memory (with no gaps), and the syntax for
accessing arrays is identical for that which can be used to dereference pointers.
Example Problem
Problem
Add two numbers using pointers.
Code
#include <stdio.h>
int main()
{
int first, second, *p, *q, sum;
12
Output
Enter two integers to add
4
5
Sum of entered numbers = 9
13
Functions
A function is a group of statements that together perform a task. Every C program has
at least one function, which is main(), and all the most trivial programs can define additional
functions. You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division usually is so each function
performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters.
A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For
example, function strcat() to concatenate two strings, function memcpy() to copy one
memory location to another location and many more functions. A function is known with
various names like a method or a sub-routine or a procedure, etc.
The general form of a function definition in C programming language is as follows:
return_type function_name( parameter list )
{
body of the function
}
A function definition in C programming language consists of a function header and a function
body. Here are all the parts of a function:
Return Type: A function may return a value. The return_type is the data type of
the value the function returns. Some functions perform the desired operations without returning
a value. In this case, the return_type is the keyword void.
14
Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Function Declarations
A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.
A function declaration has the following parts:
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration:
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so
following is also valid declaration:
int max(int, int);
Function declaration is required when you define a function in one source file and you call that
function in another file. In such case you should declare the function at the top of the file
calling the function.
Calling a Function
15
While creating a C function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task.
When a program calls a function, program control is transferred to the called function. A called
function performs defined task and when its return statement is executed or when its functionending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name,
and if function returns a value, then you can store returned value.
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function. The formal
parameters behave like other local variables inside the function and are created upon entry into
the function and destroyed upon exit. While calling a function, there are two ways that
arguments can be passed to a function:
Call Type
Call by value
Description
This method copies the actual value of an
argument into the formal parameter of the
function. In this case, changes made to the
parameter inside the function have no effect
on the argument.
Call by reference
By default, C uses call by value to pass arguments. In general, this means that code within a
function cannot alter the arguments used to call the function and above mentioned example
while calling max() function used the same method.
16
Example Problem
Problem
A program to reverse a sentence input by the user.
Code
#include <stdio.h>
void Reverse();
int main()
{
printf("Enter a sentence: ");
Reverse();
return 0;
}
void Reverse()
{
char c;
scanf("%c",&c);
if( c != '\n')
{
Reverse();
printf("%c",c);
}
}
Output
Enter a sentence: Hello there
ereht elloH
17
InarraysofCprogramming,nameofthearrayalwayspointstothefirstelementofanarray.
Here,addressoffirstelementofanarrayis&arr[0].Also,arrrepresentstheaddressofthe
pointerwhereitispointing.Hence,&arr[0] is equivalent to arr.
Also,valueinsidetheaddress&arr[0]andaddressarrareequal.Valueinaddress
&arr[0]isarr[0]andvalueinaddress arris*arr.Hence,arr[0] is equivalent to
*arr.
Similarly,
&a[1] is equivalent to (a+1)
*(a+1).
&a[2] is equivalent to (a+2)
*(a+2).
&a[3] is equivalent to (a+1)
*(a+3).
.
.
&a[i] is equivalent to (a+i)
*(a+i).
InC,youcandeclareanarrayandcanusepointertoalterthedataofanarray.
ExampleProblem
Problem
A program to find the sum of six numbers input by the user with arrays and pointers.
Code
#include <stdio.h>
int main(){
int i,class[6],sum=0;
printf("Enter 6 numbers:\n");
for(i=0;i<6;++i){
scanf("%d",(class+i)); // (class+i) is equivalent to
&class[i]
sum += *(class+i); // *(class+i) is equivalent to
class[i]
}
printf("Sum=%d",sum);
return 0;
}
Output
Enter 6 numbers:
1
2
3
4
5
19
6
Sum = 21
Example Problem
Problem
A program to pass an unsigned long pointer to a function and change the value inside the
function which reflects back in the calling function.
Code
#include <stdio.h>
#include <time.h>
void getSeconds(unsigned long *par);
int main ()
{
unsigned long sec;
getSeconds( &sec );
/* print the actual value */
printf("Number of seconds: %ld\n", sec );
return 0;
}
void getSeconds(unsigned long *par)
{
/* get the current number of seconds */
*par = time( NULL );
return;
}
20
Output
Number of seconds: 1412869533
Pointers to Functions
Functions in C are actually just pointers to a spot in the program where some code
exists. Just like you've been creating pointers to structs, strings, and arrays, you can point a
pointer at a function too. The main use for this is to pass "callbacks" to other functions, or to
simulate classes and objects. In this exercise we'll do some callbacks, and in the next one we'll
make a simple object system.
The format of a function pointer goes like this:
int (*POINTER_NAME)(int a, int b)
A way to remember how to write one is to do this:
tester(2,
3),
sorted_order(2, 3));
This will work even if the function pointer returns a pointer to something:
The solution to this is to use typedef which is a C keyword for making new names for other
more complex types. The only thing you need to do is put typedef before the same function
pointer syntax, and then after that you can use the name like it's a type.
Example Problem
Problem
A program that defines a function func that takes two integers as inputs and returns an
integer.
Code
#include<stdio.h>
int func (int a, int b)
{
printf("\n a = %d\n",a);
printf("\n b = %d\n",b);
return 0;
}
int main(void)
{
int(*fptr)(int,int); // Function pointer
fptr = func; // Assign address to function pointer
func(2,3);
fptr(2,3);
return 0;
}
Output
a=2
b=3
a=2
22
b=3
Array of Functions
By far the most important use of pointers to functions is to have arrays of functions. We
can have arrays of pointers and pointers can be made to point at functions. So combining both
we can have array of pointers to functions put differently, we can have array of functions.
If you want to pass a single-dimension array as an argument in a function, you would have to
declare function formal parameter in one of following three ways and all three declaration
methods produce similar results because each tells the compiler that an integer pointer is going
to be received. Similar way you can pass multi-dimensional array as formal parameters.
Example Problem
Problem
A program that asks the user to input two numbers and then choose if he/she wants to add,
subtract, multiply, or divide.
Code
#include <stdio.h>
int
int
int
int
=
=
=
=
Output
Enter two numbers: 1
2
0: Add, 1: Subtract, 2: Multiply, 3: Divide
Enter number of operation: 0
24
Enumeration
Anenumeration is a userdefined data type consists of integral constants andeach
integralconstantisgivenaname.Keywordenumisusedtodefinedenumerateddatatype.
enum type_name{ value1, value2,...,valueN };
Here, type_name is the name of enumerated data type or tag. And value1,
value2,....,valueN are values of type type_name.
By default, value1 will be equal to 0, value2 will be 1 and so on but the programmer can
change the default value as below:
enum suit{
club=0;
diamonds=10;
hearts=20;
spades=3;
};
DeclarationofEnumeratedVariable
Abovecodedefinesthetypeofthedatabut,noanyvariableiscreated.Variableoftypeenum
canbecreatedas:
enum boolean{
false;
true;
};
enum boolean check;
25
Example Problem
Problem
A program to identify the current day of the week (wednesday) using enumeration.
Code
#include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday, thursday,
friday, saturday};
int main(){
enum week today;
today=wednesday;
printf("%dth day",today+1);
return 0;
}
Output
4th day
26
Classification of Characters
int islower (char c)
Returns true if c is a lower-case letter.
int isupper (char c)
Returns true if c is an upper-case letter.
int isalpha (char c)
Returns true if c is an alphabetic character (a letter). If islower or isupper is true of a character,
then isalpha is also true.
In some locales, there may be additional characters for which isalpha is true--letters which
are neither upper case nor lower case. But in the standard "C" locale, there are no such
additional characters.
int isdigit (char c)
Returns true if c is a decimal digit (`0' through `9').
int isalnum (char c)
Returns true if c is an alphanumeric character (a letter or number); in other words, if either
27
Returns true if c is a graphic character; that is, a character that has a glyph associated with it.
The whitespace characters are not considered graphic
int isprint (char c)
Returns true if c is a printing character. Printing characters include all the graphic characters,
plus the space (` ') character.
int iscntrl (char c)
Returns true if c is a control character (that is, a character that is not a printing character).
int isascii (char c)
Returns true if c is a 7-bit unsigned char value that fits into the US/UK ASCII character set.
This function is a BSD extension and is also an SVID extension.
Case Conversion
int tolower (char c)
If c is an upper-case letter, tolower returns the corresponding lower-case letter. If c is not an
upper-case letter, c is returned unchanged.
This is identical to tolower, and is provided for compatibility with the SVID.
Example Problem
Problem
A program to determine if the character is an alphabet or not.
Code
#include <stdio.h>
#include <ctype.h>
int main()
{
int var1
int var2
int var3
int var4
=
=
=
=
'd';
'2';
'\t';
' ';
if( isalpha(var1)
{
printf("var1 =
}
else
{
printf("var1 =
}
if( isalpha(var2)
{
printf("var2 =
}
else
{
printf("var2 =
}
if( isalpha(var3)
{
printf("var3 =
)
|%c| is an alphabet\n", var1 );
}
else
{
printf("var3 =
}
if( isalpha(var4)
{
printf("var4 =
}
else
{
printf("var4 =
}
return 0;
}
Output
var1 = |d| is an alphabet
var2 = |2| is not an alphabet
var3 = | | is not an alphabet
var4 = | | is not an alphabet
31