0% found this document useful (0 votes)
29 views62 pages

Module 3

Uploaded by

Swaraj Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views62 pages

Module 3

Uploaded by

Swaraj Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

MODULE 3

Arrays and strings


CONTENTS
• Arrays:
• one dimensional and multi-dimensional array,
• programs on arrays.
• Strings
• Functions
• Pointers
UNDERSTANDING WHAT AN ARRAY IS?
main( )
{
int x ;
x=5; OUTPUT:
X=10
x = 10 ;
printf ( "\nx = %d", x ) ;
}
Suppose we wish to arrange the percentage marks obtained by 100 students in
ascending order.
Two ways:
Construct 100 variables to store percentage marks obtained by 100 different
students, i.e. each variable containing one student’s marks.
Construct one variable (called array or subscripted variable) capable of
storing or holding all the hundred values.
An array is a collective name given to a group of ‘similar quantities’.
all ints, or all floats, or all chars
the array of characters is called a ‘string’
Definition:
• An array is a collection of items stored at contiguous memory locations.
• In C, arrays are used to store similar types of elements.

Application in Embedded Systems:


• Arrays are used in embedded systems for handling multiple similar data efficiently, such as sensor readings,
buffer storage, and lookup tables.
One-Dimensional Arrays
Syntax and Declaration:

int arr[10]; // Declares an array of 10 integers

Example:

arr[0] = 1; // Sets the first element to 1

Array Declaration Syntax:

type arrayName[arraySize];

#define NUM_SENSORS 4
int sensorReadings[NUM_SENSORS]; //Array for storing sensor v

In embedded C, the size of arrays is often determined by the number of physical components, like sensors or
actuators, connected to the microcontroller.
Array Initialization Syntax

type arrayName[arraySize] = {val1, val2, . . . , valN};

Example: Setting Initial Sensor States

int sensorStates[NUM_SENSORS] = {0};


// Initialize all to 0

Embedded Systems Context

Initialization is crucial in embedded systems to ensure that memory


has defined values before use, particularly for registers or state variables.
Accessing Array Elements

Accessing Elements Syntax:


Elements in an array are accessed using their index.
arrayName[index]

Example:
int array[5] = {1, 2, 3, 4, 5};
int firstElement = array[0]; // Access fi rst element

• When accessing array elements in embedded systems, ensure that the


index is within the bounds to prevent undefined behavior and potential
system crashes.
Iterating Over Arrays

To perform operations on each element in an array, a loop is used.


for (int i = 0; i < arraySize; i++) {
// Code to execute
}

Example:
int sum = 0;
for (int i = 0; i < 5; i++)
{
sum += array[i];
}
Example: Summing Elements in an Array

int main() {
int values[5] = {5, 10, 15, 20, 25};
int sum = 0;
for (int i = 0; i < 5; i++)
{ sum += values[i];
}
printf("Sum of values: %d\n", sum);
return 0;
}
ex2.c
Write a program to find average marks obtained by a class of 30 students in a test.

