Arrays
a) Arrays: Data structures containing data items of the same type. Contains static data (size of array is fixed from
declaration all the way to implementation).
b) One Dimensional Array: Arrays having only one index or subscript. (Eg. Array[12])
c) Declaring a one dimensional array of size 10, and assign multiples of 2 using loops
#include <stdio.h>
void main(void){
int nums[10]; // array declaration, with 10 elements
int i; // counter variable used for loop
// assign multiples of 2 to array
for (i=0; i<10; i++){
nums[i] = (i+1) * 2; // add one to i, otherwise 0 will be the first element and 0 is not a multiple of 2
}
// print all elements in array
for (i=0; i<10; i++){
printf("nums[%d] : %d \n", i, nums[i]);
}
// wait till user press return key before closing window
getchar();
}
#include <stdio.h>
void main(void){
// 5 elements integer array initialized with values
int nums[5] = {11, 22, 33, 44, 55};
// counter variable used for loop
int i;
// print all elements in array
for (i=0; i<5; i++){
printf("nums[%d] : %d \n", i, nums[i]);
}
// wait till user press return key before closing window
getchar();
}
#include <stdio.h>
void main(void){
// 5 elements integer array initialized with values
int nums[10] = {12, 21, 13, 31, 14, 41, 15, 51, 16, 61};
// counter variable used for loop
int i;
// variable to store sum, initialized to zero
int sum=0;
// Calculate sum of all elements
for (i=0; i<10; i++){
sum = sum + nums[i];
}
// print out sum
printf("Sum of all elements in nums[] = %d", sum);
// wait till user press return key before closing window
getchar();
}
www.oumstudents.tk
f) Find the total mark, average mark, and the maximum mark of the following
#include <stdio.h>
void main(void){
// array with all the marks
int marks[5] = {10, 2, 33, 14, 17};
g) TUTORIAL1: Write a C program to store the below marks in an integer array. And perform the following tasks.
#include <stdio.h>
// initialize function prototypes
int getMaxMarks(int[], int);
int getMinSubject(int[], int);
void main(void){
// array with all the marks
int marks[9] = {12, 21, 33, 10, 55, 34, 11, 9, 3};
int subjects[9] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'};
// variables used in the program
int sum = 0; // to store sum
double avg = 0; // to store average
int minSubjectIndex; // to store min subject's index
char minSubject; // to store min subject
www.oumstudents.tk
int i;
// use loop to display all elements in array
for (i=0; i<9; i++){
printf("marks[%d] = %d\n", i, marks[i]);
}
printf("\n\n");
www.oumstudents.tk
h) Write a C program to perform the following array operations using the data below:
• Array 1: {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}
• Array 2: {100, 90, 80, 70, 60, 50, 40, 30, 20, 10}
• Array 3: {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
i. Create the Array 1, and assign the values while declaring the array.
ii. Create the Array 2 by copying the values in Array 1 in reverse order.
iii. Create the Array 3 by using the values in Array 2. (Hint: divide each array element in Array 2 by 10 before
assigning to Array 3).
#include <stdio.h>
void main(void){
// array declarations
int array1[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int array2[10], array3[10];
int i;
// print array2
for (i=0; i<10; i++){
printf("array2[%d] = %d\n", i, array2[i]);
}
printf("\n\n");
// print array3
for (i=0; i<10; i++){
printf("array3[%d] = %d\n", i, array3[i]);
}
i) Two Dimensional Array: Can be regarded as two dimensional matrix that has rows and columns. (Eg. In
Array[x][y], row is x, column is y)
j) Find the Total, Average, Worst, and Best Student from the following marks. Also find the class average using all
the totals.
www.oumstudents.tk
#include <stdio.h>
void main(void){
www.oumstudents.tk
// print marks table
printf("\n\nStudents\tSub1\tSub2\tSub3\tSub4\tSub5\tTotal\tAvg");
printf("\n========\t====\t====\t====\t====\t====\t=====\t===");
for (row = 0; row<6; row++){
printf("\n%c\t", students[row]);
for (col = 0; col<7; col++){
printf("\t%d", marks[row][col]);
}
}
printf("\n\nClass Average = %d", classAvg);
printf("\nBest Student = %c", bestStudent);
printf("\nWorstStudent = %c", worstStudent);
b) String: Character arrays that end with a NULL (‘\0’)character. (bounded in double quotations “ ”)
d) Input and Output Functions for Characters and Strings in stdlib.h library:
i. int getchar(): Inputs the following character from the input device and return the character as a value
ii. int putchar (int c): Prints the character to the output device
iii. char *gets (char str): Inputs the string from the standard input device and stores in str until ‘\n’ or <eof> is
found. NULL character is added to the end of the string.
iv. int puts (char *str): Prints the str string to the output device
v. int fflush (FILE *file): Empties the file buffer. (Eg. We use fflush(stdin); where stdin means the standard
input device, aka. keyboard)
f) String Array: Two dimensional character array where each array line is a single string. (Eg. char day[7][10] =
{“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”} )
www.oumstudents.tk
g) Strings Tutorial
#include <stdio.h>
#include <ctype.h>
// initializing function prototypes
int getLength(char[]);
int getUCaseCount(char[]);
void inverseCase(char[]);
void main(void){
// create the string
char name[] = "Ahmed Ibrahim";
return i;
}
return count;
}
i++;
}
}
www.oumstudents.tk
3. Structures
a) Structures: Combination of bits of data from different sources and types.
b) Structure Array: Represents a group of data from the same type of structure. (Eg. struct account customer[10])
c) Structure Tutorial: Create another user account structure to store the following data.
#include <stdio.h>
#include <string.h>
// Function prototypes
void printdate(struct long_date);
void printaccount(struct user_account);
struct long_date inputdate(void);
struct user_account inputaccount(void);
void main(void) {
www.oumstudents.tk
// Function to print the user account information
// Accepts a copy of a user_account struct as the parameter
void printaccount(struct user_account myaccount) {
printf("Print User Account Details\n");
printf("--------------------------\n");
printf("Name:\t\t%s\nAddress:\t%s\nDOB:\t\t%d-%s-%d, %s\n",
myaccount.name,
myaccount.address,
myaccount.DOB.day,
myaccount.DOB.month,
myaccount.DOB.year,
myaccount.DOB.wday);
}
printf("Day: ");
scanf("%d", &mydate.day);
fflush(stdin);
printf("Month: ");
gets(mydate.month);
fflush(stdin);
printf("Year: ");
scanf("%d", &mydate.year);
fflush(stdin);
return mydate;
}
puts("Name: ");
gets(myaccount.name);
puts("Address: ");
gets(myaccount.address);
puts("DOB:-");
myaccount.DOB = inputdate();
return myaccount;
}
www.oumstudents.tk
4. Pointers
a) Pointer: A variable that contains an address value referring to the memory location of a variable or an array
element. (* (star) is the Reference Operator while & (ampersand) is the Address Operator)
b) Array Name: A constant pointer to the first element of an array. (Eg. xarray points to &xarray[0]). It cannot
change its value or point to another location other than the first element of the array.
c) Reference Passing: Method of passing the address to a local pointer variable that points to the actual location
of the data item, where changes can be made to the actual data item.
ii. viod free (void *prt): Release the memory that has been reserved by malloc().
5. Linked Lists
a) Lists: Group of data items that is sequentially forming a list, where its data items are not linked to one another
(Implemented using arrays).
c) Basic Operations:
d) Assignment Question 2A: Using linked lists to insert a node into the linked list so that it remains sorted
// include libraries
#include <stdio.h>
#include <conio.h>
// type defining and creating the linked list structure
typedef struct linkedList {
int data;
struct linkedList *next;
} NODE;
www.oumstudents.tk
// globally initialising the linked list Slist
NODE *Slist;
// initialising function prototypes
void viewLinkLst(NODE *);
NODE *addSort(NODE *,NODE *);
NODE P = {12,NULL}; //The Node P that is to be inserted into the linked list
// include libraries
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
//main function
void main(void)
{
// setting up list 1
NODE list01_2 = {'B',NULL};
NODE list01_1 = {'A',&list01_2};
list_1=&list01_1;
// setting up list 2
NODE list02_2 = {'2',NULL};
NODE list02_1 = {'1',&list02_2};
list_2=&list02_1;
printf("\n\n\tList 2:\t");
viewLinkLst(list_2);
getch();
}
return LIST;
}
6. Stacks
a) Lists: A heap of arranged data items that can be accessed from one end only. (Limited version of an Array, LIFO:
Last-In-First-Out) (Implemented using both arrays AND pointers)
7. Queues
a) Queues: an ordered list where elements can be added at only one point (which is called the back or end) and an
item can only be removed from the other end (which is called the front or head).
www.oumstudents.tk
8. Sorting
a) Simple selection sorting: Starting from the left, interchange with the smallest digit and do this with each
line.(so that the smallest number will be at the left side after every step)
20 11 4 8
4 11 20 8
4 8 20 11
4 8 11 20
b) Linear Insertion Sorting: there will be a sorted list(starting from the left) and an unsorted list. In every step,
number of digit in sorted list will be incremented with one.
20 11 4 8
11 20 4 8
4 11 20 8
4 8 11 20
Highlighted is the sorted list where whole list is pushed to right as the smallest digit from the unsorted list is
taken to the sorted list.
c) Quick sorting: Compare pivot to smallest from right and interchange, then in the next line compare pivot to
biggest from left and interchange/ make sub-list if pivot is balancing
20 11 4 8 27 25
8 11 4 20 27 25
8 11 4 27 25
4 11 8 25 27
4 8 11
4 8 11 20 25 27
d) Bubble sorting: This sorting performs adjacent element exchanges until all elements are arranged according to
the requirements
Round 1
20 11 4 8
11 20 4 8
11 4 20 8
11 4 8 20
Round 2
11 4 8 20
4 11 8 20
4 8 11 20
Round 3
4 8 11 20
4 8 11 20
www.oumstudents.tk
9. Searching
a) Sequential Search: This technique is applied to records that are arranged using arrays or linked lists. Searching
begins with the first record and this is done sequentially until the data is found.
Say A[1], A[2], ... , A[n] are arrays that consists of n keys Ki; (1 <= i <= n) that are different.
The K key is the argument that is searched (key search). The following algorithm
will find the smallest integer i (array index) where Ki is its key.
b) Binary Search: In binary search, what needs to be found is the position for a K search key in a table. The search
key is compared to a key in the middle of the table.
If not, the search process continues for the elements below the
middle key in the table.
Number of data = 10
Initial value = 0 (array index value starts from 0)
Final value = 9
Round 1 We find the middle value first. Round 2 The result of round 1 found that the focus location
Middle value = (initial + final)/2 for the search is on the right of the middle key, which are the
= (0 + 9)/2 locations that goes toward the end. Therefore, we need to
change the initial value to the location to the right of the middle
= 9/2 value, which is the middle value plus 1.
=4
Change initial value, which is initial = middle + 1
Test the middle key with the search key. =4+1
Middle key = k(4) = 20 // 20 < 39 =5
We calculate for the middle value again.
Middle value = (initial + end) / 2
= (5 + 9)/2
=14 / 2
Since the search key value (39) is bigger than the middle key (20), =7
the focus of the search will only be on the right of the middle key, Test middle key with search key:
which is location k(5) until k(9). Middle key = k(7) = 40 //40 < 39
In this round, we found that the value of the search key (39) is
less that the middle key (40), therefore, the focus of the search
will only by to the left of that middle key, which is location k(5)
and k(6). You need to give your full attention to follow this
algorithm. Let us continue to the next round
www.oumstudents.tk
Round 3 The result of the second round has revealed that Round 4 From the result of round 3, the search location
the focus of the search is to the left of the middle key, which is the focus is now on the right of the middle key, which are the
location leading towards the start value. Therefore, we need to locations leading toward the end. Here, we need to change the
change the end value of the location to the left of the middle initial value of the location to the left of the middle key value,
value, which is middle value minus one. which is the middle minus one.
Change end value, End = middle - 1 Change final value, initial = middle + 1
=7-1 =6+1
=6 =7
We find the middle value again. We calculate for the middle value again.
Middle value = (initial + end)/2 Middle value = (initial + end) / 2
= (5 +6)/2 = (7 + 6)/2
= 11/2 =13 / 2
=5 =6
Test the middle key with the search key. Test the middle key with the search key.
Middle key = k(5) = 25 Middle key = k(6) = 39
In this round we found that the search key value (39) is bigger than Thus, our search is successful.
the middle key (25), so the focus of the search is only to the right of
the middle key, which is location k(5). Therefore, our search is
successful.
10. Trees
a) Trees: A structure that consists of nodes that are linked with directed pointers.
b) Binary Tree: A binary tree is a tree in which no node can have more than two subtrees. In other words, a node
can be zero, one or two subtrees.
c) Expression Trees:
Look at the following expression:
A/(B*C)+D
Add parentheses.
((A/(B*C))+D)
www.oumstudents.tk