0% found this document useful (0 votes)
8 views

CS112 Programming Languages 1 (Lecture 5 - Spring 2020)

This document is a lecture on static variables and pointers in C programming, part of the CS112 course for Software Engineering and Medical Informatics. It covers the basics of pointers, including their declaration, referencing, dereferencing, and pointer arithmetic, along with static variables and their properties. Additionally, it includes solved examples demonstrating practical applications of these concepts in C programming.

Uploaded by

zeyadzzzzsss
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)
8 views

CS112 Programming Languages 1 (Lecture 5 - Spring 2020)

This document is a lecture on static variables and pointers in C programming, part of the CS112 course for Software Engineering and Medical Informatics. It covers the basics of pointers, including their declaration, referencing, dereferencing, and pointer arithmetic, along with static variables and their properties. Additionally, it includes solved examples demonstrating practical applications of these concepts in C programming.

Uploaded by

zeyadzzzzsss
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/ 46

CS112 – Level 1

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.

0x0 0x1 0x2 0x3


Just as ints are variables that
store integers and floats are
variables that store floating-
point values, a pointer is a
variable that stores memory 0x4 0x5 0x6 0x7
addresses.

E.g., in an operating appliance,


if the memory address is 4
bytes, so it makes sense that a 0x8 0x9 0xA 0xB
pointer is also 4 bytes.
Creating Pointers
Declaring pointers:
<type>* <variable name>

Here's how to declare a pointer in C.


Examples:
Remember that a pointer's value is a
int* x;
memory address. Its type then describes the char* y;
data located at that address. float* z;
So in the first example, int* x declares a
pointer to 4 bytes of memory that will
contain an integer.
Referencing and Dereferencing
Referencing:
&<variable name>
& is the reference, or address-of, operator. It returns the address in
memory at which a variable is stored.

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.

Variable Address Value

int x = 5; x 0x04 5

int* ptr = &x; ptr 0x08 0x04

int copy = *ptr; copy 0x0C 5


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.

Variable Address Value

int x = 5; x 0x04 5

int* ptr = &x; ptr 0x08 0x04

int copy = *ptr; copy 0x0C 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.

Variable Address Value

int x = 5; x 0x04 5

int* ptr = &x; ptr 0x08 0x04

int copy = *ptr; copy 0x0C 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.

Variable Address Value

int x = 5; x 0x04 5

int* ptr = &x; ptr 0x08 0x04

int copy = *ptr; copy 0x0C 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

int* ptr = &x; 5 &x

*ptr = 35; 35 &x


Test Yourself
Test yourself by tracking the values of these variables just as we did before.
int
intaa==3,
3,bb==4,
4,cc==5;
5;
int*
int*pa
pa==&a,
&a,*pb
*pb==&b,
&b,*pc
*pc==&c;
&c; a b c pa pb pc

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

a = b * c; 20 4 5 &a &b &c

a *= c; 100 4 5 &a &b &c

b = *pa; 100 100 5 &a &b &c

pc = pa; 100 100 5 &a &b &a

*pb = b * c; 100 500 5 &a &b &a

c = (*pa) * (*pc); 100 500 10000 &a &b &a

*pc = a * (*pb); 50000 500 10000 &a &b &a


Pointer Arithmetic
You can adjust pointers by adding or subtracting an integer.

Adding / subtracting n adjusts the pointer by


n * sizeof(<type of the pointer>) bytes
Adding or subtracting n adjusts the pointer by n * sizeof(<pointer
type>) bytes. For example, in the code on this slide, y is a pointer to an int
called x, which is stored at 0x04. Therefore, adding 1 to y shifts the value of y by 1
* sizeof(int) or 4 bytes.

x y

int x = 5; 5

int* y = &x; 5 0x04

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.

Here is the syntax of static variables in C language:


static data_type var_name = var_value;
Here,
o data_type − The datatype of variable; int, char, float, .. etc.
o var_name − This is the name of variable given by the user.
o var_value − Any value to initialize the variable.
By default, it is zero.
Revision ..&..
Solved
Examples [1]

26
5.1: Write a C program to Swap Two
Numbers using a Function

Swapping two variables refers to mutually exchanging the