main( )
{
int avg, sum = 0 ;
int i ;
int marks[30] ; /* array declaration */
for ( i = 0 ; i <= 29 ; i++ )
{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ; /* store data in array */
}
for ( i = 0 ; i <= 29 ; i++ )
sum = sum + marks[i] ; /* read data from an array*/
avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ;
}
ex1.c
Multi-Dimensional Arrays--- arrays
within arrays.,
Syntax and Declaration:
type arrayName[size1][size2];
Example:
int multi Arr[3][4]; // Declares a 3x4 array
multi Arr[0][1] = 5; // Element at row 0, column 1 to 5
Initializing Multi-Dimensional Arrays
Initialization Syntax:
type arrayName[size1][size2] = {{val1, val2}, {...}};
Example:
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
• Use row and column indices to access elements in a multi-dimensional array.
arrayName[row][column]
int value = matrix[1][2];
// Accesses the element at second row-third column
• For embedded systems, ensure the indices are within bounds to maintain
system stability.
Nested Loops and Multi-Dimensional Arrays
• Nested loops allow iteration over rows and columns of a multi-dimensional array.
for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) {
// Access array elements
}
}
• Example:
for(int i = 0; i < 2; i++)
{ for(int j = 0; j < 3; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
• In embedded systems, nested loops are commonly used for scanning or controlling a grid of sensors or
actuators.
Example
• Matrix addition ------ matrix_add_sub.c
#include <stdio.h> // add the matrices
int main() { for (i = 0; i < m; i++) {
int m, n, i, j; for (j = 0; j < n; j++) {
printf("Enter the number of rows and columns of the c[i][j] = a[i][j] + b[i][j];
matrices: "); }
scanf("%d%d", &m, &n); }
int a[m][n], b[m][n], c[m][n]; // print the result
printf("Enter the elements of matrix A: \n"); printf("The sum of the two matrices is: \n");
for (i = 0; i < m; i++) { for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) { for (j = 0; j < n; j++) {
scanf("%d", &a[i][j]); printf("%d ", c[i][j]);
} }
} printf("\n");
printf("Enter the elements of matrix B: \n"); }
for (i = 0; i < m; i++) { return 0;
for (j = 0; j < n; j++) { }
scanf("%d", &b[i][j]);
}
}
Arrays in Memory: How C Stores Arrays
Example: Searching an Array
Implementing a Search
Algorithm
A linear search algorithm iterates over an array to find a value.
This is a straightforward example of how to traverse an array with
a loop.

Standard C Code for Linear


iSearch
n t l i n e a r S e a r c h ( i n t a r r [ ] , i n t s i z e , i n t va l u e ) {
for ( i n t i = 0; i < s i z e ; i + + ) {
i f ( a r r [ i ] == va l u e ) return i ;
}
return - 1 ; / / Value not found
}

Embedded C Scenario
Searching through a data array to find a sensor reading that exceeds
a threshold could trigger an event or alert.
Strings in C: A Special Kind of Array

What Are Strings in


C?
In C, strings are arrays of characters terminated by a null character \
0.
Usage in Embedded
Systems
Strings are often used for storing data read from or to be written
to peripherals, like displays in embedded systems.

19/103
Reading and Writing Strings

Using Standard I/O


Functions
s canf (" % s" , s t r ) ;
p r i n tf ( " % s " , s t r ) ;

Embedded C Considerations
In embedded systems, functions like ‘sprintf‘ and ‘sscanf‘ are used
for formatting strings to interact with hardware or protocol
messages.

20/103
Programs on Strings ----- gets()

#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}

#include<stdio.h>
void main()
{
char str[20];
printf("Enter the string? ");
fgets(str, 20, stdin);
printf("%s", str);
}
Programs on Strings ----- puts()

#include<stdio.h>
#include <string.h>
int main(){
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}
String Functions
No. Function Description
1) strlen(string_name) returns the length of string name.

2) strcpy(destination, source) copies the contents of source string to destination


string.
3) strcat(first_string, second_string) concats or joins first string with second string. The
result of the string is stored in first string.

4) strcmp(first_string, second_string) compares the first string with second string. If both
strings are same, it returns 0.

5) strrev(string) returns reverse string.


6) strlwr(string) returns string characters in lowercase.

7) strupr(string) returns string characters in uppercase.


1. String Length: strlen() function

#include<stdio.h> str3.c

#include <string.h>
int main(){
char ch[10]={'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}
2. Copy String: strcpy()
#include<stdio.h>
#include <string.h> str4.c
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}
3. String Concatenation: strcat() str5.c

#include<stdio.h>
#include <string.h>
int main(){
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={'c', '\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
return 0;
}
4. Compare String: strcmp()
str9.c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;
// comparing strings str1 and str2
result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result);
// comparing strings str1 and str3
result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result);
return 0;
}
5. Reverse String: strrev() str7.c

#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
String Palindrome str8.c

int main() // Keep comparing characters


