Welcome

C Programming Tutorial


C Arrays and Strings


C Arrays

'C' Arrays are fixed length Data Structure.Arrays represent collection of Data of same data type, Memory will be allocated as a contiguoes block.

C Arrays has lower bound and upper bound,upper bound must be specified at the time of declaration, otherwise error. Lower bound starts from 0.
It is a Linear Data Structure, elements can be accessed in Linear fashion.
C Arrays are Random access Data Structure, any elements can be accessed randomly.
Fixed Number of items , such as collection of products,cities,courses,seats in Bus or train or flight etc.,, can be represented as an Array.
It is a homogenious datatype,all elements should be of same type.
'C' Language supports one-dimensional and multi-dimensional arrays

Array Syntax:

		datatype variable[expr];

/* here expr is a subscript, this value can be a Integer constant, or 
	constant integral expression,must be +ve number */
	

Array Declartion in 'C' :example:

		     int a[10] ;
     short s[10];
     char c[10];
     float f[10];
			or it can be declared using constant value
	
		     #define MAX-SIZE 10
		      int a[MAX-SIZE]
		
			or it can be declared using constant integral expression
	
		     #define MAX-SIZE 10
		      int a[MAX-SIZE/2+1]
		
In Array sqaure brackets [] contain subscript
based on data type space will be allocated. int 4 bytes,short 2 bytes char 1byte,float 4 bytes.
size of the array = max-elements * datatype size.
for ex: for int a[10], max elements are 10 and space allocated for int is 4 bytes, 10*4 = 40 bytes space will be allocated for array a,similaryly for other arrays.

Initialize an Array

      int a[3]={0} /* Initialize all 3 elements with 0 */

      int a[3]={1,5,7} /* Initialize all 3 elements with 1,5,7 */

     char a[3]={'a','b','c'}

      float a[3]={10.00,5.77,7.99}

error: variable-sized object may not be initialized 8 | int c[n+m]={0};

Array Example: sum of all elements

	#include <stdio.h>
	
	int main()
	{
		int a[5]={1,4,5,3,1};
		int sum=0;
		
		for (int i=0; i < sizeof(a)/sizeof(int); i++){
			sum+=a[i];
		}

		printf("sum of array=%d",sum);
	}
	
output:
		sum of array=14
	

Print Array Elements using recursion



void printArray(int a[],int len)
{
    static int i=0;
    if(len==0)return;

    printf("%d ",a[i++]);
    printArray(a,--len);
}

Multi-Dimensional Arrays

         C Language supports Multi-Dimensional Arrays i.e arrays of arrays.single sqaure brackets is single dimensional array, double square brackets makes two-dimensional arrays, 3 sqaure brackets leads to 3-dimensional arrays. and so on...

Declaring Two-Dimensional Array

	int a[2][2];
	// a is a 2 dimensional array which has 2 rows and 2 columns

	internally array "a" represented as

		column0 	column1

	row 0   a[0][0] 	a[0][1]
	row 1   a[1][0] 	a[1][1]

	first subscript represents  "row"  second subscript represents "column".

	Number of elements in 2-dimesional arrays  is  "n*m" , n=rows m= columns
Fill 2-Dimensional Array with Static Data
	a[0][0]=10;
	a[0][1]=13;
	a[1][0]=20;
	a[1][1]=24;
Fill 2-Dimensional Array with Dynamic Data
   	int n=2,m=3;
	int a[n][m];

	printf("Reading values from keyboard\n");
	
	for(int row=0; row < n; row++)
	{
		for(int col=0; col < m; col++)
		{
			scanf("%d",&a[row][col]);
		}
	}

	Display Array Elements

	printf("Displaying Array Elements\n");

	for(int row=0; row < n; row++)
	{
		for(int col=0; col < m; col++)
		{
			printf("%d ",a[row][col]);
		}
		printf("\n");
	}
Input and Output
Reading values from keyboard
1 2 3 
4 5 6
Displaying Array Elements
1 2 3 
4 5 6 

//second input, user can enter all values in single line.
Reading values from keyboard
1 2 3 4 5 6
Displaying Array Elements
1 2 3 
4 5 6 

Initializing 2-Dimensional Array

    int a[2][3]={1}; all elements filled with 1
    int a[2][3]={1,2,3,4,5,6};First three numbers will go to row 0, next three elements go to row 1
    int a[2][3]={{10,20,30},{40,50,60} };In this style of initialization, row 0 has {10,20,30}  row 1 has {40,50,60}

	int n=2,m=3;
 int a[n][m]={{10,20,30},{40,50,60} };
error: variable-sized object may not be initialized

Adding 2 matrix

    Adding 2 matrix requires, matrix should have same number of rows and columns.

	int a[2][2]={{10,20},{30,40}};
	int b[2][2]={{30,40},{10,20}};

	printf("Matrix sum\n");
	for(int i=0; i < 2; i++){
        for(int j=0; j < 2; j++){
            printf("%d ",a[i][j]+b[i][j]);
        }
        printf("\n");
	}
ouput:
Matrix sum
40 60 
40 60 

Multiply 2 matix

Transpose a Matrix

Sparse Matrix

       A sparse matrix is a matrix that is comprised of mostly zero values

Sparse matrices are distinct from matrices with mostly non-zero values, which are referred to as dence matrices.

The sparcity of a matrix can be qualified with a score, which is the number of zero values in the matrix divided by the total number of elements in the matrix.

	   sparcity = count zero elements / total number of elements
	1 0 0 1 0 0
	0 0 2 0 0 1
	0 0 0 2 0 0

the matrix has 13 zero values of the 18 elements.
giving this matrix a sparcity score is 13/18 = 0.722 or about 72%.

Sparse matrices can cause problems with regards to space and time complexity

Passing two-Dimensional Arrays to Function as a Argument

     passing arrays to functions as a argument is nothing but passing base address of the array, In case of Multi-dimensional arrays first Dimensional is ignored by the compiler.Remaning all dimesions must be passed to the function

	int arr[2][3]={{4,5,6},{10,11,12}};
	func(arr,2);
	void func(int a[2][3],int ROWS)
	{
		//find no. of columns

		int COLS = sizeof(a[0])/sizeof(a[0][0]);

		//display array elements
		for(int i=0; i < ROWS; i++)
		{
			for(int j=0; j < COLS; j++)
			{
				printf("%d ",a[i][j]);
			}
			printf("\n");
		}
	}

calling func(int a[100][3] is accepted by the compiler. Here Row size 100 is ignored by the compiler,matter of fact any number specified is not considered.

‘arr’ as multidimensional array must have bounds for all dimensions except the first

Character Arrays

Character Arrays are special types of arrays where last character will be NULL character. It can be supplied by programmer or automatically appends NULL character . '\0' or NULL

Declaring Character Arrays

	char c[10];
	//read characters into array.
	for(int i=0; i <10; i++){
		scanf("%c",&c[i]);	
	}

C Strings

Strings represent sequence of characters null character at the end '\0', null character marks end of the string, Since Strings represent array of characters each element is a single byte ASCII value.
in bitwise operations null character has all bits off.

Find string length


char *p="hello String!";

printf("string=\"%s\" length:%d",p,strlen(p));

int strlen(char*p)
{
    int n=0;

        while(*p++!='\0')++n;

    return n;
}

//output:13

storage size isn't constant, static storage class on arrays

ADS