Lecture5-Array String
Lecture5-Array String
BASIC PROGRAMMING
Lecture 5: Array and String
▪ Array:
▪ Why and What?
▪ Declaring arrays
▪ Accessing Array Elements
▪ Arrays and Addresses
▪ Passing and returning arrays to/from functions
▪ String:
▪ String-array
▪ String library functions
2
Array
3
Why Array?
4
Compute Average with
Individual Variables
#include <stdio.h>
int main(void){
int count = 10; /* Number of values to be read */
long sum = 0L; /* Sum of the numbers */
int mark1, mark2, mark3, mark4, mark5, mark6, mark7, mark8, mark9, mark10;
float average = 0.0f; /* Average of the numbers */
sum = mark1 + mark2 + mark3 + mark4 + mark5 + mark6 + mark7 + mark8 + mark9 + mark10;
average = (float)sum/count; /* Calculate the average
*/
printf("\nAverage of the ten numbers entered is: %f\n", average);
return 0;
}
5
What is an Array?
▪ Idea:
▪ A data structure to store consecutive individual variables
▪ manage as a collection
6
Declaring Arrays
▪ Array declaration:
▪ Data type of items
▪ Variable name
▪ Array size: number of items
▪ 1-D Arrays: 0 1 2 3 4
int A[5];
▪ 2-D Arrays: 0 1 2 3 4
int A[3][5]; 0
7
Initializing Arrays
8
Accessing Array Elements
▪ One-dimensional arrays
// array declaration 0 1 2 3 4
int A[5] = {1, 2, 3, 4, 5}; 1 2 3 4 5
9
Accessing Array Elements
▪ 2-dimensional arrays
// array declaration
int A[2][5] = {{1,2,3,4,5}, {6,7,8,9,10}};
for (int i =0; i<2; i++)
{
for (int j =0; j<5; j++)
{
printf("%d \t", A[i][j]); 0 1 2 3 4
}
0 1 2 3 4 5
printf("\n");
} 1 6 7 8 9 10
10
Accessing Array Elements
11
Arrays and Address
1 2 3 4 5
Memory area
A
12
Arrays and Address
▪ 2-D array:
int A[2][3];//2 rows, 3 columns
1 2 3 4 5 6
13
Arrays and Address
▪ Print out address of array elements
int A[2][3] = {
{1,2,3},
{4,5,6}
};
14
Compute the Average using Array
#include <stdio.h>
int main(void){
int numbers[10]; /* Array storing 10 values */
int count = 10; /* Number of values to be read */
long sum = 0L; /* Sum of the numbers */
float average = 0.0f; /* Average of the numbers */
printf("\nEnter the 10 numbers:\n"); /* Prompt for the input */
▪ As an unknown-size array
▪ 1-D array: void myfunction(int a[], int size)
▪ 2-D array: void myfunction(int a[][3], int row)
▪ As a fixed size array
▪ 1-D array: void myfunction(int a[5])
▪ 2-D array: void myfunction(int a[5][3])
▪ As a pointer
▪ 1-D array: void myfunction(int *a)
▪ 2-D array: void myfunction(int **a)
16
Passing Arrays to Functions
Compute_average.h Main.c
#include <stdio.h>
float compute_average (int numbers[], int size)
#include "compute_average.h"
{
int main(void){
float sum = 0L; /* Sum of the numbers */ int numbers[10]; /* Array storing 10 values */
float avg = 0.0f; /* Average of the numbers */ int count = 10; /* Number of values to be read */
for(int i = 0; i < size; i ++) long sum = 0L; /* Sum of the numbers */
return 0;
}
17
Returning Arrays from Functions
18
String
19
String Concept
▪ A string:
▪ Sequence of characters
▪ Is stored in an array of type char
H E L L O
W H A T ’ S A B E A U T I F U L D A Y !
20
Eg: String as an Array char
#include <stdio.h>
int main(void){
char gretting[] = "Hello";//compiler will automatically
create sufficient space fo hold all characters declared*/
int size = 5;
for (int i =0;i<size;i++)
{
printf("The charactor #%d is %c\n", i+1, gretting[i]);
}
return 0;
}
21
Array of strings
#include <stdio.h>
int main(void){
char subject_names[5][30] = {"Linear Algebra", "Calculus", "Physics", "Com
puter Architecture", "Basic Programming"};
int size = 5;
for (int i =0;i<size;i++)
{
printf("The subject #%d is %s\n", i+1, subject_names[i]);
}
return 0;
}
22
Standard Functions for Strings
▪ Declared in <string.h>
▪ Common functions
Function Uses
strlen() computes string's length
strcpy() copies a string to another
strcat() Concatenates (joins) two strings
strcmp() compares two strings
strlwr() converts string to lowercase
strupr() converts string to uppercase
23
Practical time
24
Declaring and Initializing Arrays
Manage the daily sales figures for a week.
25
Declaring and Initializing Arrays
#include <stdio.h>
int main() {
return 0;
26
Accessing Array Elements
Practical Task: Find the total sales and the best sales day of the week.
27
Accessing Array Elements
#include <stdio.h>
int main() {
float dailySales[7] = {250.50, 310.00, 190.75, 450.00, 500.25, 600.00, 200.50};
float totalSales = 0.0;
float maxSales = dailySales[0];
int bestDay = 1;
return 0;
}
28
Arrays and Addresses
Practical Task: Show that the array name points to the first element and that elements are stored contiguously.
29
Arrays and Addresses
#include <stdio.h>
int main() {
int grades[5] = {88, 92, 75, 98, 85};
return 0;
}
30
Passing Arrays to Functions
Practical Task: Create a reusable function to print any integer array, promoting modular code.
31
Passing Arrays to Functions
#include <stdio.h>
int main() {
int studentScores[5] = {88, 92, 75, 98, 85};
int sensorReadings[3] = {102, 105, 99};
return 0;
}
32
Returning Arrays from Functions
Practical Task: A function that generates a sequence of numbers (e.g., the first 5 even numbers) and returns it.
Note: In C, you return a pointer to an array. For this to be safe, the array must exist after the function returns. The best way is to
use dynamic memory allocation (malloc ).
33
Returning Arrays from Functions
#include <stdio.h>
#include <stdlib.h> // Needed for malloc
return evens_array;
}
int main() {
int count = 5;
int* myEvens = generate_evens(count);
if (myEvens != NULL) {
printf("First %d even numbers: ", count);
for (int i = 0; i < count; i++) {
printf("%d ", myEvens[i]);
}
printf("\n");
// IMPORTANT: Free the memory when you are done with it!
free(myEvens);
}
return 0;
} 34
String as a Character Array
Practical Task: Get a user's name and greet them.
35
String as a Character Array
#include <stdio.h>
int main() {
char userName[30]; // Declare a char array to hold the string
return 0;
}
36
String Library Functions
Practical Task: A simple username/password validation program.
37
String Library Functions
#include <stdio.h>
#include <string.h> // Include the string library
int main() {
char saved_password[] = "Secret123";
char user_input[50];
return 0;
}
38
2D Array for a Tic-Tac-Toe Board
Concept: Accessing and modifying elements in a 2D array.
Task: Create and display a Tic-Tac-Toe board, then let a player make a move.
39
2D Array for a Tic-Tac-Toe Board
#include <stdio.h>
int main() {
// Initialize the board with empty spaces
char board[3][3] = {
{' ', ' ', ' '},
{' ', ' ', ' '},
{' ', ' ', ' '}
};
return 0; 40
}
Passing Array to a Function for
Modification
Concept: Arrays are passed "by reference" (as pointers), so functions can modify the original array.
41
Passing Array to a Function for
Modification
#include <stdio.h>
int main() {
int my_numbers[5] = {1, 5, 10, 15, 20};
return 0;
}
42
Array of Strings for a Simple
Database
Concept: Using a 2D char array to store a list of strings, like a simple in-memory database.
Task: Store a list of student names and implement a simple search function.
43
Array of Strings for a Simple
Database
#include <stdio.h>
#include <string.h> // For strcmp()
int main() {
// An array of 4 strings, each can be up to 29 chars + null terminator
char students[4][30] = {
"Nguyen Van An",
"Tran Thi Binh",
"Le Hoang Cuong",
"Pham My Duyen"
};
char search_name[30];
int found = 0; // 0 means false
if (!found) {
printf("Student '%s' not found.\n", search_name);
}
44
return 0;
}
String Manipulation with Library
Functions
Concept: Using <string.h> to build a new string from parts of others.
Task: Create a full name by combining a first name and a last name, separated by a space.
45
String Manipulation with Library
Functions
#include <stdio.h>
#include <string.h> // For strcpy, strcat
int main() {
char first_name[] = "Minh";
char last_name[] = "Nguyen";
// Allocate enough space for both names, a space, and the null terminator
char full_name[50];
return 0;
}
46
Using an Array to Count Frequencies
Concept: A powerful technique where the index of an array represents a value, and the content at that index represents its count.
Task: Count the frequency of each digit (0-9) in a long number given as a string.
47
Using an Array to Count Frequencies
#include <stdio.h>
#include <string.h>
int main() {
char number_string[] = "9870981239870";
48
Scalar Multiplication
Linear Algebra Concept: Multiplying a matrix by a single number (a scalar). Every element in the matrix is multiplied by that
number.
49
Scalar Multiplication
#include <stdio.h> int main() {
int matrix[ROWS][COLS] = {
#define ROWS 2 {1, 2, 3},
#define COLS 3 {4, 5, 6}
};
// Function to print a matrix
void print_matrix(int matrix[ROWS][COLS]) { int scalar = 3;
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) { printf("Original Matrix:\n");
printf("%4d ", matrix[i][j]); // %4d print_matrix(matrix);
for better alignment
} // Call the function to modify the matrix
printf("\n"); scalar_multiply(matrix, scalar);
}
} printf("\nMatrix after multiplying by %d:\n"
,
scalar);
// Function to perform scalar multiplication print_matrix(matrix);
// It modifies the original matrix passed to it
void scalar_multiply(int matrix[ROWS][COLS], int return 0;
scalar) { }
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
matrix[i][j] = matrix[i][j] * scalar;
}
}
}
50
Dot Product of Two Vectors
Linear Algebra Concept: The dot product (or scalar product) of two vectors is a fundamental operation. For vectors
A=[a1,a2,…,an] and B=[b1,b2,…,bn], the dot product is …
C Programming Concept: A function that takes two 1D arrays, performs a calculation, and returns a single value.
51
Dot Product of Two Vectors
#include <stdio.h>
#define SIZE 4
return result;
}
int main() {
float vectorA[SIZE] = {1.0, 2.0, 3.0, 4.0};
float vectorB[SIZE] = {5.0, 6.0, 7.0, 8.0};
return 0;
}
52
Matrix-Vector Multiplication
Linear Algebra Concept: Multiplying a matrix by a vector. If
A is an m×n matrix and v n×1 vector, the result is an m×1 vector. Each element of the result is the dot product of a row from the
matrix and the vector.
C Programming Concept: Combining all previous concepts: 2D arrays, 1D arrays, and functions.
53
Matrix-Vector Multiplication
#include <stdio.h> int main() {
int matrix[ROWS][COLS] = {
#define ROWS 2 {1, 2, 3}, // Row 0
#define COLS 3 {4, 5, 6} // Row 1
};
// Function to perform Matrix-Vector
multiplication int vector[COLS] = {10, 20, 30};
// It takes a matrix, a vector, and stores the
result in another vector int result_vector[ROWS];
void matrix_vector_mult(int matrix[ROWS][COLS],
int vector[COLS], int result_vector[ROWS]) { // Call the function to perform the
calculation
for (int i = 0; i < ROWS; i++) { matrix_vector_mult(matrix, vector,
result_vector[i] = 0; // Initialize result_vector);
result for this row to 0
// Result[0] = (1*10) + (2*20) + (3*30) = 10
for (int j = 0; j < COLS; j++) { + 40 + 90 = 140
// This is essentially a dot product // Result[1] = (4*10) + (5*20) + (6*30) = 40
of a matrix row and the vector + 100 + 180 = 320
result_vector[i] += matrix[i][j] *
vector[j]; printf("Result of Matrix * Vector is:\n");
} printf("[%d]\n", result_vector[0]);
} printf("[%d]\n", result_vector[1]);
}
return 0;
}
54