0% found this document useful (0 votes)
2 views

UNIT 3 (C Programming)-1

Uploaded by

januammu0211
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

UNIT 3 (C Programming)-1

Uploaded by

januammu0211
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Programming in C I Sem BCA

CHAPTER – 3
Derived data types in C
Arrays
A normal variable can hold only one value. Suppose we may need to process a group of data
items that are having the same data type such as integer, float etc. in such situations we need one
special data structure that is “arrays”.

Definition:

An array can be defined as an ordered collection of homogeneous data elements of same


data type.

Each element in an array is declared by a subscript or index. It is represented by pair of square


braces [ ].

Arrays are mainly classified into 2 types. They are

Arrays

One multi dimensional

dimensional

Two dimensional Three dimensional

One dimensional Array


“It is an array all the data elements are accessed using same name and single subscript.”

Declaration of one dimension array:


A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 1
Programming in C I Sem BCA

Syntax: datatype arrayname [ size ] ;


Where

 Datatype is any basic datatype or user defined data type.

 Arrayname is the name of the array.


 Size is the number of elements present in that array.
Ex: inta [ 10 ] ;

Rules for subscript:

 Each subscript size must be positive integer.

 Subscript of subscript is not allowed.

 In C the subscript ranges from 0 to n-1

Accessing elements of an array:


Array elements always starting from 0th the location and ends with n-1. Where n is the size of
an array.

Suppose int a [5] ;

Here first 5 location will be created in memory.

a[0] a[1] a[2] a[3] a[4]

Array Initialization:

Initialization is a process of accessing values to a variable.

Syntax: datatype arrayname [ size ] = {ele1, ele2, ……. ele n} ;

Where

 Datatype is any basic datatype or user defined data type.

 Arrayname is the name of the array.

 Size is the number of elements present in that array

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 2


Programming in C I Sem BCA
 ele1, ele2….ele n are the initial values enclosed with in a pair of braces { }.
Ex: int a [5] = { 10 , 20, 30, 40, 50 };

10 20 30 40 50

a[0] a[1] a[2] a[3] a[4]

Code for accept or read array elements:

printf ( “ \n enter elements to an array”);

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

scanf ( “%d” , &a[i]);

Code for print or display array elements:

printf ( “ \n elements of an array are”);

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

printf ( “%d” , a[i]);

Example programs

/* program to accept n integers and store them in an array and also print them */

void main()
{
int a[10], i ,n ;
printf(“\n enter the size of an array”);
scanf(“%d”,&n);
printf ( “ \n enter elements to an array”);
for ( i=0; i<n ; i++)
scanf ( “%d” , &a[i]);
printf ( “ \n elements of an array are”);
for ( i=0; i<n ; i++)
printf ( “%d” , a[i]);
}

Output: enter size of an array 5

Enter elements to an array 1 2 3 4 5


A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 3
Programming in C I Sem BCA

Elements of an array are 1 2 3 4 5

/* program to accept 2 integer arrays and find sum of the corresponding elements in the
array */

