0% found this document useful (0 votes)
4 views43 pages

Lecture_Week_7.1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
4 views43 pages

Lecture_Week_7.1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 43

Introduction to Computing

and Programming

Arrays and Function


Outline
• Multi-Dimensional Arrays
• Basics of Function
• Scope of Functions
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
int i;
// Get the length of the array
Write a program int length = sizeof(ages) / sizeof(ages[0]);
that finds the // Create a variable and assign the first array element
of ages to it
lowest age int lowestAge = ages[0];
among different // Loop through the elements of the ages array to find
the lowest age
ages for (i = 0; i < length; i++) {
if (lowestAge > ages[i]) {
lowestAge = ages[i];
}}
• A multi-dimensional array can be defined as an array that
has more than one dimension.
• It can grow in multiple directions.
Syntax:
• The general form of declaring N-dimensional arrays is
Multidimensiona shown below:
l Arrays – 2D
and 3D type arr_name[size1][size2]….[sizeN];
• Ex.
• Two-dimensional array: int two_d[10][20];
• Three-dimensional array: int three_d[10][20][30];
Size of Multidimensional Arrays
• The total number of elements that can be stored in a multidimensional array
can be calculated by multiplying the size of both dimensions.
• Example:
• The array arr[10][20] can store total of (10*20) = 200 elements.
• To get the size in bytes, we multiply the size of a single element (in bytes)
by the total number of elements in the array.
• Example:
• The size of array int arr[10][20] = 10 * 20 * 4 = 800 bytes, where the
size of int is 4 bytes.
Two-Dimensional • 2D array is also known as a matrix (a table of rows
Array and columns).

• Example:
• int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
Access the Elements of a 2D Array
• To access an element of a two-dimensional array, you must specify the
index number of both the row and column.

• This statement accesses the value of the element in the first row
(0) and third column (2) of the matrix array.

• Example
• int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

printf("%d", matrix[0][2]); // Outputs 2


Change Elements in a 2D Array
• To change the value of an element, refer to the index number of the element
in each of the dimensions:

• The following example will change the value of the element in the first row
(0) and first column (0):
• Example
• int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;

printf("%d", matrix[0][0]); // Now outputs 9 instead of 1