{ // while they are same
char string1[20]; while (h > l) {
// Prompt the user for input if (string1[l++] != string1[h--]) {
printf("Enter a string: "); printf("%s is not a palindrome\n",
scanf("%s", string1); string1);
return 0;
// will return from here
// Start from first and }
// last character of str }
int l = 0; printf("%s is a palindrome\n", string1);
int h = strlen(string1) - 1; return 0;
}
FUNCTIONS
• Functions are reusable blocks of code that perform a specific
task. They help modularize the code, making it more readable
and maintainable.
• Functions in embedded systems are used to encapsulate
hardware control operations, algorithms, and routines.
• Function prototypes are often declared in header files, while
definitions are in source files.
Types of Functions
• Library Functions are the functions which are declared in the C
header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
• User-defined functions are the functions which are created by the C
programmer, so that it can be used many times. It reduces the
complexity of a big program and optimizes the code.
Declaring and Defining Functions

• Function Declaration (Prototype)


void functionName(parameters);
• Function definition:
void functionName(parameters) {
// Code to execute
}
Calling Functions in C
The Return Statement and Return
Types
• Returning Values from Functions
• Functions in C can return a value. The type of the return value must match the
function’s return type.
• Example:
int getSensorData()
{
return sensorValue; // Assume sensorValue is an int
}
• Embedded C application
• Functions that interact with hardware components often return status codes, data
readings, or boolean values indicating success or failure.
Different aspects of function calling
• A function may or may not accept any argument. It may or may not
return any value. Based on these facts, There are four different
aspects of function calls.
• function without arguments and without return value
• function without arguments and with return value
• function with arguments and without return value
• function with arguments and with return value
Function without argument and return
value
#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf(“welcome");
}
#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Function without argument and with
return value
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Function with argument and without
return value
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Function with argument and with
return value
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
int main()
#include <stdio.h>
{
#include <conio.h>
int a[1000],i,n,sum;
int sumofarray(int a[],int n)
printf("Enter size of the array : ");
{
scanf("%d", &n);
int i,sum=0;
printf("Enter elements in array : ");
for(i=0; i<n; i++)
for(i=0; i<n; i++)
{
{
sum+=a[i];
scanf("%d",&a[i]);
}
}
return sum;
sum=sumofarray(a,n);
}
printf("sum of array is :%d",sum);}
C Library Functions
Header Description
file
stdio.h This is a standard input/output header file. It contains all the library functions regarding standard
input/output.
conio.h This is a console input/output header file.
string.h It contains all string related library functions like gets(), puts(),etc.
stdlib.h This header file contains all the general library functions like malloc(), calloc(), exit(), etc.
math.h This header file contains all the math operations related functions like sqrt(), pow(), etc.
time.h This header file contains all the time-related functions.
ctype.h This header file contains all character handling functions.
stdarg.h Variable argument functions are defined in this header file.
signal.h All the signal handling functions are defined in this header file.
setjmp.h This file contains all the jump functions.
locale.h This file contains locale functions.
errno.h This file contains error handling functions.
assert.h This file contains diagnostics functions.
Recursion in C
• Process which comes into existence when a function calls a copy of
itself to work on a smaller problem.
• Any function which calls itself is called recursive function, and such
function calls are called recursive calls.
• A recursive function performs the tasks by dividing it into the
subtasks.
#include <stdio.h> int fact(int n)
int fact (int); {
int main() if (n==0)
{ {
int n,f; return 0;
printf("Enter the number whose factorial you want to cal }
culate?"); else if ( n == 1)
scanf("%d",&n); {
f = fact(n); return 1;
printf("factorial = %d",f); }
} else
{
return n*fact(n-1);
}
}
int fibonacci (int n)
#include<stdio.h> {
int fibonacci(int); if (n==0)
void main () {
{ return 0;
int n,f; }
else if (n == 1)
printf("Enter the value of n?");
{
scanf("%d",&n); return 1;
f = fibonacci(n); }
printf("%d",f); else
} {
return fibonacci(n-1)+fibonacci(n-2);
}
}
Pointers
Address in C
If you have a variable var in your program, &var will give you its address in the
memory.
#include <stdio.h>
int main()
{
int var = 5;
printf("var: %d\n", var);
printf("address of var: %p", &var);
return 0;
}
#include <stdio.h>

int main() {

int age = 25;

printf("%p", &age);

int *ptr = &age;

printf("\n%p", ptr);

return 0;
}
C Pointers
• Pointers (pointer variables) are special variables that are used to store addresses rather
than values.
Pointer Syntax
• int* p;
• int *p1;
• int * p2;
• int* p1, p2; //Here, we have declared a pointer p1 and a normal variable p2.
• Assigning addresses to Pointers
• int* pc, c;
• c = 5;
• pc = &c;
• Here, 5 is assigned to the c variable. And, the address of c is assigned to the pc pointer.
Get Value of Thing Pointed by Pointers
• To get the value of the thing pointed by the pointers, we use the * operator.
• For example:
• int* pc, c;
• c = 5;
• pc = &c;
• printf("%d", *pc); // Output: 5
• Here, the address of c is assigned to the pc pointer. To get the value stored
in that address, we used *pc.
Changing Value Pointed by Pointers
Let's take an example.

int* pc, c;
c = 5;
pc = &c;
c = 1;
printf("%d", c); // Output: 1
printf("%d", *pc); // Ouptut: 1
• We have assigned the address of c to the pc pointer.
• Then, we changed the value of c to 1.
• Since pc and the address of c is the same, *pc gives us 1.
int* pc, c;
c = 5;
pc = &c;
*pc = 1;
printf("%d", *pc); // Ouptut: 1
printf("%d", c); // Output: 1

We have assigned the address of c to the pc pointer.


Then, we changed *pc to 1 using *pc = 1;. Since pc and the address of c is the same, c will be equal to 1.
int* pc, c, d;
c = 5;
d = -15;

pc = &c; printf("%d", *pc);


// Output: 5
pc = &d; printf("%d", *pc);
// Ouptut: -15

Initially, the address of c is assigned to the pc pointer using pc = &c;. Since c is 5, *pc gives us 5.
Then, the address of d is assigned to the pc pointer using pc = &d;. Since d is -15, *pc gives us -15.
#include <stdio.h> *pc = 2;
int main() printf("Address of c: %p\n", &c);
{ printf("Value of c: %d\n\n", c);
int* pc, c; return 0;
}
c = 22;
Address of c: 2686784
printf("Address of c: %p\n", &c);
Value of c: 22
printf("Value of c: %d\n\n", c);

Address of pointer pc: 2686784


pc = &c;
Content of pointer pc: 22
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc);
Address of pointer pc: 2686784
Content of pointer pc: 11
c = 11;
printf("Address of pointer pc: %p\n", pc);
Address of c: 2686784
printf("Content of pointer pc: %d\n\n", *pc);
Value of c: 2
Common mistakes when working with pointers

