0% found this document useful (0 votes)
3 views54 pages

Lecture5-Array String

This document is a lecture on basic programming concepts focusing on arrays and strings, presented by Dr. Nguyen Hoang Ha, Dr. Nguyen Minh Huong, and Dr. Tong Si Son. It covers the definition, declaration, initialization, and manipulation of arrays, as well as string handling in C programming. Practical examples are provided to illustrate how to compute averages, pass arrays to functions, and utilize string library functions.

Uploaded by

giaphonghoang123
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)
3 views54 pages

Lecture5-Array String

This document is a lecture on basic programming concepts focusing on arrays and strings, presented by Dr. Nguyen Hoang Ha, Dr. Nguyen Minh Huong, and Dr. Tong Si Son. It covers the definition, declaration, initialization, and manipulation of arrays, as well as string handling in C programming. Practical examples are provided to illustrate how to compute averages, pass arrays to functions, and utilize string library functions.

Uploaded by

giaphonghoang123
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

VIETNAM ACADEMY OF SCIENCE AND TECHNOLOGY

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF HANOI

BASIC PROGRAMMING
Lecture 5: Array and String

Dr. NGUYEN Hoang Ha


Dr. NGUYEN Minh Huong
Dr. TONG Si Son

ĐO TẠO NGHIÊN ỨU SÁNG TO


1
Lecture 5:

▪ 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?

How to store a list of 10 students’ marks and compute the


average?
▪ Using Individual variables:
▪ Declaring 10 individual variables
▪ Computing from 10 individual variables
🡪 cumbersome, repetitive writing

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

printf("\nEnter the 10 numbers:\n"); /* Prompt for the input */


scanf("%d", &mark1);
scanf("%d", &mark2);
...
scanf("%d", &mark10);

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

Number 1 Number 2 Number 3 Number 4 Number 5

▪ Definition of Array: a data structure storing a fixed-size


sequential collection of elements of the same type.

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

▪ Initializing with array size

int A[5] = {1, 2, 3, 4, 5};

Number of elements matches array size

▪ If array size is omitted, an array just big enough to hold the


initialization is created
int A[] = {1, 2, 3, 4, 5};

8
Accessing Array Elements

▪ To access an element, you should point out:


▪ Array name
▪ The location of the element in the array

▪ One-dimensional arrays
// array declaration 0 1 2 3 4
int A[5] = {1, 2, 3, 4, 5}; 1 2 3 4 5

for (int i =0; i<5; i++)


{
printf("Element %d in the array is %d \n", i, A[i]);
}

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

▪ 3-D arrays: for (int i =0; i<2; i++)


{
// array declaration printf("block %d \n",i);
int A[2][2][3] = { for (int j =0; j<2; j++)
{ {
for (int k = 0; k<3; k++)
{1,2,3},
{
{4,5,6}
printf("%d \t", A[i][j][k]);
},
}
{
printf("\n");
{7,8,9},
}
{10,11,12}
}
}
};

11
Arrays and Address

▪ Array name is a pointer to the first element of the array


(detailed in the next session)
▪ 1-D array:
int A[5];

A[0] A[1] A[2] A[3] A[4]

1 2 3 4 5

Memory area
A

12
Arrays and Address

▪ 2-D array:
int A[2][3];//2 rows, 3 columns

A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][3]

1 2 3 4 5 6

A, A[0] A[1] Memory area

13
Arrays and Address
▪ Print out address of array elements
int A[2][3] = {
{1,2,3},
{4,5,6}
};

for (int j =0; j<2; j++)


{
for (int k = 0; k<3; k++)
{
printf("%p \t", &A[j][k]);
}
printf("\n");
}

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

/* Read the ten numbers to be averaged */


for(int i = 0; i < count; i++)
{
printf("%2d> ",i+1);
scanf("%d", &numbers[i]); /* Read a number */
sum += numbers[i]; /* Add it to sum */
}