void main()
{
int a[10],b[10,c[10, i ,n,sum[10] ;
printf(“\n enter the size of an array”);
scanf(“%d”,&n);
printf ( “ \n enter elements to the first array”);
for ( i=0; i<n ; i++)
scanf ( “%d” , &a[i]);
printf ( “ \n enter elements to the second array”);
for ( i=0; i<n ; i++)
scanf ( “%d” , &b[i]);
for(i=0 ; i<n ; i++ )
sum[i] = a[i] + b[i] ;
printf ( “ \n sum elements of an array are”);
for ( i=0; i<n ; i++)
printf ( “%d” , sum[i]);
}

Output: enter the size of an array 5

Enter the elements to the first array 1 2 3 4 5

Enter the elements to the second array 1 2 3 4 5

Sum elements are 2 4 6 8 10

Multi dimensional Arrays


Multi dimensional arrays can be consisting of more than one subscripts. This can be classified as
2 types. They are

 Two dimensional array

 Three dimensional array

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 4


Programming in C I Sem BCA

Two dimensional array:

This array can be consisting of 2 subscripts. The simplest and most commonly used
arraysare 2 dimensional arrays.

This array required row size and column size. The declaration of 2D array will be
Syntax:

Datatype arrayname [rowsize] [colsize] ;

Ex: int a [2][2] ;

Here total 4 elements stored in that array. (2X2=4)

Three dimensional array:

This array can be consisting of 3 subscripts. The declaration of 3D array will be

Syntax:

Datatype arrayname [size1] [size2] [size3];

Ex: int a [2] [2] [3] ;

Here total 12 elements stored in that array. (2X2X3=12)

Initialization of 2D array
The list of values assigned to array elements in order.

Ex: int a[3][3] = {1,2,3,4,5,6,7,8,9} ;

a[0][0] = 1 a[1][0] = 4 a[2][0] = 7

a[0][1] = 2 a[1][1] = 5 a[2][1] = 8

a [0][2] = 3 a[1][2] = 6 a[2][2] = 9

Code for accept or read 2D-array elements:

printf ( “ \n enter elements to an array”);

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

for (j=0; j<n ; j++)

scanf ( “%d” , &a[i][j]);

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 5


Programming in C I Sem BCA

Code for print or display 2D-array elements:

printf ( “ \n elements of an array are”);

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

for (j=0; j<n; j++)

printf ( “%d” , a[i][j]);

Multiplication of matrices
Suppose the order of 1 st matrix is mxn,

The order of 2nd matrix is pxq

The matrix multiplication is possible only, when the columns of 1 st matrix must be equals to the
rows of 2nd matrix.

m x n = p x q

equal

/* program to find matrix multiplication */

void main()
{
int a[10][10], b[10][10], mul[10][10], i, j ,k,n;
clrscr();
printf(“\n enter the order of matrix”);
scanf(“%d”,&n);
printf ( “ \n enter elements to the first array”);
for ( i=0; i<n ; i++)
for (j=0; j<n ; j++)
scanf ( “%d” , &a[i][j]);
printf ( “ \n enter elements to the second array”);
for ( i=0; i<n ; i++)
for (j=0; j<n ; j++)
scanf ( “%d” , &b[i][j]);
for ( i=0; i<n ; i++)
for (j=0; j<n ; j++)
{
mul[i][j]=0;
for(k=0;k<n;k++)
mul[i][j] = mul[i][j] + a[i][k] * b[k][j];

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 6


Programming in C I Sem BCA
}
printf ( “ \n product matrix is”);
for ( i=0; i<n ; i++)
{
for (j=0; j<n; j++)
printf ( “%d” , mul[i][j]);
printf(“\n”);

}
getch();
}
STRINGS
STRINGS:

It is a packed character array, which is terminated by NULL character. In the declaration statement,
character array and strings are one and the same. To differentiate character array and string is only after
inputting the data. A character array, which is end with a NULL character is called string otherwise is a
character array.

String Defn: It is a one dimensional array of characters terminated by a null.

DECLARATION:

char String_name [size] ;

Where, Str is the user defined string variable name, size indicates the number of character accommodated in
the string.

Eg: char name [20] ;

Reserves a block of 20 bytes to the name, each elements can holds one character and its contents can
accessed by its subscripts.

Allocation

String initialization :

String can be initialized by two methods, character constant and string constant.

i. character constant :

Char St [7] = {‘a’,’l’,’p’,’h’,’\0’};

In this method user can specified NULL character ate the end of the string.

ii. String constant:

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 7


Programming in C I Sem BCA
Char st[10] ={“TUMKUR”};

In this method complier it can introduce NULL character.

Reading a string from terminal


Reading string from terminal using 3 ways. They are

 scanf ( ) function

 gets ( ) function
 getchar ( ) function

scanf ( ) function:

The function scanf with %s format specifier is needed to read the string from the
terminal.

Syntax: scanf ( “ format specifiers” , string name) ;

In this & symbol is not required for reading variables. Because array itself allocates address for
that it cannot have & symbol.

Ex: suppose if we input “BANGALORE” ,then storage looks like

B A N G A L O R E \0
Ex: suppose if we input “NEW DELHI”, then storage looks like

N E W \0 ? ? ? ? ? ?

The function scanf ( ) has a drawback it just terminates as soon as it finds blank space.

In the above example scanf reads only new but not delhi because after the word new one blank
space is appeared. Then scanf understand the string will be ended.

Ex: /* program to read a string and print by using scanf() function */

void main()

{
char str[30];

printf(“\n enter a string”);

scanf(“%s”, str);

printf(“\n given string is %s”, str );

getch(); }

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 8


Programming in C I Sem BCA

gets ( ) function:
this unformatted input function. Using this we can read one string at a time.
This is the most convenient method of reading a string . this is a library
function and it isavailable in the <stdio.h> header file.

Syntax: gets ( string );

It reads characters from the keyboard until a new line character is encountered and
then appendsa null character to the string automatically.

Ex: char str[20] = { “this is vision”};

gets ( str );

output: this is vision


in the above example gets function reads the total string. This is the advantage
of the gets ()function. But it cannot read more than one string at a time.

Ex: /* program to read a string and print by using gets () function */

void main()

{
char str[30];

printf(“\n enter a string”);

gets (str);

printf(“\n given string is %s”, str );

getch();

getchar ( ) function:
This function is unformatted input function. It read only one character at a time.

Ex:

void main()
{
char str[40], ch;
int i=0;
printf(“\n enter a string “);

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 9


Programming in C I Sem BCA
do
{
ch=getchar( );
str[i]=ch; i++;
}while ( ch !=’\n’);
str[i-1]=’\0’;
printf(“\n the string is %s”, str );
}

Writing a string to screen

Writing string to screen using 3 ways. They are

 printf ( ) function

 puts ( ) function

 putchar ( ) function

printf ( ) function:
The function printf with %s format specifier is needed to print the string on the
terminal.

Syntax: printf ( “ format specifiers” , string name) ;

puts ( ) function:

this unformatted output function. Using this we can print one string at a time.

This is the most convenient method of writing a string . this is a library


function and it isavailable in the <stdio.h> header file.

Syntax: puts ( string );


It prints characters on the terminal until a new line character is encountered and
then appends anull character to the string automatically.

Ex: char str[20] = { “this is vision”};

puts ( str );

output: this is vision


in the above example puts function prints the total string.

Ex: /* program to read a string and print by using puts () function */


void main()

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 10


Programming in C I Sem BCA
{
char str[30];

printf(“\n enter a string”);

gets(str);

puts(str);

getch();
}

putchar ( ) function:
This function is unformatted output function. It print only one character at a
time. We canuse this function repeatedly to output a string of characters stored in
an array using a loop.

Ex:
void main( )

{
char str[8]= {“skyward”};

int i=0;

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

putchar(str[i]);

putchar(“\n”);

String operations: C-Library supports a large number of string-handling that can be used to
carry out may of the string manipulations such as,

i. Length [number of characters in a string].


ii. Concatenation [Adding of the two strings].
iii. Comparing two strings.
iv. Substring [Extracting substring from the main string].
v. Copy [Copies one string to another].

String manipulation functions:

These are the built in functions which are used to manipulate the null terminated strings.
A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 11
Programming in C I Sem BCA

Note: To use all the string functions in C you must include string.h library header file in the
program.

1. strlen () function: This function counts and returns the number of characters in a string. The
length does not include the NULL character.

Syntax: n= strlen (string);

Where n is integer variables which receive the value from the strlen function

E.g. n = strlen (“TUMKUR”); 6

2. strcpy () function: This function is used to make the duplicate copy of existing string.

Syntax: strcpy (str2, str1);

It copies the content of str1 to str2.

E.g. strcpy(str2, “TUMKUR”) ;

Note: C language does not allow you to assign the string to another string directly by
assignment operator.

Str1 = “Tumkur” ; This is invalid statement.

3. strcat () function : This function used to combine two strings into single string. In
other words add the content of second string to the end of the first string. It is also
called as merge two strings.
Syntax: strcat(str1,str2);

Str2 is appended to str1 and str2 unchanged.

E.g. strcpy (str1, “Tumkur”);

strcpy(str2, “Karnataka”);

strcat (str1, str2); The resultant of str1 is “Tumkur Karnataka”

4. strcmp () function : This function is used to compare two strings with case sensitive, which
returns an integer. If the integer value is equal to zero, indicate both the strings are equal. If value
is +ve , first string is greater than second string. If value is –ve, first string is smaller then second
string.

Syntax: strcmp(str1, str2);

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 12


Programming in C I Sem BCA
E.g. strcmp(“Tumkur”, “Tumkur”); will return 0 value.

strcmp(“tumkur”, “Tumkur”); will return +ve value.

strcmp(“Tumkur”, “tumkur”); will return –ve value.

6. strcmpi () function: This function is same as strcmp, which compares two strings but not case
sensitive, which returns an integer. If the integer value is equal to zero, indicate both the strings
are equal. If value is +ve , first string is greater than second string. If value is –ve, first string is
smaller then second string.

Syntax: strcmpi(str1, str2);

E.g. strcmpi (“Tumkur” , “tumkur”); will return 0 value

7. strlwr () function : This function converts all alphabets in a string from uppercase to lower
case.

Syntax: strlwr(str);

E.g. strlwr (“TUMKUR”); output is : “tumkur”

8. strupr () function : This function converts all alphabets in a string from lower case to upper
case

Syntax: strupr(str);

E.g. strupr (“tumkur”); output is : “TUMKUR”

9. strrev () function: This function reverser the characters in a string.

Syntax: strrev(str);

strrev (“TUMKUR”); output is : “RUKMUT”

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 13


Programming in C I Sem BCA
Operations on characters [ctype.h]:

Function Description Example

isalnum(char) Tests whether a character is an isalnum(‘+’);  0


alphanumeric or not
isalnum(‘9’);  1

isalnum(‘B’);  1

isalpha(char) Tests whether a character is an isalpha(‘A’);  1


alphabet or not
isalpha(‘7’);  0

isdigit(char) Tests whether a character is a isdigit(‘B’);  0


numerical digit or not
isdigit(‘4’);  1

islower(char) Tests whether a character is lower islower(‘B’);  0


case alphabet or no
islower(‘e’);  1

isupper(char) Tests whether a character is upper isupper(‘B’);  1


case alphabet or no
isupper(‘e’);  0

isspace(char) Tests whether a character is white isspace(‘\n’);  1


space character or not [space, tab,
new line ] isspace(‘b’);  0

Conversion character functions :

Function Description Example

toascii(char) Translate character to ASCII value toascii(‘A’);  65

toascii(‘2’);  50

tolower(char) Translate upper case alphabet to tolower(‘B’)  ‘b’


lower case alphabet
tolower(‘b’);  ‘b’

toupper(char) Translate lower case alphabet to toupper(‘B’)  ‘B’


upper case alphabet
toupper(‘b’);  ‘B’

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 14


Programming in C I Sem BCA

Example 1: String manipulations program

#include<stdio.h>

void main()

char str1[20],str2[20],str3[20];

int length;

clrscr();

printf("enter the first string\n");

gets(str1);

printf("the entered first string is\n");

puts(str1);

printf("enter the second string\n");

gets(str2);

printf("the entered second string is\n");

puts(str2);

length=strlen(str1);

strlwr(str1);

strupr(str2);

strcpy(str1,str2);

printf("the length of the string is %d\n",length);

printf("the first string is %s\n",str1);

printf("the second string is %s\n",str2);

printf("the copied string is %s\n",str1);

getch();

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 15


Programming in C I Sem BCA

Example2: Program to concatenate two strings

#include <stdio.h>
#include <string.h>

int main()
{
char a[100], b[50];

printf("Enter the first string\n");


gets(a);

printf("Enter the second string\n");


gets(b);

strcat(a,b);

printf("The concatenated string is %s\n",a);

return 0;
}

Example3: Program to reverse a string without using library function

#include<stdio.h>

#include<string.h>

int main() {

char str[100], temp;

int i, j = 0;

printf("\nEnter the string :");

gets(str);

i = 0;

j = strlen(str) - 1;

while (i < j) {

temp = str[i];

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 16


Programming in C I Sem BCA

str[i] = str[j];

str[j] = temp;

i++;

j--;

printf("\nReverse string is :%s", str);

return (0);

Example 4:Program to compare two strings

#include<stdio.h>

void main()

char str1[20],str2[20];

int res;

printf("enter first string\n");

gets(str1);

printf("enter second string\n");

gets(str2);

res=strcmp(str1,str2);

if(res==0)

printf("strings are equal\n");

else if(res<0)

printf("string 1 is less than string 2\n");

else

printf("string 1 is greater than string2\n");

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 17


Programming in C I Sem BCA

getch();

Example 5 Program to find the length of string without using built in function

#include<stdio.h>

void main()

char str[20];

int i,len=0;

clrscr();

printf("enter the string\n");

gets(str);

for(i=0;str[i]!='\0';i++)

len++;

printf("length of the given string is %d",len);

getch();

Example 6 Program to count uppercase and lowercase characters in a string.

//to count the number of upper and lower case characters in a string

#include<stdio.h>

void main()

char str[20];

int i,uppercount=0,lowercount=0;

clrscr();

printf("enter a sytring\n");

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 18


Programming in C I Sem BCA

gets(str);

for(i=0;str[i]!='\0';i++)

if(str[i]>='A'&&str[i]<='Z')

uppercount++;

if(str[i]>='a'&&str[i]<='z')

lowercount++;

printf("the number of uppercase characters is %d\n",uppercount);

printf("the number of lowercase characters is %d\n",lowercount);

getch();

Example 7 to check whether given string is palindrome or not

#include<stdio.h>

#include<conio.h>

void main()

char str1[20],str2[20];

clrscr();

printf("enter a string\n");

gets(str1);

strcpy(str2,str1);

strrev(str2);

if(strcmp(str1,str2)==0)

printf("the given string is palindrome\n");

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 19


Programming in C I Sem BCA

else

printf("the given string is not a palindrome\n");

getch();

Questions:

1. Write a program to find product of two matrices.

2. What is an array? How it is declared and initialization?

3. What is multidimensional Arrays?

4. The range of index for an array of size n is ?

5. Write a program to find given string is palindrome or not.

6. Which built-in function used to find number of characters in given string?

7. Give the syntax of string comparison?

8. Explain any 3 character handling functions.

9. Write a program to reverse the given string.

10. Write a c-program to convert all lower case letters to upper case letters and
vice versa in a given string.

11. Explain any 3 string handling functions with syntax.

12. Write a program to find length of a given string without using built-in function.
13. What is the syntax of string concatenation.

A R MAHESHA HOD Dept. of Computer Science, GFGC Tumakuru Page 20

You might also like