0% found this document useful (0 votes)
14 views12 pages

C Programming: Arrays and Strings Guide

This document provides an introduction to C programming, focusing on two-dimensional and three-dimensional arrays, strings, and various matrix operations. It includes syntax for declaring arrays, memory representation, passing rows to functions, reading and displaying matrices, and performing operations like transposition and multiplication. Additionally, it covers string handling and includes example C programs for sorting, counting vowels and consonants, and summing diagonal elements of a matrix.

Uploaded by

Kangana W. M
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)
14 views12 pages

C Programming: Arrays and Strings Guide

This document provides an introduction to C programming, focusing on two-dimensional and three-dimensional arrays, strings, and various matrix operations. It includes syntax for declaring arrays, memory representation, passing rows to functions, reading and displaying matrices, and performing operations like transposition and multiplication. Additionally, it covers string handling and includes example C programs for sorting, counting vowels and consonants, and summing diagonal elements of a matrix.

Uploaded by

Kangana W. M
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

[INTRODUCTION TO C PROGRAMMING - BESCK104E] saleem_ece@[Link].

in

MODULE 4
1. Write the syntax for declaring two dimensional arrays with suitable example.
A two dimensional array is declared as:
data_type array_name[row_size][column_size];
Therefore, a two dimensional m x n array is an array that contains m x n data elements
and each element is accessed using two subscripts, i and j where i<=m and j<=n.
For example, if we want to store the marks obtained by 3 students in 5 different subjects,
then we can declare a two-dimensional array as
int marks[3][5];
A two-dimensional array called ‘marks’ is declared that has m(3) rows and n(5) columns.
The first element of the array is denoted by marks[0][0], second element as marks[0][1], and
so on. Here, marks[0][0] stores the marks obtained by the first student in the first subject,
marks[1][0] stores the marks obtained by the second student in the first subject, and so on.
2. Demonstrate the representation of 2D array in memory with a suitable example.
For example, if we want to store the marks obtained by 3 students in 5 different subjects,
then we can declare a two-dimensional array as
int marks[3][5];
A two-dimensional array called ‘marks’ is declared that has m(3) rows and n(5) columns.
The first element of the array is denoted by marks[0][0], second element as marks[0][1], and
so on. Here, marks[0][0] stores the marks obtained by the first student in the first subject,
marks[1][0] stores the marks obtained by the second student in the first subject, and so on.
The memory representation of above two dimensional array is shown below:

Row / Column Column 0 Column 1 Column 2 Column 3 Column 4

Row 0 marks[0][0] marks[0][1] marks[0][2] marks[0][3] marks[0][4]

Row 1 marks[1][0] marks[1][1] marks[1][2] marks[1][3] marks[1][4]

Row 2 marks[2][0] marks[2][1] marks[2][2] marks[2][3] marks[2][4]

Figure: Memory representation of two dimensional array for int marks[3][5];


If we initialize a two-dimensional array ‘marks’ as:
int marks[2][3] = {90, 87, 78, 68, 62, 71};
Then the memory representation is shown:

MOHAMMED SALEEM | Asst. Prof., Dept. of E & C, PACE 1


[INTRODUCTION TO C PROGRAMMING - BESCK104E] saleem_ece@[Link]

3. Explain how a single row can be passed into a 2D array with an example.
A row of a two-dimensional array can
be passed by indexing the array name
with the row number. When we send
a single row of a two-dimensional
array, then the called function receives
a one-dimensional array. Figure illustrates
how a single row of a two-dimensional array
is passed to the called function.

4. With a neat diagram, Explain three dimensional array. Write a C program to read and
display 2x2x2 array.
Three dimensional array:
A three dimensional m1 x m2 x m3 array is
a collection of m1 * m2 * m3 elements.
Figure shows a three dimensional array
having three pages, four rows and 2 columns.
Program: #include <stdio.h>
int main ( )
{
int i, j, mat[3][3], t_mat [3][3];
printf ( "Enter the elements of the matrix: \n" );
for ( i=0; i<3; i++ )
{
for ( j=0; j<3; j++ )
{
scanf ( "%d", &mat[ i ][ j ] );
} }
printf ( "The elements of the matrix are: \n " );

MOHAMMED SALEEM | Asst. Prof., Dept. of E & C, PACE 2


[INTRODUCTION TO C PROGRAMMING - BESCK104E] saleem_ece@[Link]

for ( i=0; i<3; i++)


{
printf("\n");
for ( j=0; j<3; j++ )
printf ( "\t %d", mat[ i ][ j ] );
}
for ( i=0; i<3; i++)
{
for ( j=0; j<3; j++ )
t_mat[ i ][ j ] = mat[ j ][ i ] ;
}
printf ( " The elements of the transposed matrix are: \n " );
for ( i=0; i<3; i++)
{
printf("\n");
for ( j=0; j<3; j++ )
printf ( "\t %d", t_mat[ i ][ j ] );
}
return 0;
}