values of the variables. Generally, this is done with the data in
memory. The simplest method to swap two variables is to use a
third temporary variable : a temp b
define swap(a, b)
temp := a
a := b
b := temp
Function: Swap two numbers using a function:
------------------------------------------------
Input the 1st number: 2
Input the 2nd number: 4
Before Swapping: n1 = 2, n2 = 4
After Swapping: n1 = 4, n2 = 2
#include <stdio.h>
void swap( int *, int * );
int main() {
int n1, n2;
printf("\n\nFunction: Swap two numbers using a function:\n");
printf("------------------------------------------------\n");
printf("Input the 1st number: "); scanf("%d", &n1);
printf("Input the 2nd number: "); scanf("%d", &n2);
printf("Before Swapping: n1 = %d, n2 = %d ", n1, n2);

// pass the addresses of both variables to the function.


swap( &n1, &n2 );
printf("\nAfter Swapping: n1 = %d, n2 = %d \n\n", n1, n2);
return 0;
}
void swap( int *p, int *q )
{
// p = &n1, so p stores the address of n1, and therefore *p stores the value of n1
// q = &n2, so q stores the address of n2, and therefore *q stores the value of n2
int tmp;
tmp = *p; // tmp stores the value of n1
*p = *q; // *p stores the value of *q, i.e. the value of n2
*q = tmp; // *q stores the value of tmp, i.e. the value of n1
}
5.2: Write a C program to find out the
maximum & minimum of some values using a
function that returns an array.
Write a C program that includes a function to find out the
maximum & minimum of some values, the function should
return an array.

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.

Two strings are anagrams of each other if we can rearrange the


characters of one string to form the other string. All the
characters of one string must be present in the other string,
and should appear the same number of times in other string.
Strings can contain any ASCII characters.
Examples: rescued / secured, resign / singer, stone / tones,
pears / spare, ELEVEN_PLUS_TWO / TWELVE_PLUS_ONE,
binary / brainy
Function: Whether any two given strings are Anagrams or not:
Anagrams' Examples: (pears and spare), (stone and tones):
-------------------------------------------------------
Input the First String: spare
Input the Second String: pears
spare and pears are Anagrams.
#include <stdio.h>
#include <string.h>

int checkAnagram( char *str1, char *str2 );


int main()
{
char str1[ 100 ], str2[ 100 ];
printf("\n Function: Whether any two given strings are Anagrams or not:\n");
printf("\n Anagrams' Examples: (pears and spare), (stone and tones):\n");
printf(" -------------------------------------------------------\n");
printf(" Input the First String: ");
scanf("%s", &str1 );
printf(" Input the Second String: ");
scanf("%s", &str2 );

if( checkAnagram( str1, str2 ) == 1) {


printf(" %s and %s are Anagrams.\n\n", str1, str2 );
}
else {
printf(" %s and %s are Not Anagrams.\n\n", str1, str2 );
}
return 0;
}
// This function checks whether any two strings are anagrams or not

int checkAnagram( char *str1, char *str2 )


{
int str1ChrCtr[ 256 ] = { 0 }, str2ChrCtr[ 256 ] = { 0 };
int ctr;

/* Check if both strings have the same length or not */


if( strlen( str1 ) != strlen( str2) ) { return 0; }

// Count the frequency of each character in the first string


for( ctr = 0; str1[ ctr ] != '\0'; ctr++ ) { str1ChrCtr[ str1[ ctr ] ]++; }

// Count the frequency of each character in the second string


for( ctr = 0; str2[ ctr ] != '\0'; ctr++ ) { str2ChrCtr[ str2[ ctr ] ]++; }

// Compare the characters’ counts of both strings


for( ctr = 0; ctr < 256; ctr++ )
{
if( str1ChrCtr[ ctr ] != str2ChrCtr[ ctr ] )
return 0;
}
return 1;
}
5.4: Write a C function to get the Largest Element
of an array using recursion.

Recursion: Get the Largest Element of an Array:


------------------------------------------------------
Input the number of elements to be stored in the array (not more than 100): 5
Input 5 elements in the array:
Element #1: 5
Element #2: 10
Element #3: 15
Element #4: 20
Element #5: 25
The Largest Element of the Array is: 25
#include<stdio.h>
#define MAX 100

void MaxElem( int [], int );


int n, hstno;

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 );