average = (float)sum/count; /* Calculate the average*/


printf("\nAverage of the ten numbers entered is: %f\n", average);
return 0; 15
}
Passing Arrays to Functions

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

sum += numbers[i]; float average = 0.0f; /* Average of the numbers */

printf("\nEnter the 10 numbers:\n"); /* Prompt for the input */


if(size >0)

avg = (float)sum/size; /* Read the ten numbers to be averaged */

else for(int i = 0; i < count; i ++)

avg = -1;//can't compute the average {

return avg; printf("%2d> ",i+1);

scanf("%d", &numbers[i]); /* Read a number */


}
}

average = compute_average (numbers, count);

printf("\nAverage of these numbers entered is: %f\n", average);

return 0;

}
17
Returning Arrays from Functions

int* increase_elements(int arr[], int size)


{
for (int i =0;i<size;i++)
{
arr[i] = arr[i] + 1;
}
return arr;
}

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

▪ Average of an array of numbers


▪ List of students

24
Declaring and Initializing Arrays
Manage the daily sales figures for a week.

25
Declaring and Initializing Arrays
#include <stdio.h>

int main() {

// Declare and initialize an array to hold sales for 7 days

float dailySales[7] = {250.50, 310.00, 190.75, 450.00, 500.25, 600.00, 200.50};

printf("Sales for the week:\n");

// Days are often 1-7, but array indices are 0-6

printf("Day 1 (Mon): %.2f\n", dailySales[0]);

printf("Day 5 (Fri): %.2f\n", dailySales[4]);

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;

// Use a loop to access each element


for (int i = 0; i < 7; i++) {
// Accumulate total
totalSales += dailySales[i];

// Find the best day


if (dailySales[i] > maxSales) {
maxSales = dailySales[i];
bestDay = i + 1; // +1 to convert index to day number
}
}

printf("Total weekly sales: %.2f\n", totalSales);


printf("Best sales day was Day %d with %.2f\n", bestDay, maxSales);

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

// 'grades' itself holds the address of the first element


printf("Address of the whole array (grades): %p\n"
, grades);

// '&grades[0]' explicitly gets the address of the first element


printf("Address of the first element (&grades[0]): %p\n\n"
, &grades[0]);

printf("Addresses of each element:\n");


for (int i = 0; i < 5; i++) {
// &grades[i] gets the address of the i-th element
printf(" Address of grades[%d]: %p\n", i, &grades[i]);
}
// You will notice the addresses increase by 4 bytes each time (for int)

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>

// A function that takes an array and its size as input


// Note: 'int arr[]' is the preferred way to show it's an array
void print_array(int arr[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
printf("%d", arr[i]);
if (i < size - 1) {
printf(", "); // Add comma, but not for the last element
}
}
printf("]\n");
}

int main() {
int studentScores[5] = {88, 92, 75, 98, 85};
int sensorReadings[3] = {102, 105, 99};

printf("Student Scores: ");


print_array(studentScores, 5); // Pass the first array

printf("Sensor Readings: ");


print_array(sensorReadings, 3); // Reuse the function for a different array

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

// This function returns a pointer to an integer array (int*)


int* generate_evens(int n) {
// Allocate memory on the heap so it persists after the function returns
int* evens_array = (int*)malloc(n * sizeof(int));

if (evens_array == NULL) return NULL; // Safety check

for (int i = 0; i < n; i++) {


evens_array[i] = (i + 1) * 2; // Generate even numbers: 2, 4, 6...
}

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

printf("Please enter your name: ");

// scanf reads a string into the char array


// No '&' is needed for string arrays with scanf
scanf("%s", userName);

printf("Hello, %s! Welcome to the program.\n"


, userName);

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

printf("Enter password: ");


scanf("%s", user_input);

// Use strcmp() to compare strings


// strcmp returns 0 if the strings are identical
if (strcmp(user_input, saved_password) == 0) {
printf("Access Granted.\n");

// Use strlen() to get the length


printf("Your password is %zu characters long.\n"
, strlen(user_input));
} else {
printf("Access Denied. Incorrect password.\n"
);
}

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>

void print_board(char board[3][3]) {


printf("\n");
for (int i = 0; i < 3; i++) {
printf(" %c | %c | %c \n", board[i][0], board[i][1], board[i][2]);
if (i < 2) {
printf("---|---|---\n");
}
}
printf("\n");
}

int main() {
// Initialize the board with empty spaces
char board[3][3] = {
{' ', ' ', ' '},
{' ', ' ', ' '},
{' ', ' ', ' '}
};

printf("Initial Tic-Tac-Toe Board:");


print_board(board);

// Player X makes a move at row 1, column 2 (indices 0, 1)


board[0][1] = 'X';

// Player O makes a move at the center (indices 1, 1)


board[1][1] = 'O';

printf("Board after a few moves:");


print_board(board);

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.

Task: Write a function that doubles every element in an integer array.

41
Passing Array to a Function for
Modification
#include <stdio.h>

void double_elements(int arr[], int size) {


for (int i = 0; i < size; i++) {
// This modification affects the ORIGINAL array in main()
arr[i] = arr[i] * 2;
}
}

void print_array(int arr[], int size) {


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int my_numbers[5] = {1, 5, 10, 15, 20};

printf("Original array: ");


print_array(my_numbers, 5);

// Pass the array to the function that modifies it


double_elements(my_numbers, 5);

printf("Array after doubling: ");


print_array(my_numbers, 5); // The original array has changed!

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

printf("Enter name to search: ");


// fgets is safer than scanf for names with spaces
fgets(search_name, 30, stdin);
// Remove the newline character that fgets adds
search_name[strcspn(search_name, "\n")] = 0;

// Iterate through the array of strings


for (int i = 0; i < 4; i++) {
if (strcmp(students[i], search_name) == 0) {
printf("Found '%s' at index %d.\n", search_name, i);
found = 1;
break;
}
}

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

// 1. Copy the first name into full_name


strcpy(full_name, first_name); // full_name is now "Minh"

// 2. Concatenate (append) a space


strcat(full_name, " "); // full_name is now "Minh "

// 3. Concatenate the last name


strcat(full_name, last_name); // full_name is now "Minh Nguyen"

printf("First Name: %s\n", first_name);


printf("Last Name: %s\n", last_name);
printf("Full Name: %s\n", full_name);

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

// An array to store counts for digits 0 through 9


// All elements are initialized to 0
int frequency[10] = {0};

// Iterate through the string


for (int i = 0; i < strlen(number_string); i++) {
char current_char = number_string[i];

// Convert the character '0'-'9' to an integer 0-9


int digit = current_char - '0';

// Increment the count at that digit's index


if (digit >= 0 && digit <= 9) {
frequency[digit]++;
}
}

// Print the results


printf("Frequency of each digit in '%s':\n", number_string);
for (int i = 0; i < 10; i++) {
printf("Digit %d appeared %d times.\n", i, frequency[i]);
}

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.

C Programming Concept: A function that takes a 2D array and modifies it in place.

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

// Function to calculate the dot product of two vectors


// It returns a single value (the dot product)
float dot_product(float vec1[], float vec2[], int size) {
float result = 0.0;

for (int i = 0; i < size; i++) {


result += vec1[i] * vec2[i];
}

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

// Dot Product = (1*5) + (2*6) + (3*7) + (4*8) = 5 + 12 + 21 + 32 = 70

float result = dot_product(vectorA, vectorB, SIZE);

printf("Vector A: [1.0, 2.0, 3.0, 4.0]\n"


);
printf("Vector B: [5.0, 6.0, 7.0, 8.0]\n"
);
printf("Dot Product of A and B is: %.2f\n", result);

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

You might also like