5. What are strings? Mention reading strings & writing strings along with their syntax.
In C programming, a string is a sequence of characters terminated with a null character.
This means that, after the last character, a null character (‘\0’) is stored to signify the end
of the character array.
H e l l o \0
For example, char str[ ] = “Hello”; This will be stored as
Reading Strings: If we declare a string by writing
char str [100];
Then str can be read by using three ways:
1. using scanf( ) function

MOHAMMED SALEEM | Asst. Prof., Dept. of E & C, PACE 3


[INTRODUCTION TO C PROGRAMMING - BESCK104E] saleem_ece@[Link]

2. using gets( ) function


3. using getchar( ), getch( ) or getche( ) function repeatedly
Stings can be read using scanf( ) by writing
scanf( "%s", str );
The main drawback with this function is that the function terminates as soon as it finds a
blank space. For example, if the user enters ‘Hello World’, then str will contain only ‘Hello’.
This is because the moment a blank space is encountered, the string is terminated by the
scanf( ) function.
The field width can be specified to indicate the maximum number of characters that can be
read in.
The string can be read by using gets( ) function. The string can be read by writing
gets( str );
gets( ) is a simple function that overcomes the drawbacks of the scanf() function. The gets( )
function takes the starting address of the string which will hold the input. The string
inputted using gets( ) is automatically terminated with a null character.
The string can also be read by calling the getchar( ) function repeatedly to read a sequence
of single characters (unless a terminating character is entered) and simultaneously storing
it in a character array.
Writing Strings: Strings can be displayed on the screen using three ways:
1. using printf( ) function
2. using puts( ) function
3. using putchar( ) function repeatedly
A string can be displayed using printf( ) by writing
printf( "%s", str );
The conversion character ‘s’ is used to output a string. The width and precision
specifications along with %s can also be included. The width specifies the minimum output
field width. If the string is short, extra space is either left padded or right padded. The
precision specifies the maximum number of characters to be displayed. If the string is long,
the extra characters are truncated.
For example,
printf( "%5.3s", str );

MOHAMMED SALEEM | Asst. Prof., Dept. of E & C, PACE 4


[INTRODUCTION TO C PROGRAMMING - BESCK104E] saleem_ece@[Link]