printf(" Input %d elements in the array:\n", n );


for( i = 0; i < n; i++ ) {
printf(" Element #%d: ", i + 1 ); scanf("%d", &arr1[ i ] );
}

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.

Delete an element at a desired position from an array:


---------------------------------------------------------
Input the size of the array (not more than 50): 5
Input %d elements in the array:
Element #1 : 4
Element #2 : -5
Element #3 : 2020
Element #4 : 3
Element #5 : 89

Input the position of the element to be deleted: 3


The new list is: 4 -5 3 89
5.5: Write a program in C to delete an element
at a desired position from an array.
#include <stdio.h>
#define MAX 50

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 );

/* Store values into the array */


printf("Input %d elements in the array:\n\n", n );
for( i = 0; i < n; i++ ) { printf("Element #%d: ", i + 1 ); scanf("%d", &arr1[ i ] ); }

printf("Input the position of the element to be deleted: "); scanf("%d", &pos );

/* locate the position of i in the array */


i=0; while( i != pos - 1 ) i++;

/* 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

Input the Elements of the First Matrix:


Element - [1], [1]: 1
Element - [1], [2]: 2
Element - [2], [1]: 3
Element - [2], [2]: 4

Input the Elements of the Second Matrix:


Element - [1], [1]: 5
Element - [1], [2]: 6
Element - [2], [1]: 7
Element - [2], [2]: 8
5.6: Write a C program to Multiply Two Matrices.

The First Matrix is:


1 2
3 4

The Second Matrix is:


5 6
7 8

The Multiplication of the Two Matrices is:


19 22
43 50
5.6: Write a C program to Multiply Two Matrices.
#include <stdio.h>
#define SIZE 50

int main() {
int arr1[ SIZE ][ SIZE ], brr1[ SIZE ][ SIZE ], crr1[ SIZE ][ SIZE ], i, j, k, r1, c1, r2, c2, sum = 0;

printf("\n\nMultiplication of Two Matrices :\n");


printf("----------------------------------\n");
printf("\nInput the numbers of rows and columns of the First Matrix : ");
scanf("%d %d", &r1, &c1);
printf("\nInput the numbers of rows and columns of the Second Matrix : ");
scanf("%d %d", &r2, &c2);
if( c1 != r2 ) {
printf("The Multiplication of those Matrices is Not Possible.");
printf("\nThe Number of Columns of the 1st matrix & the Number of Rows of the 2nd
Matrix must be equal."); }
else {
printf("Input the Elements of the First Matrix:\n");
for( i = 0; i < r1; i++ ) {
for( j = 0; j < c1; j++ ) {
printf("Element - [%d], [%d]: ", i + 1, j + 1 );
scanf("%d", &arr1[ i ][ j ] );
}
}
printf("Input the Elements of the Second Matrix :\n");
for( i = 0; i < r2; i++ ) {
for( j = 0; j < c2; j++ ) {
printf("Element - [%d], [%d]: ", i + 1, j + 1);
scanf("%d", &brr1[ i ][ j ] );
}
}

printf("\nThe First Matrix is:\n");


for( i = 0; i < r1; i++ )
{
printf("\n");
for( j = 0; j < c1; j++ )
printf("%d\t", arr1[ i ][ j ] );
}

printf("\nThe Second Matrix is:\n");


for( i = 0; i < r2; i++ )
{
printf("\n");
for( j = 0; j < c2; j++ )
printf("%d\t", brr1[ i ][ j ] );
}
// Multiplication of the Matrices
for( i = 0; i < r1; i++ )
for( j = 0; j < c2; j++ )
crr1[ i ][ j ] = 0;
for( i = 0; i < r1; i++ ) // Rows of the First Matrix
{
for( j = 0; j < c2; j++ ) // Columns of the Second Matrix
{
sum = 0;
for( k = 0; k < c1; k++ )
sum = sum + arr1[ i ][ k ] * brr1[ k ][ j ];
crr1[ i ][ j ] = sum;
}
}
printf("\nThe Multiplication of the Two Matrices is: \n");
for( i = 0; i < r1; i++ ) {
printf("\n");
for( j = 0; j < c2; j++ )
{
printf("%d\t", crr1[ i ][ j ] );
}
}
}
}
Thanks! .. Questions?

46

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy