2. New Stuff...
• We can find the difference between average
and the number of accidents on a particular
day only after reading all numbers from the
user
• So data has to be stored
• Same type of data is to be stored
• Number of items not known prior
• Best choice would be using arrays in C
• Array - Can store a fixed-size sequential
collection of elements of the same type
3. Arrays in C
• Consist of contiguous memory locations
• lowest address corresponds to the first
element
• highest address to the last element
• Array indices start with zero
• The elements have indices from 0 to ‘n-1’
• Similar to list in Python but homogenous
4. Declaration of Arrays in C
• type arrayName [ arraySize ];
Example : double balance[10];
Initializing Arrays
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
(or)
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
7. Cannot assign one array to other
int a[] = {0, 1, 2}; // ok: array of ints
int a2[] = a; // error: cannot initialize one array
with another
int main()
{
array_size = 3;
int a3[array_size];
// ok: but elements are uninitialized!
a3 = a; // error: cannot assign one array to
another
return 0;
}
8. • Arrays have 0 as the first index not 1. In this
example, mark[0]
• If the size of an array is n, to access the last
element, (n-1) index is used. In this
example, mark[4]
• Suppose the starting address of mark[0] is
2120d. Then, the next address, a[1], will be
2124d, address of a[2] will be 2128d and so
on. It's because the size of a float is 4 bytes.
10. Input the element
• Take input from the user and insert element
for(i=0; i<n; ++i)
{
printf("Enter number:”);
scanf("%d", &marks[i]);
}
11. #include <stdio.h>
int main()
{ int marks[10], i, n, sum = 0, average;
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i]; // sum= sum+marks[i];
}
average = sum/n;
printf("Average = %d", average);
return 0;
}
12. Problems
• C Program to Find Largest Element of an Array
• C Program to Calculate Standard Deviation
• Write a program to insert an element in the
given array given the element and location.
• Write a C program to add all elements in an
array.
• Write a C program to print the reverse of an
array
13. Compare List and Arrays
List Arrays
Can have mixed type of elements Can have only one type
of element
Number of elements in list need
not be specified
L = []
Size has to be specified
during declaration
int a[10];
Elements are accessed by
subscript operator L[0], L[1]...
Same way
a[0], a[1], a[2],...
Size is dynamic, increases when
elements are added and decreases
when removed
Size is static
Have predefined functions such as
len, count, index etc
No such functions
14. String Array
• Strings are actually one-dimensional array of
characters terminated by a nullcharacter '0'.
Thus a null-terminated string contains the
characters that comprise the string followed by
a null.
• The following declaration and initialization create
a string consisting of the word "Hello".
• char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'};
You can write the above statement as follows
• char greeting[] = "Hello";
15. • The C compiler automatically places the '0' at
the end of the string when it initializes the array.
17. Sr.No. Function & Purpose
1 strcpy(s1, s2);
Copies string s2 into string s1.
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if
s1<s2; greater than 0 if s1>s2.
5 strchr(s1, ch);
Returns a pointer to the first occurrence of character
ch in string s1.
6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2
in string s1.
C supports a wide range of functions that manipulate null-terminated strings −
18.
19.
20. Strings in C
• No data type string
• Represented as array of characters
21. Character Arrays Are Special
• Can be initialized with either a list of comma-
separated character literals enclosed in braces
or a string literal
• Two forms are not equivalent
• String literal contains an additional
terminating null character
22. Strcpy
• used to copy a string and can be as
strcpy(destination, source)
• Will not perform any boundary checking, and
thus there is a risk of overrunning the strings
23. Strcmp
• used to compare two strings and can be used
as strcmp(str1, str2)
• If the first string is greater than the second
string a number greater than null is returned.
• If the first string is less than the second string
a number less than null is returned.
• If the first and the second string are equal a
null is returned.
24. strcat
• concatenates a string onto the end of the
other string and the resultant string is
returned
• strcat() will not perform any boundary
checking, and thus there is a risk of
overrunning the strings.
25. strlen
• returns the length of a string
• All characters before the null termination
26. Row Major Ordering of 2 D Arrays
• Elements in the first row are placed followed by
elements of second row and so on
• Contiguous memory allocation is done and address
of first byte of memory is stored in the name of the
array
• Address of nth element in an array named as a (i.e.)
a[n], is determined as: (a+n*b) where b is the
number of bytes allocated for the data type
27. 2D Array
• In C programming, you can create an array of arrays
known as multidimensional array. For example,
float x[3][4];
• Here, x is a two-dimensional (2d) array. The array can
hold 12 elements
28. Initialization of a two dimensional array
• // Different ways to initialize two dimensional
array
• int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
• int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
• int c[2][3] = {1, 3, 0, -1, 5, 9};
29. • // C program to store temperature of two cities for a week and display it.
#include <stdio.h>
const int CITY = 2; const int WEEK = 7;
int main()
{ int temperature[CITY][WEEK];
for (int i = 0; i < CITY; ++i)
{ for(int j = 0; j < WEEK; ++j)
{ printf("City %d, Day %d: ", i+1, j+1);
scanf("%d", &temperature[i][j]);
} }
printf("nDisplaying values: nn");
for (int i = 0; i < CITY; ++i)
{ for(int j = 0; j < WEEK; ++j)
{ printf("City %d, Day %d = %dn", i+1, j+1, temperature[i][j]);
} }
return 0;
}
30. Problems
• Write a C program to find the transpose of the matrix
• Write a C program to sum the right and left diagonal of
the matrix and print it separately
• Write a C program to sum the outer array matrix
element ,given square matrix.
• Write a C program to sum of each row and finally sum
all the row sum.
• Write a C program to perform addition of two matrix.
• Write a C program to find the multiplication of two
matrix. Check for the dimension of the matrix if it is
possible to perform multiplication or not.
31. Multi dimensional Arrays
• store the enrolment data for a college
• assume that the college offers 100 ( MAXCRS )
courses at five different campuses
• Students from any of the four years can opt for the
courses