The above statement would print only the first three characters in a total field of five
characters. Also these three characters are right justified in the allocated width. To make
the string left justified, we must use a minus sign. For example,
printf( "%-5.3s", str );
The next method is by using puts() function. The string can be displayed by writing
puts( str );
puts( ) is a simple function that overcomes the drawbacks of the printf() function. The puts(
) function writes a line of output on the screen. It terminates the line with a newline
character ('\n'). It returns an EOF (-1) if an error occurs and returns a positive number on
success.
The strings can also be written by calling the putchar() function repeatedly to print a
sequence of single characters.
6. Write a C program to read and display 3 x 3 matrix.
#include <stdio.h>
int main ( )
{
int i, j, mat[3][3];
printf ( "Enter the elements of the matrix: \n" );
for ( i=0; i<3; i++ )
{
for ( j=0; j<3; j++ )
{
scanf ( "%d", &mat[ i ][ j ] );
}
}
printf ( "The elements of the matrix are: \n " );
for ( i=0; i<3; i++)
{
printf ("\n");
for ( j=0; j<3; j++ )

MOHAMMED SALEEM | Asst. Prof., Dept. of E & C, PACE 5


[INTRODUCTION TO C PROGRAMMING - BESCK104E] saleem_ece@[Link]

printf ( "\t %d", mat[ i ][ j ] );


}
return 0;
}
7. Write a program to transpose the elements of a 3 x 3 matrix.
#include <stdio.h>
int main ( )
{
int i, j, mat[3][3], t_mat [3][3];
printf ( "Enter the elements of the matrix: \n" );
for ( i=0; i<3; i++ )
{
for ( j=0; j<3; j++ )
{
scanf ( "%d", &mat[ i ][ j ] );
}
}
printf ( "The elements of the matrix are: \n " );
for ( i=0; i<3; i++)
{
printf("\n");
for ( j=0; j<3; j++ )
printf ( "\t %d", mat[ i ][ j ] );
}
for ( i=0; i<3; i++)
{
for ( j=0; j<3; j++ )
t_mat[ i ][ j ] = mat[ j ][ i ] ;
}
printf ( " The elements of the transposed matrix are: \n " );

MOHAMMED SALEEM | Asst. Prof., Dept. of E & C, PACE 6


[INTRODUCTION TO C PROGRAMMING - BESCK104E] saleem_ece@[Link]

for ( i=0; i<3; i++)


{
printf("\n");
for ( j=0; j<3; j++ )
printf ( "\t %d", t_mat[ i ][ j ] );
}
return 0;
}
8. Write a C program to implement matrix multiplication and validate the rules of
multiplication.
#include<stdio.h>
#include<stdlib.h>
int main( )
{
int r1, c1, r2, c2, row, col, k, a[10][10],b[10][10],m[10][10];
printf ( "Enter the order of matrix A\n" );
scanf ( "%d %d",&r1, &c1 );
printf ( "Enter order of matrix B\n" );
scanf ( "%d %d", &r2, &c2 );
if ( c1 != r2)
{
printf ( "Matrix Multiplication is not possible \n" );
exit (0);
}
printf ( "Enter the elements into matrix A\ n" );
for ( row=0; row<r1; row++)
{
for ( col=0; col<c1; col++ )
scanf ( "%d" , &a[ row ][ col ] );
}

MOHAMMED SALEEM | Asst. Prof., Dept. of E & C, PACE 7


[INTRODUCTION TO C PROGRAMMING - BESCK104E] saleem_ece@[Link]

printf ( "Enter the elements into matrix B \n" );


for ( row=0; row<r2; row++ )
{
for( col=0; col<c2; col++ )
scanf ( "%d", &b[ row ][ col ]);
}
for( row=0; row<r1; row++)
{
for( col=0; col<c2; col++)
{
m[row][col]=0;
for( k=0; k<c1; k++)
{
m[ row ][ col ] = m[ row ][ col ] + a[ row ][ k ] * b[ k ][ col ];
} } }
printf ( " The elements of Product of Matrix A and B is: \n");
for( row=0; row<r1; row++ )
{
for (col=0; col<c2; col++ )
printf ( "%3d", m[ row ][ col ] );
}
printf ( "\n" );
}
return 0;
}
9. Develop a C program to sort the given set of N numbers using bubble sort.
#include<stdio.h>
int main( )
{
int i, j, N, temp, a[20];

MOHAMMED SALEEM | Asst. Prof., Dept. of E & C, PACE 8


[INTRODUCTION TO C PROGRAMMING - BESCK104E] saleem_ece@[Link]

printf ( "Enter the value of N: \n" );


scanf ( "%d", &N );
printf ("Enter the numbers in unsorted order:\n" );
for ( i=0; i<N; i++ )
scanf ( " %d ", &a[i] );
// bubble sort logic
for ( i=0; i<N; i++ )
{
for ( j=0; j<(N-i)-1; j++ )
{
if ( a[j]>a[j+1] )
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf ( "The sorted array is \n" );
for ( i=0; i<N; i++ )
{
printf ("%d\n", a[i] );
}
return 0;
}

10. Write a program to count vowels and consonants in a string.


#include<stdio.h>
#include<string.h>
int main( )

MOHAMMED SALEEM | Asst. Prof., Dept. of E & C, PACE 9


[INTRODUCTION TO C PROGRAMMING - BESCK104E] saleem_ece@[Link]

{
char s[100];
int i, vowels=0, consonants=0, len=0;
printf ( "Enter the string: " );
gets ( s );
len = strlen(s);
for ( i=0; i<len; i++ )
{
if ( s[ i ] >= ‘A’ && s[ i ] <= ‘Z’ ) || ( s[ i ] >= ‘a’ && s[ i ] <= ‘z’ )
{
if ( s[ i ] == ‘a’ || s[ i ] == ‘e’ || s[ i ] == ‘i’ || s[ i ] == ‘o’ || s[ i ] == ‘u’ || s[ i ] == ‘A’ || s[ i ]
== ‘E’ || s[ i ] == ‘I’ || s[ i ] == ‘O’ || s[ i ] == ‘U’ )
vowels++;
else
consonants++;
}
}
printf (“ Vowels in the string is = %d”, vowels);
printf (“ Consonants in the string is = %d”, consonants);
return 0;
}
11. Write a C program to find the sum of diagonal elements of a matrix.
##include<stdio.h>
int main( )
{
int r, c, i, j, a[10][10], sum;
printf ( "Enter the order of the matrix \n" );
scanf ( "%d %d", &r, &c );
if ( r != c)
{

MOHAMMED SALEEM | Asst. Prof., Dept. of E & C, PACE 10


[INTRODUCTION TO C PROGRAMMING - BESCK104E] saleem_ece@[Link]

printf ( "Not a square matrix \n" );


exit (0);
}
printf ( "Enter the elements of matrix \ n" );
for ( i=0; i<r; i++)
{
for ( j=0; j<c; j++ )
scanf ( "%d" , &a[ i ][ j ] );
}
}
for ( i=0; i<r; i++)
{
sum = sum + a[ i ][ i ];
}
printf ( “ The sum of diagonal elements is %d”, sum);
return 0;
}
12. Write program to generate Pascal’s triangle.
#include <stdio.h>
#include <conio.h>
int main ( )
{
int arr[7][7] = { 0 };
int row=2, col, i, j;
arr[0][0] = arr[1][0] = arr[1][1] = 1;
while (row < 7)
{
arr[row][0] = 1;
for (col = 1; col <= row; col++)
arr[row][col] = arr[row-1][col-1] + arr[row-1][col];

MOHAMMED SALEEM | Asst. Prof., Dept. of E & C, PACE 11


[INTRODUCTION TO C PROGRAMMING - BESCK104E] saleem_ece@[Link]

row++;
}
for(i=0;i<7;i++)
{
printf("\n");
for (j=0; j<=i; j++)
printf ( "\t %d", arr[i][j]);
}
return 0;
}
13. Write a program to print following pattern.
#include <stdio.h>
int main ( )
{
int i, p;
char str[ ] = "HELLO";
printf ( "\n" );
for ( i=0; i<5; i++)
{
p = i+1;
printf ( "\n % -5 . * s", p, str );
}
printf ( "\n" );
for ( i=4; i>=0; i-- )
{
p = i+1;
printf ( "\n % -5 . * s", p, str );
}
return 0;
}

MOHAMMED SALEEM | Asst. Prof., Dept. of E & C, PACE 12

Common questions

Powered by AI

Matrix transposition involves swapping the rows and columns of the matrix. In a C program, two matrices are defined: 'mat' for the original and 't_mat' for the transposed version. First, the elements are inputted into 'mat'. Then, in a nested loop, the elements are transferred from 'mat[i][j]' to 't_mat[j][i]'. Finally, the transposed matrix 't_mat' is printed.

To count vowels and consonants in a string, input the string and measure its length. Iterate through each character, checking if it's a vowel by comparing against both uppercase and lowercase vowel characters. Non-vowel alphabets are counted as consonants. Increment the respective counters for vowels or consonants based on character match. Display the final counts at the end of iterations.

In C programming, a single row of a two-dimensional array can be passed to a function by indexing the array with the specific row number. For instance, if you have a 2D array 'marks' and want to pass the first row, you would call the function and pass marks[0]. This essentially passes a one-dimensional array pointer to the function.

A 3-dimensional array is defined by three subscripts [m1][m2][m3], representing collections of m1 * m2 * m3 elements. Unlike a 2D array which can be visualized as a single grid, a 3D array represents multiple grids or pages, each containing a 2D array. The elements are organized by traversing pages, measuring the cumulative size as a factor of all three dimensions. This structure allows complex data representation resembling a cube.

Strings in C can be read using functions like scanf(), gets(), and getchar(). scanf() reads until a space is encountered, which can lead to incomplete string reading with spaces. gets() overcomes this by reading the whole line until a newline character, making it better for multi-word input. Strings can be written using printf(), puts(), and putchar(). printf() allows formatted output, including precision and width control, but puts() automatically appends a newline and can be simpler for direct output.

Matrix multiplication in C requires the number of columns in the first matrix to equal the number of rows in the second matrix. In a C program, these conditions are validated by comparing dimensions after reading them. If the condition fails (i.e., c1 != r2), the program exits with a message indicating the impossibility of multiplication. Otherwise, the elements are multiplied, and products are stored in a resultant matrix. These results are computed in a nested loop summing the product of respective entries.

To calculate the sum of diagonal elements in a square matrix, first verify the matrix is square by checking if its row and column counts are equal. Input the matrix elements, and use a loop to iterate through indices where row equals column, summing up these elements. This produces the sum of the diagonal. Incorrect dimensions result in exiting the program with a message.

Bubble sort is implemented to sort 'N' numbers in ascending order. In C, an array is scanned such that adjacent elements are compared. If the element on the left is greater, they are swapped. This process repeats, with each pass bringing the highest unsorted element to its correct position, reducing the effective array size, until no more swaps are needed. Its primary logic is repeatedly walking through the list and comparing each pair of adjacent items.

Pascal's triangle is generated using nested loops. Firstly, initialize a 2D array, set the first two rows of Pascal's triangle explicitly. In subsequent rows, each element arr[row][col] is calculated as the sum of the element directly above `arr[row-1][col-1]` and to the left `arr[row-1][col]`. This logic is repeated for increasing row numbers, expanding until the desired row count. Finally, print each row of the calculated triangle elements.

A two-dimensional array in C is declared using the syntax: data_type array_name[row_size][column_size]. For example, int marks[3][5] declares a two-dimensional array named 'marks' with 3 rows and 5 columns. This means it can hold the marks of 3 students in 5 subjects. In memory, it's represented in a row and column layout such that marks[0][0] is the first student's mark in the first subject, and marks[0][1] is the same student's mark in the second subject, etc.

You might also like