Intro
Let's say we have 10 students and we need to store their grades are integers. We could define 10 variables say:
grade_student1, grade_student2, grade_student3
We could store our values in these variables. However it is a bit messy to create separate variables to hold 10 similar values that may be used together.
As an example to find the average of the grades we have to do:
int average = ( grade1 + grade2 + grade3 + grade4 ... + grade10 ) / 10
A cleaner option is to use the data structures arrays. We can declare an array as:
int studentGrades[10] ;
This states that "studentGrades" can hold 10 integer values. How can we store values in the array ? We can use the array subscript notation. Ex:
studentGrades[0] = 50 ;
studentGrades[1] = 66 ;
studentGrades[9] = 86 ;
Now the average can be coded as :
int average = 0 ;
int total = 0 ;
for( int i1=0 ; i1< 10 ; i1++ )
total += studentGrades[i1]
average = total / 10 ;
File: arr1.c
#include <stdio.h>
int main()
{
int grade_student1= 10 , grade_student2= 20 , grade_student3= 30 , grade_student4 = 40 , grade_student5= 50 ,
grade_student6= 60 , grade_student7= 70 , grade_student8=80, grade_student9=90 , grade_student10 =100 ;
double total = 0 ;
total = grade_student1 +
grade_student2 + grade_student3 + grade_student4 + grade_student5 +
grade_student6 + grade_student7 + grade_student8 + grade_student9 + grade_student10 ;
printf( "Average is : %.1f\n" , total / 10.0 ) ;
int studentGrades[] = { 10 , 20 , 30 , 40 , 50 , 60 , 70, 80 , 90, 100 } ;
total = 0 ;
for( int i1=0 ; i1<10 ; i1++ )
{
total = total + studentGrades[i1] ;
}
printf( "Average is : %.1f\n" , total / 10.0 ) ;
}
Using functions.
We can see how the array fits what we want to do in a much cleaner fashion. This also becomes important when we write functions and pass arrays as arguments. Let us compare the programs
File: arr2.c
#include <stdio.h>
double average( int grade_student1 ,
int grade_student2 , int grade_student3 , int grade_student4 , int grade_student5 ,
int grade_student6 , int grade_student7 , int grade_student8 , int grade_student9 , int grade_student10 )
{
double total = 0 ;
total = grade_student1 +
grade_student2 + grade_student3 + grade_student4 + grade_student5 +
grade_student6 + grade_student7 + grade_student8 + grade_student9 + grade_student10 ;
return ( total / 10.0 ) ;
}
double averageArray( int array1[] )
{
double total = 0 ;
for( int i1=0 ; i1<10 ; i1++ )
{
total = total + array1[i1] ;
}
return ( total / 10.0 ) ;
}
int main()
{
int grade_student1= 10 , grade_student2= 20 , grade_student3= 30 , grade_student4 = 40 , grade_student5= 50 ,
grade_student6= 60 , grade_student7= 70 , grade_student8=80, grade_student9=90 , grade_student10 =100 ;
printf( "Average is : %.2f\n" , average( grade_student1 ,
grade_student2 , grade_student3 , grade_student4 , grade_student5 ,
grade_student6 , grade_student7 , grade_student8 , grade_student9 , grade_student10 ) ) ;
int studentGrades[] = { 10 , 20 , 30 , 40 , 50 , 60 , 70, 80 , 90, 100 } ;
printf( "Average is : %.2f\n" , averageArray( studentGrades ) ) ;
}
In the above we declared the array as:
int studentGrades[] = { 10 , 20 , 30 , 40 , 50 , 60 , 70, 80 , 90, 100 } ;
We are declaring the array as "studentGrades[]" and then assigning values at the same time. The array can be declared as :
studentGrades[]
or with a size between the square brackets:
studentGrades[10]
In our case we did not use the "[10]" notation because we are assigning the values and the C compiler is able to figure out
what size it needs to create the array as. Also notice how we run the "for" loop.
for( int i1=0 ; i1<10 ; i1++ )
{
total = total + studentGrades[i1] ;
}
We can access the elements in the array using the notation [i1] . Notice the i1 starts with 0. In C indexing starts with 0 .The "[0]" gives us the
first element of the array. The array can be thought of a consecutive block of 10 integers in this case. Let us look at a program illustrating a different declaration and assignment style.
File: "decl1.c"
#include <stdio.h>
int global1[5] ;
int main()
{
int arr1[5] ;
arr1[0] = 10 ;
arr1[1] = 20 ;
global1[0] = 10 ;
global1[1] = 20 ;
for( int i1 = 0 ; i1<5 ; i1++ )
printf( "arr1[i1]: %d\n" , arr1[i1] ) ;
for( int i1 = 0 ; i1<5 ; i1++ )
printf( "global1[i1]: %d\n" , global1[i1] ) ;
}
Output:
arr1[i1]: 10
arr1[i1]: 20
arr1[i1]: 0
arr1[i1]: 0
arr1[i1]: 0
global1[i1]: 10
global1[i1]: 20
global1[i1]: 0
global1[i1]: 0
global1[i1]: 0
As a general rule it is good practice to initialize something explicitly rather than the relying on the system default values. It makes the code more readable. The intent is not just to write something that works but write in a clear understandable manner.
A small note here. Some of the C standard versions do not allow for variable length arrays as the stack expects the size to be declared at compile time.
File: "decl3.c"
#include<stdio.h>
const int size = 5;
int main()
{
int arr1[size] = {1, 2, 3, 4, 5};
printf("%d", arr1[0]);
return 0;
}
Output:
decl3.c: In function ‘main’:
decl3.c:7:5: error: variable-sized object may not be initialized
7 | int arr1[size] = {1, 2, 3, 4, 5};
| ^~~
We can write another example with a user inputting the grades in the array and then we print the array out.
File: "grade1.c"
#include <stdio.h>
int main()
{
const int NUM = 5; // Number of students
float grades[NUM];
int count;
// Input the grades.
for (count = 0; count < NUM ; count++)
{
printf( "Enter the grade for student %d:" , (count+1) ) ;
scanf( "%f" , &grades[count] ) ;
}
// Display the contents of the array.
printf( "The grades you entered are:" ) ;
for (count = 0; count < NUM ; count++)
printf( " %.1f" , grades[count] ) ;
printf( "\n" ) ;
return 0;
}
Output:
Enter the grade for student 1:1.1
Enter the grade for student 2:1.2
Enter the grade for student 3:1.3
Enter the grade for student 4:1.4
Enter the grade for student 5:1.5
The grades you entered are: 1.1 1.2 1.3 1.4 1.5
We are asking the user for input of the grades and run a loop to enter them into the array. The index in a C++ array starts at 0 . In the example above we are using "count" as a variable to hold the value. This could also be an expression such as "count+1" .
An array variable holds the address of where the block is stored in RAM . It can be pictured as:
In the above diagram th array variable "Array1" holds the address of where the block for the array is created in the RAM. Once the variable gets assigned an address the array's variable value cannot be changed. C only stores the bare minimum information for an array. It stores the address where the memory block is created and nothing else. The block that is used for storage is determined based on the number of elements and the type. If the array is of size 10 and the size of int on this machine is 4 bytes then 40 bytes will be allocated. The array variable cannot be reassigned once it is defined.
Programmers used to arrays from other languages such as Java or C# will find this minimalist approach very different If we have an array in C then there is no way to get the size( length ) of the array .
Ex: "size1.c"
#include <stdio.h>
void function1( int arr[] )
{
printf( "Size of arr:%d\n" , sizeof( arr ) ) ;
}
int main()
{
int arr1[5] ;
arr1[0] = 10 ;
arr1[1] = 20 ;
function1( arr1 ) ;
}
Output:
[amittal@hills Site]$ ./a.exe
Size of arr:8
The size of the array is actually 5 and we use the C++ "sizeof" function to try to print the length but we get the value of 8. Where is this 8 coming from ? It is actually the size of the address that "arr" has . This was compiled on a 64 bit machine and the addresses are 64 bits . In a C style string we have a similar storage scheme but all the string are terminated by the null character. There is no such character ( and there couldn't be because the array can also contain the character 0 ) with arrays. That is the reason we see many functions that take an array argument also have the "size" as an additional parameter so that the function knows the size of the array.
There is no bounds checking in arrays in C . The following code will compile:
Ex:
#include <stdio.h>
int main()
{
int array1[] = { 1, 2 } ;
int array2[] = {2, 4} ;
printf( "%d\n" , array1[100] ) ;
return(0) ;
}
Output:
[amittal@hills Chapter7]$ ./a.exe
0
The array1 is of sizee 2 and we are accessing 100 th element. What happens at run time ? We don't know where that position will end up in the RAM. If it falls in what the operating system considers to be an invalid memory location then we will get a "segment" error and if the address falls in the RAM block assigned for the program then it's possible we will not get a crash but rather some garbage value. Running the above program produces a garbage integer value. Now let's test the case of accessing the array1 at position 100000 .
File: "size3.c"
#include <stdio.h>
int main()
{
int array1[] = { 1, 2 } ;
int array2[] = {2, 4} ;
printf( "%d\n" , array1[100000] ) ;
return(0) ;
}
Output:
Segmentation fault (core dumped)
In the above case the address pointed to an invalid location and the CPU was able to catch that. The absence of bounds checking does have a purpose in C. The focus of C is on efficiency and speed and it stores the minimum information needed for that. It is up to the programmer to make sure the indices do not fall out of range. This is vastly different from other languages like Java that will throw an exception at run time.
Ex:
#include <stdio.h>
int global[5] ;
int[] function1()
{
return global ;
}
int main()
{
int array1[] = { 1, 2 } ;
int array2[] = {2, 4} ;
array1 = array2 ;
int array3[] ;
return(0) ;
}
Output:
arr3.c:6:4: error: expected identifier or ‘(’ before ‘[’ token
6 | int[] function1()
| ^
arr3.c: In function ‘main’:
arr3.c:19:10: error: assignment to expression with array type
19 | array1 = array2 ;
| ^
arr3.c:20:7: error: array size missing in ‘array3’
20 | int array3[] ;
| ^~~~~~
Segmentation fault (core dumped)
The above example has couple of problems. A function cannot return an array because that array value will have to be assigned to an array variable and that means changing the value of the existing array. Also the statement:
array1 = array2
is invalid because "array1" cannot be changed. The statement
int array3[] ;
is not valid because the size of the array is not specified.
Initializing an array
Ex: "arr4.c"
#include <stdio.h>
int main()
{
int array1[4] = { 6, 1, 2 , 4} ;
for( int i1=0 ; i1 < 4 ; i1++ )
printf( "%d " , array1[i1] ) ;
printf( "\n" ) ;
return(0) ;
}
Output:
[amittal@hills Chapter7]$ ./a.exe
6 1 2 4
We declared an array "array1" of size 4 and initialized it with 4 elements. We could have chosen not to specify the size of the array. The C compiler will figure out what the size is.
Ex: "arr5.c"
#include <stdio.h>
int main()
{
int array1[] = { 6, 1, 2 , 4} ;
for( int i1=0 ; i1 < 4 ; i1++ )
printf( "%d " , array1[i1] ) ;
printf( "\n" ) ;
return(0) ;
}
We can specify the size and choose to only initialize some of the elements.
Ex:
#include <stdio.h>
int main()
{
int array1[4] = { 6, 1 } ;
for( int i1=0 ; i1 < 4 ; i1++ )
printf( "%d " , array1[i1] ) ;
printf( "\n" ) ;
return(0) ;
}
Output:
[amittal@hills Chapter7]$ ./a.exe
6 1 0 0
We cannot choose not to initialize an element in the middle. What that means is we cannot do :
int array1[4] = { 6, , 1}
The end result that we are trying to obtain is:
{ 6, 0 , 1, 0 }
We can only initialize elements to the left and not leave out the middle element to assume default values.
In the first loop we we increment x1 but that does not change anything . All we have is a variable that is assigned a value from the array. The second range loop has a variable that is declared as a reference and this does end up changing the value of the element in the array. It increments the original array to 11,21,32,41,51 and that's what the last for range loop prints out.
A two dimension array can be defined as:
int array1[2][3] = { {1,2,3} , { 4,5,6} } ;
This states that the array consists of 2 rows and 3 columns. Let us look at the following code:
File: "arr7.c"
#include <stdio.h>
void function2( int arr1[] )
{
}
void function1( int arr1[][3] )
{
printf( "%d\n" , arr1[1][0] ) ;
}
int main()
{
int array1[2][3] = { {1, 2,3} , {4, 5,6} } ;
int array2[3] = { 10,20,30 } ;
function1( array1 ) ;
function2( array2 ) ;
return(0) ;
}
Output:
4
The above code defines a 2 dimensional array with 2 rows and 3 columns. When an array is stored in RAM only the address of the array is known and that is stored in the array variable. Information such as number of rows and columns are not kept. In RAM the array looks like:
RAM
0
array1 1 5
2
3
4
5 1
6 2
7 3
8 4
9 5
10 6
The above is a simplified diagram. Actual memory address numbers will of course be different. The 2 dimensional array is stored in consecutive 6 locations.This creates a problem if we try to pass it to a function.
void function1( int arr1[][] )
{
cout << arr1[1][0] ;
}
in order to print the value of "arr1[1][0]" the "function1" has to know the number of columns in order to print the first element of the second row. We can accomplish that by specifying the number of columns in the declaration.
void function1( int arr1[][3] )
{
cout << arr1[1][0] ;
}
Now the compiler know that there are 3 columns so it knows to skip 3 elements in order to get to the first element of the second row.
Exercise 1. What is the output of the following code:
#include <stdio.h>
int main()
{
int arr1[] = { 1 , 2, 3, 4 , 5 } ;
int arr2[5] = { 1 , 2 } ;
for( int i1=0 ; i1 < 5 ; i1++ )
{
arr2[i1] = arr1[i1] + arr2[i1] ;
arr2[i1] += arr1[i1] ;
printf( "%d " , arr2[i1] ) ;
} //for
printf( "\n" ) ;
return(0) ;
}
A C style string is an array of characters terminated by the null character . The null character is the decimal 0 in the ascii chart.
File: "str1.c"
#include <stdio.h>
#include <string.h>
int main()
{
char firstName[] = "Jack" ;
char lastName[] = "Dempsey" ;
char fruit[] = {'A' , 'p' , 'p', 'l' , 'e' } ;
char buffer1[256] ;
printf( "Name: %s %s\n", firstName, lastName ) ;
printf( "Fruit: %\n" , fruit ) ;
//printing the length
printf ( "Length of firstName: %d\n" , strlen( firstName ) ) ;
return(0) ;
}
Output:
Name: Jack Dempsey
Fruit: AppleDempsey
Length of firstName: 4
How can we correct the output of the line with "Fruit" ? We need to place the null character at the end otherwise "printf" doesn't know when to stop.
File: "str2.c"
#include <stdio.h>
#include <string.h>
int main()
{
char firstName[] = "Jack" ;
char lastName[] = "Dempsey" ;
char fruit[] = {'A' , 'p' , 'p', 'l' , 'e' , 0 } ;
char buffer1[256] ;
printf( "Name: %s %s\n", firstName, lastName ) ;
printf( "Fruit: %s\n" , fruit ) ;
//printing the length
printf ( "Length of firstName: %d\n" , strlen( firstName ) ) ;
return(0) ;
}
We also have many functions in the standard library such as "strlen" to manipulate strings. We can include the header file "<string.h>" to use these functions. We can grab individual characters from the array and manipulate the array.
File: "str3.c"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char firstName[] = "Jack" ;
int i1 = 0 ;
while( firstName[i1] != 0 )
{
firstName[i1] = toupper( firstName[i1] ) ;
i1++ ;
}
printf( "Name: %s\n", firstName ) ;
return(0) ;
}
Output:
./a.exe
Name: JACK
We can use "scanf" function to read a line from the console.
File: "str4.c"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char buffer1[256] ;
printf( "Enter a string:" ) ;
scanf( "%s" , buffer1 ) ;
printf( "Buffer1: %s\n", buffer1 ) ;
printf( "Enter a string:" ) ;
scanf( "%s" , buffer1 ) ;
printf( "Buffer1: %s\n", buffer1 ) ;
return(0) ;
}
Output:
Enter a string:t1
Buffer1: t1
Enter a string:t2
Buffer1: t2
The function "sscanf" is like "scanf" but reads from a string instead of a console. The string is specified in the first parameter. Similarly the function "sprintf" prints to a string instead of the console. These functions are incredibly useful as the following example shows.
File: "str5.c"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char buffer1[256] ;
char buffer2[256] ;
int x1 = 100 ;
int x2 = 0 ;
//Here an integer is converted to a string
sprintf( buffer1 , "%d", x1 ) ;
printf( "Buffer1: %s\n", buffer1 ) ;
//convert from string to integer
sscanf( buffer1, "%d" , &x2 ) ;
printf( "x2 = %d\n" , x2 ) ;
//we can read more than one integer value
sprintf( buffer2 , "11 12" ) ;
sscanf( buffer2, "%d %d" , &x1 , &x2 ) ;
printf( "x1 = %d x2 = %d\n" , x1, x2 ) ;
return(0) ;
}
Output:
Buffer1: 100
x2 = 100
x1 = 11 x2 = 12
File: "str6.c"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char buffer1[256] = "Jack" ;
char buffer2[256] ;
int x1 = 100 ;
int x2 = 0 ;
//Copies the second arguent to first
strcpy( buffer2 , " Johnson" ) ;
printf( "buffer2: %s\n" , buffer2 ) ;
//Concatenates the second argument to first
strcat( buffer1, buffer2 ) ;
printf( "buffer1: %s\n" , buffer1 ) ;
return(0) ;
}
Output:
buffer2: Johnson
buffer1: Jack Johnson
There are 2 important topics regarding arrays and algorithms. One is searching and the other is sorting.
Linear Search
In a linear search we traverse the array starting from bottom and go to the end looking for the element we are interested in.
File: "search1.c"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//Return the index if a match is found
//or return -1 if the match is not found.
//max time size of array
int linearSearch( int arr1[] , int size , int value )
{
int result = -1 ;
for( int i1=0 ; i1 < size ; i1++ )
{
if( arr1[i1] == value )
return i1 ;
}
return result ;
}
//Array must be sorted
//Maximum time log size with the base being 2
int binarySearch( int arr1[] , int size , int value )
{
int result = -1 ;
int left = 0 ;
int right = size-1 ;
int mid ;
while ( left <= right )
{
mid = ( left + right ) / 2 ;
if ( arr1[mid] == value )
return mid ;
else if( arr1[mid] < value )
left = mid + 1 ;
else
right = mid - 1 ;
//printf( "left: %d right: %d\n", left , right ) ;
} //while
return result ;
}
int main()
{
int arr1[] = { 8, 4 , 9 , 1, 2 } ;
int arr2[] = { 1, 2 , 4 , 8, 9 } ;
printf( "Linear search1: %d\n" , linearSearch(arr1, 5, 2 ) ) ;
printf( "Linear search2: %d\n" , linearSearch(arr1, 5, 19 ) ) ;
printf( "Binary search1: %d\n" , binarySearch(arr2, 5, 2 ) ) ;
printf( "Binary search2: %d\n" , binarySearch(arr2, 5, 9 ) ) ;
printf( "Binary search3: %d\n" , binarySearch(arr2, 5, 12 ) ) ;
return(0) ;
}
File: "sort1.c"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void printArray( int arr1[] , int size )
{
for( int i1=0 ; i1<size ; i1++ )
{
printf( "%d " , arr1[i1] ) ;
}
printf( "\n" ) ;
}
void bubbleSort1( int arr1[] , int size )
{
int notDone = 1 ;
int temp ;
int exchangeDone ;
while ( notDone )
{
int exchangeDone = 0 ;
for( int i1=0 ; i1 < size-1 ; i1++ )
{
if( arr1[i1] > arr1[i1+1] )
{ //exchange
temp = arr1[i1] ;
arr1[i1] = arr1[i1+1] ;
arr1[ i1+1 ] = temp ;
exchangeDone = 1 ;
}
} //for
//aleady sorted
if( exchangeDone == 0 )
break ;
}//while
}
void bubbleSort2( int arr1[] , int size )
{
int limit = size - 1 ;
int temp ;
int exchangeDone ;
for( int j1= limit ; j1 > 0 ; j1-- )
{
exchangeDone = 0 ;
for( int i1=0 ; i1 < j1 ; i1++ )
{
if( arr1[i1] > arr1[i1+1] )
{ //exchange
temp = arr1[i1] ;
arr1[i1] = arr1[i1+1] ;
arr1[ i1+1 ] = temp ;
exchangeDone = 1 ;
}
} //for
//aleady sorted
if( exchangeDone == 0 )
break ;
}//for
}
void selectionSort( int arr1[] , int size )
{
int limit = size - 1 ;
int temp ;
int min ;
int minIndex ;
for( int i1= 0 ; i1 < size -1 ; i1++ )
{
min = arr1[i1] ; minIndex = i1 ;
for( int j1= i1+1 ; j1 < size ; j1++ )
{
if( arr1[j1] < min )
{
min = arr1[j1] ;
minIndex = j1 ;
}
} //for
arr1[minIndex] = arr1[i1] ;
arr1[i1] = min ;
}//for
}
void insertionSort( int arr1[] , int size )
{
int limit = size - 1 ;
int temp ;
for( int i1= 1 ; i1 < size ; i1++ )
{
for( int j1= i1 ; j1 > 0 ; j1-- )
{
if( arr1[j1] < arr1[j1-1] )
{ //exchange
temp = arr1[j1] ;
arr1[j1] = arr1[j1-1] ;
arr1[ j1-1 ] = temp ;
}
else
break ;
} //for
}//for
}
int main()
{
int arr1[5] ;
arr1[0] = 8 ; arr1[1] = 4 ; arr1[2] = 9 ;
arr1[3] = 1 ; arr1[4] = 2 ;
bubbleSort1( arr1, 5 ) ;
printArray( arr1, 5 ) ;
arr1[0] = 8 ; arr1[1] = 4 ; arr1[2] = 9 ;
arr1[3] = 1 ; arr1[4] = 2 ;
bubbleSort2( arr1, 5 ) ;
printArray( arr1, 5 ) ;
arr1[0] = 8 ; arr1[1] = 4 ; arr1[2] = 9 ;
arr1[3] = 1 ; arr1[4] = 2 ;
selectionSort( arr1, 5 ) ;
printArray( arr1, 5 ) ;
arr1[0] = 8 ; arr1[1] = 4 ; arr1[2] = 9 ;
arr1[3] = 1 ; arr1[4] = 2 ;
insertionSort( arr1, 5 ) ;
printArray( arr1, 5 ) ;
return(0) ;
}
1)
Complete the code in the following function.
File: "min_max.c"
#include <stdio.h>
/*
Print the max and min in an array. If the array is empty the
function should not print anything.
*/
void printMaxMin(int arr1[] , int size )
{
}
int main()
{
int array1[] = { 1, 2, 300, 5 , 6 } ;
int array2[] = {2} ;
int array3[] = {} ;
printMaxMin( array1 , 5 ) ;
printMaxMin( array2 , 1 ) ;
printMaxMin( array3 , 0 ) ;
return(0) ;
}
2)
//What does the following print ?
#include <stdio.h>
int main()
{
int arr1[] = { 1 , 2, 3, 4 , 5 } ;
int arr2[5] = { 1 , 2 } ;
for( int i1=0 ; i1 < 5 ; i1++ )
{
arr2[i1] = arr1[i1] + arr2[i1] ;
arr2[i1] += arr1[i1] ;
printf( "%d " , arr2[i1] ) ;
} //for
printf( "\n" ) ;
return(0) ;
}
3)
//Fill in the code below for the 2 functions mystrlen and add2Strings .
#include <stdio.h>
#include <string.h>
//------------------------------------------
int mystrlen( char str1[] )
{
int count = 0 ;
int i1 = 0 ;
//TODO
return ( count ) ;
}
//------------------------------------------
//Add 2 strings and place them in str3 with a space between them
void add2Strings( char str1[] , char str2[] , char str3[] )
{
int ind3 = 0 ;
//TO DO
}
//------------------------------------------
int main()
{
char firstName[] = "Jack" ;
char lastName[] = "Dempsey" ;
char buffer1[256] ;
add2Strings( firstName , lastName , buffer1 ) ;
printf( "Full Name: %s\n", buffer1 ) ;
//printing the length
printf ( "Length of firstName: %d\n" , mystrlen( firstName ) ) ;
return(0) ;
}
4)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void mystrcpy( char str1[] , char str2[] )
{
}
void mystrcat( char str1[] , char str2[] )
{
}
int main()
{
char buffer1[256] = "Jack" ;
char buffer2[256] ;
int x1 = 100 ;
int x2 = 0 ;
//Copies the second arguent to first
mystrcpy( buffer2 , " Johnson" ) ;
printf( "buffer2: %s\n" , buffer2 ) ;
//Concatenates the second argument to first
mystrcat( buffer1, buffer2 ) ;
printf( "buffer1: %s\n" , buffer1 ) ;
return(0) ;
}
1) Search for an element in the array.
2) Reverse the elements in the array.
3) Find length of the repeating character that is max.
4) Find stand alone element in the array. Find the single duplicate element in the array.
1)
#include <stdio.h>
/*
Print the max and min in an array. If the array is empty the
function should not print anything.
*/
void printMaxMin(int arr1[] , int size )
{
int max ;
int min ;
if ( size == 0 )
return ;
max = arr1[0] ; min = arr1[0] ;
for( int i1=0 ; i1<size ; i1++ )
{
if ( arr1[i1] < min )
min = arr1[i1] ;
if ( arr1[i1] > max )
max = arr1[i1] ;
}
printf( "The max is %d and the min is %d\n" , max , min ) ;
}
int main()
{
int array1[] = { 1, 2, 300, 5 , 6 } ;
int array2[] = {2} ;
int array3[] = {} ;
printMaxMin( array1 , 5 ) ;
printMaxMin( array2 , 1 ) ;
printMaxMin( array3 , 0 ) ;
return(0) ;
}
2)
$ gcc arr8.c ; ./a.exe
3 6 6 8 10
3)
#include <stdio.h>
#include <string.h>
//------------------------------------------
int mystrlen( char str1[] )
{
int count = 0 ;
int i1 = 0 ;
while ( str1[i1] != 0 )
{
i1++ ;
count++ ;
} //while
return ( count ) ;
}
//------------------------------------------
//Add 2 strings and place them in str3 with a space between them
void add2Strings( char str1[] , char str2[] , char str3[] )
{
int ind3 = 0 ;
for( int i1=0 ; i1 < strlen ( str1 ) ; i1++ )
{
str3[ind3++] = str1[i1] ;
}
str3[ind3++] = ' ' ;
for( int i1=0 ; i1 < strlen ( str2 ) ; i1++ )
{
str3[ind3++] = str2[i1] ;
}
}
//------------------------------------------
int main()
{
char firstName[] = "Jack" ;
char lastName[] = "Dempsey" ;
char buffer1[256] ;
add2Strings( firstName , lastName , buffer1 ) ;
printf( "Full Name: %s\n", buffer1 ) ;
//printing the length
printf ( "Length of firstName: %d\n" , mystrlen( firstName ) ) ;
return(0) ;
}
4)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void mystrcpy( char str1[] , char str2[] )
{
int i1=0 ;
while( str2[i1] != 0 )
{
str1[i1] = str2[i1] ;
i1++ ;
}
str1[i1] = 0 ;
}
void mystrcat( char str1[] , char str2[] )
{
int i1=0 ;
int i2=0 ;
while( str1[i1] != 0 )
{
i1++ ;
}
while( str2[ i2 ] != 0 )
{
str1[ i1++ ] = str2[ i2++ ] ;
}
str1[i1] = 0 ;
}
int main()
{
char buffer1[256] = "Jack" ;
char buffer2[256] ;
int x1 = 100 ;
int x2 = 0 ;
//Copies the second arguent to first
mystrcpy( buffer2 , " Johnson" ) ;
printf( "buffer2: %s\n" , buffer2 ) ;
//Concatenates the second argument to first
mystrcat( buffer1, buffer2 ) ;
printf( "buffer1: %s\n" , buffer1 ) ;
return(0) ;
}
Case Study
Given a 2 dimensional array write a function that will print the elements in a spiral fashion.
File: "spiral.c"
#include <stdio.h>
#define TRUE 1
#define FALSE 0
void spiral( int arr1[4][4] , int size )
{
int originX = 0 ;
int originY = 0 ;
while( TRUE )
{
//printf( "Size: %d\n" , size ) ;
if ( size == 0 )
break ;
if ( size == 1 )
{
printf( "%d " , arr1[originX][originY] ) ;
break ;
}
//horizontal
for( int i1=originY ; i1 < originY + size ; i1++ )
printf( "%d " , arr1[ originX ][ i1] ) ;
//right vertical
for( int i1=originX+1 ; i1 < originX + size ; i1++ )
{
printf( "%d " , arr1[ i1][originY+size-1] ) ;
}
//below horizontal
for( int i1=originY+size-2 ; i1 >= originY ; i1-- )
printf( "%d " , arr1[originX+size-1][ i1] ) ;
//left vertical
for( int i1=originX+size-2 ; i1 > originX ; i1-- )
printf( "%d " , arr1[i1 ][ originY] ) ;
size -= 2 ;
originX++ ; originY++ ;
}//while
printf( "\n" ) ;
}
int main()
{
int arr1[1][1] = { {1} } ;
int arr2[2][2] = { {1,2} , {3,4} } ;
int arr3[3][3] = { {1,2,3} , {4,5,6}, {7,8,9} } ;
int arr4[4][4] = { {1,2,3,4} , {5,6,7,8}, {9,10,11,12}, {13,14,15,16} } ;
//spiral( arr1 , 1 ) ;
//spiral( arr2 , 2 ) ;
// spiral( arr3 , 3 ) ;
spiral( arr4 , 4 ) ;
}