CS112 Programming Languages 1 (Lecture 5 - Spring 2020)
CS112 Programming Languages 1 (Lecture 5 - Spring 2020)
Programming Languages 1
( General Division – Software Engineering Program – Medical Informatics Program )
Lecture 5
Static Variables, Revision [ Basics of Pointers ] .. and ..
Solved Examples [ 1 ]
Spring 2020 (Semester 2)
Week 6
Course & Lectures are based on their counterparts in the following courses:
o Harvard University's CS50; An introduction to the intellectual enterprises of
computer science and the art of programming, Harvard School of
Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New
South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++
(2011), and 6.S096 Introduction to C and C++ (2013), MIT (Massachusetts
1
Institute of Technology) OpenCourseWare.
• Revision 2
• Basics of Pointers
• Static Variables in C
• Solved Examples
• 5.1: A C program to Swap Two
Numbers using a Function
O • 5.2: A C program to find out the
u maximum & minimum of some values
t using a function that returns an array.
Outline l
i
n
• 5.3: A C function that checks whether
any two given strings are anagrams or
e
not.
• 5.4: A C function to get the Largest
Element of an array using recursion.
• 5.5: A C program to delete an element
at a desired position from an array.
• 5.6: A C program to Multiply Two
Matrices. 2
Revision Basics of
Pointers
3
Pointers
The C programming language gives us the ability to directly
manipulate the contents of memory addresses via pointers.
Unfortunately, this power brings with it the freedom to screw things
up spectacularly as simple errors can corrupt the state of your
program in ways that make debugging difficult.
The goal of these slides is to make sure that you understand exactly
what you're doing when you use pointers in your code.
Memory
Code and data for your program are stored in random-access memory (RAM),
which is basically a huge array of 1 byte (8 bits) blocks. Each block is associated
with a hexadecimal number that represents its memory address.
Dereferencing:
*<pointer name>
* is the dereference operator. A pointer's value is a memory address. When
the dereference operator is applied to a pointer, it returns the data stored
at that memory address.
Under the hood ..
Here are examples of the referencing and dereferencing operators in use. Let's think
carefully about what's going on under the hood as each line executes.
int x = 5; x 0x04 5
int x = 5; x 0x04 5
• The first line declares an integer called x. 4 bytes are allocated for x at the
memory address 0x04, and the value 5 is stored there.
Under the hood ..
Here are examples of the referencing and dereferencing operators in use. Let's think
carefully about what's going on under the hood as each line executes.
int x = 5; x 0x04 5
• The second line declares an int pointer called ptr. 4 bytes are allocated
for ptr at the memory address 0x08, and the address of x is stored there.
Under the hood ..
Here are examples of the referencing and dereferencing operators in use. Let's think
carefully about what's going on under the hood as each line executes.
int x = 5; x 0x04 5
• The third line declares an integer called copy. 4 bytes are allocated for copy at
the memory address 0x0C, and the value of the integer that ptr is pointing to is
stored there.
Track the values
Let's track the values of these variables as each line executes:
• In the first line, x is initialized to 5.
• In the second line, ptr is assigned x's memory address. x remains 5.
• In the third line, we dereference ptr (aka, go to the value it is pointing to)
and change that value to 35.
x ptr
int x = 5; 5
a = b * c;
a *= c;
b = *pa;
pc = pa;
*pb = b * c;
c = (*pa) * (*pc);
*pc = a * (*pb);
Answers
int a = 3, b = 4, c = 5;
int* pa = &a, *pb = &b, *pc = &c; a b c pa pb pc
x y
int x = 5; 5
y += 1; 5 0x08
What will print?
int main(void)
{
char* str = "cat";
int counter = 0;
for (char* ptr = str; *ptr != '\0'; ptr++)
{
counter++;
}
printf("%d\n", counter);
}
str
What will print? c
int main(void) a
{ t
char* str = "cat"; \0
int counter = 0;
for (char* ptr = str; *ptr != '\0'; ptr++)
{
counter++;
}
printf("%d\n", counter);
}
counter 1
str
What will print? ptr c
int main(void) a
{ t
char* str = "cat"; \0
int counter = 0;
for (char* ptr = str; *ptr != '\0'; ptr++)
{
counter++;
}
printf("%d\n", counter);
}
Pay close attention to the syntax of this for loop. ptr starts out
pointing to the first character of the string.
counter 2
str
What will print? ptr c
int main(void) a
{ t
char* str = "cat"; \0
int counter = 0;
for (char* ptr = str; *ptr != '\0'; ptr++)
{
counter++;
}
printf("%d\n", counter);
}
Incrementing ptr shifts the pointer by 1 * sizeof(char)or 1 byte,
moving ptr to the next character in the string.
counter 3
str
What will print? ptr c
int main(void) a
{ t
char* str = "cat"; \0
int counter = 0;
for (char* ptr = str; *ptr != '\0'; ptr++)
{
counter++;
}
printf("%d\n", counter);
}
Incrementing ptr shifts the pointer by 1 * sizeof(char)or 1 byte,
moving ptr to the next character in the string.
counter 3
str
What will print? ptr c
int main(void) a
{ t
char* str = "cat"; \0
int counter = 0;
for (char* ptr = str; *ptr != '\0'; ptr++)
{
counter++;
}
printf("%d\n", counter);
}
Incrementing ptr shifts the pointer by 1 * sizeof(char)or 1 byte,
moving ptr to the next character in the string.
After the loop executes, the length of the string will be printed.
Pointers and Arrays
int array[3];
*array = 1; 0 1 2
*(array + 1) = 2;
*(array + 2) = 3;
1 2 3
Under the hood, an array is treated like a pointer to its first element,
so standard pointer arithmetic applies:
*array is equivalent to array[0]
*(array+1) is equivalent to array[1]
*(array + 2) is equivalent to array[2].
Static Variables
23
Static Variables in C
Static variables:
- are initialized only once.
- have a property of preserving their value even after they
are out of their scope.
Hence, ..
Static variables preserve their previous value in their previous
scope and are not initialized again in the new scope.
Static Variables in C
Static variables:
- can be defined inside or outside the function.
- are local to the block.
- are alive till the execution of the program.
-The default value of static variables is zero.
26
5.1: Write a C program to Swap Two
Numbers using a Function
The number of values you want to input (not more than MAX): 6
38
22
11
15
65
60
The minimum value is: 11
The maximum value is: 65
#include <stdio.h>
#define max 10
int * maxmin( int ar[], int v );
int main() {
int arr[ max ]; int n, i, *p;
printf("The number of values you want to input (not more than %d): ", max );
scanf("%d", &n);
printf("Input the %d values:\n", n);
for( i = 0; i < n; i++ )
scanf("%d", &arr[ i ] );
p = maxmin( arr, n );
printf("The minimum value is: %d\n", *p++ );
printf("The maximum value is: %d\n", *p);
}
int * maxmin( int arra1[], int v ) {
int i; static int result_mm[ 2 ];
result_mm[ 0 ] = arra1[ 0 ];
result_mm[ 1 ] = arra1[ 0 ];
for ( i = 1; i < v; i++ ) {
if( result_mm[ 0 ] > arra1[ i ] ) result_mm[ 0 ] = arra1[ i ];
if( result_mm[ 1 ] < arra1[ i ] ) result_mm[ 1 ] = arra1[ i ];
}
return result_mm;
}
5.3: Write a C function that checks whether any
two given strings are anagrams or not.
int main()
{
int arr1[ MAX ], i;
printf("\n Recursion: Get the Largest Element of an Array:\n");
printf(" ------------------------------------------------------\n");
printf(" Input the number of elements to be stored in the array (not more than %d):", MAX);
scanf("%d", &n );
hstno = arr1[ 0 ];
MaxElem( arr1, 1 ); // Call the recursive function MaxElem to return the largest element
printf(" The Largest Element of the Array is: %d\n\n", hstno );
return 0;
}
void MaxElem( int arr1[], int index )
{
if( index < n )
{
if( hstno < arr1[ index ] )
hstno = arr1[ index ];
// Calling the recursive function MaxElem again to compare with a further element
MaxElem( arr1, index + 1 );
}
return;
}
5.5: Write a program in C to delete an element
at a desired position from an array.
int main() {
int arr1[ MAX ], i, pos, n;
printf("Delete an element at a desired position from an array:\n");
printf("---------------------------------------------------------\n");
printf("Input the size of the array (not more than %d): ", MAX); scanf("%d", &n );
/* the position of i in the array will be replaced by the value to its right */
while( i < n ) { arr1[ i ] = arr1[ i + 1 ]; i++; } n--;
printf("\nThe new list is: "); for( i = 0; i < n; i++ ) { printf(" %d", arr1[ i ] ); }
}
5.6: Write a C program to Multiply Two Matrices.
The Multiplication of Two Matrices:
----------------------------------
Input the Numbers of Rows and Columns of the First Matrix: 2 2
Input the Numbers of Rows and Columns of the Second Matrix: 2 2
int main() {
int arr1[ SIZE ][ SIZE ], brr1[ SIZE ][ SIZE ], crr1[ SIZE ][ SIZE ], i, j, k, r1, c1, r2, c2, sum = 0;
46