#include <stdio.h>
int main() {
// Initialize an array with 3 rows and 2 columns
int arr[3][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
Traversal in // Print each array element's value
for (int i = 0; i < 3; i++) {
2D Array for (int j = 0; j < 2; j++) {
printf("arr[%d][%d]: %d ", i, j, arr[i][j]);
}
printf("\n"); }
return 0;}
#include <stdio.h>
void main ()
{ int arr[3][3],i,j;
Storing and for (i=0;i<3;i++)

printing
{ for (j=0;j<3;j++) {
printf("Enter a[%d][%d]: ",i,j);

elements at } }
scanf("%d",&arr[i][j]);

runtime printf("\n printing the elements ....\n");


for(i=0;i<3;i++)
{ printf("\n");
for (j=0;j<3;j++)
{ printf("%d\t",arr[i][j]); } } }
Three-Dimensional (3D) Array in C

• A Three-Dimensional Array or 3D array


is a collection of two-dimensional arrays.

• It can be visualized as multiple 2D arrays


stacked on top of each other.
Declaration and Initialization

Declaration: type arr_name[x][m][n];

int arr[2][3][2] = {0, 1, 2, 3, 4, 5, 6, 7 , 8, 9, 10, 11}


Initialization: Or
int arr[2][3][2] = { { { 0, 1 }, { 2, 3 }, { 4, 5 } }, { { 6, 7 }, { 8, 9 }, { 10, 11 } } };
#include <stdio.h> Traversal in
3D array
int main() {
// Create and Initialize the 3-dimensional array
int arr[2][3][2] = { { { 1, 1 }, { 2, 3 }, { 4, 5 } }, { { 6, 7 }, { 8, 9 }, { 10, 11 } } };
for (int i = 0; i < 2; ++i) {// Loop through the depth
for (int j = 0; j < 3; ++j) {// Loop through the rows of each depth
for (int k = 0; k < 2; ++k) // Loop through the columns of each row
printf("arr[%i][%i][%i] = %d ", i, j, k, arr[i][j][k]);
printf("\n");}
printf("\n\n"); }
return 0;}
Advantages:

• Fast access to elements.


• Efficient memory usage.
Advantages
and
Disadvantages Disadvantages:

• Fixed size (in static arrays).


• Insertion and deletion can be
costly.
Use Cases of Arrays

Matrix Buffers and


Data Storage:
Representation: Tables:

Use in
Storing
2D arrays for graphics,
collections of
matrices. tables, and
data.
buffers.
Array with pointer will be discussed later
Functions
Content

Function
Arguments, Mid-sem Paper Macro & Inline
Function with Discussion Functions
Arrays
Function basics & Motivations

• Program redundancy can be reduced by creating a grouping of predefined


statements for repeatedly used operations, known as a function.

• This is Temperature conversion code;


• Cluttered repeated code; Error in c3;
Function basics & Motivations Cont..

• // Function to convert Fahrenheit to Celsius

float F2C(float f) {
float c= (f – 32.0) * (5.0 / 9.0);
return c;}
• The impact is even greater when the
operation has multiple statements.

• The main program is much simpler.


• The general skeleton of a function in C is as follows:
return_type function_name ( parameter list ) {
// body of the function}
Example: int add(int a, int b){
return (a+b);}
▪ A function definition consists of:
Defining a ▪ a function header and
Function ▪ a function body
▪ Function Declaration tells the compiler about a
function's name, return type, and parameters
▪ A function definition provides the actual body
of the function
Function an Example:
Scope of the variables
• A simplified version of the same function that
Functions – A finds the maximum of two integers: m, n

Simplified int getMax(int num1, int num2) {


Example return ((num1 > num2) ? num1 : num2);
}
• How do we call getMax function from main()?
int main(void) {
int m = 10, n = 27;
printf("\nm = %d, n = %d\n", m, n);
Functions – main() int max = getMax(m,n);
printf("\nMax = %d\n", max);

return 0;

}
Function
that finds
max(m,n)
Where is
the
function
defined?
Function Arguments

• A function argument (or parameter) is a value passed to a function when it is


called.
• The function can use these values to perform its task.
• Two types:
• Formal Arguments (declared in the function definition): Formal parameters
behave like local variables inside the function and are created upon entry
into the function and destroyed upon exit.
• Actual Arguments (provided during the function call)
Function Arguments Example
1. Formal Arguments:
Example: int add(int a, int b) {
return a + b;
}

2. Actual Arguments: Arguments are


passed to the function when it is called
Example: int result = add(5, 10); // 5 and
10 are actual arguments
Function Call ➢Two ways to call a function:
with Call by Value
Arguments Call by Reference
➢arguments can be passed to a function
using any o the above way
A copy of the actual argument is passed to the
function.

Modifying the parameter inside the function


does not affect the original argument.
Call by Example:
void changeValue(int x) {
Value x = 20;
}
int main() {
int num = 10;
changeValue(num);
printf("%d", num); // Output: 10
}
#include <stdio.h>
// Function to swap two numbers using call by value
void swapByValue(int a, int b) {
int temp = a;
a = b;
b = temp;
Another printf("Inside swap: a = %d, b = %d\n", a, b);
}
Example of int main() {
Call by int x = 10, y = 20;
printf("Before swap: x = %d, y = %d\n", x, y);
Value swapByValue(x, y); // Call by value
printf("After swap: x = %d, y = %d\n", x, y);
return 0;}
Output: Before swap: x = 10, y = 20
Inside swap: a = 20, b = 10
After swap: x = 10, y = 20
A reference (address) to the actual argument is
passed to the function.

Modifying the parameter inside the function does


affect the original argument.
Example:

Call by void changeValue(int *x) {


*x = 20;
Reference }

int main() {
int num = 10;
changeValue(&num);
printf("%d", num); // Output: 20
}
#include <stdio.h>
// Function to swap two numbers using call by reference
void swapByReference(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
Example of }
printf("Inside swap: a = %d, b = %d\n", *a, *b);

Call by int main() {

Reference
int x = 10, y = 20;
printf("Before swap: x = %d, y = %d\n", x, y);
swapByReference(&x, &y); // Call by reference
printf("After swap: x = %d, y = %d\n", x, y);
return 0;}
Output: Before swap: x = 10, y = 20
Inside swap: a = 20, b = 10
After swap: x = 20, y = 10
▪ Example: void PrintGreetings() {
printf(“\nWelcome to SNU”);
printf(“\nSNU is an Institute of
Eminence\n”);
A Simple }

Function • The above function has


Example no arguments and
no return value
But prints the greetings message

• Functions can also have arguments (one or more)


depending on the specific task in hand
▪ Compute and print the sum of the first N natural Numbers
• This function does not need to return any value.
#include <stdio.h>
/* Method 1 – Using FOR loop */
void getSumN( int n ) {
int i = 0, sum = 0;
for (i = 0; i < n + 1; i++) {
Function sum += i;
}
with one printf("\nMethod - 1: \nN = %d, SUM = %d\n", n, sum);
}
argument int main(int argc, char *argv[]) {
/*accepts command-line arguments: int argc: Argument
count (the number of arguments passed from the command
line, char *argv[]) :Argument vector (an array of pointers to
the command-line arguments*/
int m = 10;
getSumN(m); /* Calling Method 1 */
return 0;
}
A small exercise
Write the function declaration & definition for BMI
calculation
A small exercise- Solution
#include <stdio.h> // Call the BMI function
bmi = calculateBMI(weight, height);
// Function declaration
float calculateBMI(float weight, float height);
// Output the calculated BMI
// Main function printf("Your BMI is: %.2f\n", bmi);
int main() {
float weight, height, bmi; return 0;
}
// Input weight and height
printf("Enter weight in kilograms: ");
scanf("%f", &weight); // Function definition
float calculateBMI(float weight, float height) {
printf("Enter height in meters: "); return weight / (height * height); // BMI
scanf("%f", &height); formula
}
Function
with Two
arguments
Function
with no
return value
Function
with return
value
Mid-semester pattern discussion
• Consists of ~ total 10 to 12 questions (Objective, theory, and Programming questions);
• Marks: ~ 20 marks
• Duration ~ 1 to 1.5 Hours;
• These types of Questions can be asked:
• Type 1: MCQ questions: What will be output of the following programs
• Type 2. Point out the errors, if any in the following C statements
• Type 3: Evaluate the following expression/ Number System
• Type 4: Theory Question (The concepts taught in the lecture)
• Type 5: Write the C Program for the question
• Type 6: Fill in the blanks with logic (Code snippet)
Mid-Semester Syllabus
• All the topics covered till today (24th Sept)
• Topics: Introduction to Basic Fundamentals of Computers, Introduction to
Programming, Identifiers and Constants, Data Types, Number System, Operators,
Logical Expressions, Managing input & output, Conditional statements, Decision
making & Branching, Decision making & loops, Arrays, Functions
• Note: kindly refer lecture slides as well as textbooks mentioned in the lecture 1
slides for detailed theory & practice purpose.
• I will upload the question bank today for your reference & the practice of coding.
• Thursday (26th Sept) class would be of revision class; Attendance will be given to
all the students.
• I will upload the question bank of Array & Function today.
• We will be taking graded lab 2 from 7th to 11th Oct.

You might also like