1. int c, *pc;
// pc is address but c is not
2. pc = c; // Error
// &c is address but *pc is not
3. *pc = &c; // Error
// both &c and pc are addresses
4. pc = &c; // Not an error
// both c and *pc are values
5. *pc = c; // Not an error
Arrays & Pointers:
An array is a block of sequential data.

Write a program to print addresses of array elements.

#include <stdio.h> From the above example, it is clear that &x[0] is equivalent
int main() { to x. And, x[0] is equivalent to *x.
int x[4]; Similarly,
int i;
 &x[1] is equivalent to x+1 and x[1] is equivalent to *(x+1).
for(i = 0; i < 4; ++i) {  &x[2] is equivalent to x+2 and x[2] is equivalent to *(x+2).
printf("&x[%d] = %p\n", i, &x[i]);
 ...
}
 Basically, &x[i] is equivalent to x+i and x[i] is equivalent
printf("Address of array x: %p", x); to *(x+i).

return 0;
}
Example 1: Pointers and Arrays Here, we have declared an array x of
#include <stdio.h> 6 elements. To access elements of the
int main() { array, we have used pointers.
int i, x[6], sum = 0;
printf("Enter 6 numbers: ");

for(i = 0; i < 6; ++i) {


// Equivalent to scanf("%d", &x[i]);
scanf("%d", x+i);
// Equivalent to sum += x[i]
sum += *(x+i); }

printf("Sum = %d", sum);


return 0;
}
#include <stdio.h>
int main() {
int x[5] = {1, 2, 3, 4, 5};
int* ptr;
// ptr is assigned the address of the third element
ptr = &x[2];

printf("*ptr = %d \n", *ptr); • &x[2], the address of the third element, is


assigned to the ptr pointer. Hence, 3 was
//3
displayed when we printed *ptr.
printf("*(ptr+1) = %d \n", *(ptr+1)); • And, printing *(ptr+1) gives us the fourth
//4 element. Similarly, printing *(ptr-1) gives us the
second element.
printf("*(ptr-1) = %d", *(ptr-1));
//5
return 0;
}
C Pass Addresses and Pointers
• In C programming, it is also possible to pass addresses as arguments to functions.
• To accept these addresses in the function definition, we can use pointers. It's because pointers are used
to store addresses.
#include <stdio.h> void swap(int* n1, int* n2)
void swap(int *n1, int *n2); {
int temp;
int main()
{ temp = *n1;
int num1 = 5, num2 = 10; *n1 = *n2;

// address of num1 and num2 is passed *n2 = temp;


swap( &num1, &num2); }

printf("num1 = %d\n", num1);


printf("num2 = %d", num2);
return 0;
}
#include <stdio.h>
• Here, the value stored at p, *p, is 10 initially.
• We then passed the pointer p to the addOne()
void addOne(int* ptr) { function.
(*ptr)++; // adding 1 to *ptr
• The ptr pointer gets this address in the addOne()
} function.
• Inside the function, we increased the value stored at
int main() ptr by 1 using (*ptr)++;.
{ • Since ptr and p pointers both have the same address,
int* p, i = 10; *p inside main() is also 11.
p = &i;
addOne(p);

printf("%d", *p);
// 11
return 0;
}

You might also like