0% found this document useful (0 votes)
18 views28 pages

Unit 3

unit3 ppsc

Uploaded by

mounica
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)
18 views28 pages

Unit 3

unit3 ppsc

Uploaded by

mounica
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
You are on page 1/ 28

UNIT-3

Arrays

 Array is a variable which store more than one values of same datatype in a
continuous memory location.

 Array is a derived datatype.

 The elements of the array are referred by using index/subscript.

 The array index starts with 0 and goes till size-1.

EX: students,employees.

Declaration of arrays:

Syntax:

datatype arrayname[size];

 Data type represents what kind of values it can store.

Ex:int,char,float,double.

 Name is used to identify the array

 Size represents how many values that an array can store.

Ex: Int marks[5];

Initializing array:

There are different ways to initialize an array.

1. The simplest way to initialize an array is by using the index of each


element.
Syntax: datatype arrayname[size];
arrayname[index]=value;
Ex:
int marks[5];
marks[0]=19;
marks[1]=10;
marks[2]=8;
marks[3]=17;
marks[4]=9;
2. It is possible to initialize an array during declaration.
Syntax: datatype arrayname[size]={value0,value1…value(size-1)};

Ex: int marks[5]={19,10,8,17,9};


Accessing elements of an array:
 For accessing an individual elements of an array, the array index must
be used.
Ex:int marks[5]={19,10,8,17,9};
Printf(“%d”,marks[0]);//prints 19
Printf (“%d”,marks[4]);// prints 9
• To acess all elements of an array ,we have to use loops
Ex:
#include<stdio.h>
#include<conio.h>
main()
{
int i;
int marks[5]={19,10,8,17,9};
for(i=0;i<5;i++)
{
printf(“%d\n”,marks[i]);
}
getch();
}
Example program for reading and writing values into array:
#include<stdio.h>
#include<conio.h>
main()
{
int i;
int marks[5];
clrscr();
printf(“enter the marks\n”);
for(i=0;i<5;i++)
scanf(“%d”,&marks[i]);
printf(“the marks are:\n”);
for(i=0;i<5;i++)
printf(“%d\n”,marks[i]);
getch();
}
Use of arrays
 Storing more than 1 value at a time under a single name.
 Reading ,processing and displaying the array elements is easy.
TWO – DIMENSIONAL ARRAYS:
 To store data in the form of matrices and tables,
we need two dimensional arrays.
Declaring 2-d arrays:
Syntax: datatype arrayname[rowsize][columnsize];
Ex:int a[2][3];
Initializing 2d-array:
 3 ways to initialize 2-d array
1.Syntax: datatype arrayname[rows][columns]=value;
Ex:marks[2][3];
marks[0][0]=90;
marks[0][1]=87;
marks[0][2]=78;
marks[1][0]=68;
marks[1][1]=62;
marks[1][2]=71;
2.Syntax:datatype arrayname[rows][columnas]={value1,value2,…};
Ex:int marks[2][3]={90,80,70,65,85,95};
3.Syntax:datatype arrayname[rows][columnas]={{values of row1},..{value of
row n,…};
Ex:int marks[2][3]={{90,80,70},{65,85,95}};
Write a c program to read and print the elements of a 2d-array:

#include<stdio.h>

#include<conio.h>

main()

int marks[5][5];

int i,j,r,c;

clrscr();

printf(“enter the rows and columns\n”);

scanf(“%d%d”,&r,&c);

printf(“enter the elements\n”);

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

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

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

printf(“printing elements of the array\n”);

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

printf(“\n”);

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

printf(“%d\t”,marks[i][j]);

getch();

Multidimensional Arrays:

• In multidimensional array ,the array is having three or more dimensions.


Declaring multi dimensional arrays:
Syntax: datatype arrayname[d1][d2]…[dn];//d is the dimension
Ex:int a[2][2][2];
Initializing multi dimensional array:
Syntax: datatype arrayname[d1][d2]…[dn]={valu1,value2,…};
Ex:int a[2][2][2]={2,3,4,5,6,7,10,9};//size of a is (2*2*2)i.e 8

Write a c program to read and print a 2*2*2 array:

#include<stdio.h>

#include<conio.h>

main()

int a[2][2][2];

int i,j,k;

clrscr();

printf(“enter the elements of the array\n”);

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

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

{
for(k=0;k<2;k++)
scanf(“%d”,&a[i][j][k]);

printf(“printing elements of the array\n”);

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

printf(“\n\n”);

for(j=0;j<2;j++)
{

printf(“\n”);

for(k=0;k<2;k++)

printf(“\t a[%d][%d][%d]=%d”,i,j,k,a[i][j][k]);

getch();

#include<stdio.h>

#include<conio.h>

main()

int a[2][2][2][2];

int i,j,k,l;

clrscr();

printf(“enter the elements of the array\n”);


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

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

for(k=0;k<2;k++)

For(l=0;l<2;l++)

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

printf(“printing elements of the array\n”);

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

printf(“\n\n\n”);

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

printf(“\n\n”);

for(k=0;k<2;k++)

Printf(“\n”);

For(l=0;l<2;l++)

printf(“\t a[%d][%d][%d][%d]=%d”,i,j,k,l,a[i][j][k][l]);

}
}

getch();

Strings

Strings:

• A String is an array of characters.


• Any group of characters (except double
• quote sign )defined between double quotes is a constant string
Ex:”hello”-output is hello
• if we want to include double quotes
Ex:”\”hello\””-output is “hello”

Declaring strings :

Syntax: char stringname[size];

Ex:char s[5];

Initializing strings:

 There are two ways to initialize a string in c language.


1. By character array
Ex:char c[5]=’a’,’b’,’c’,’d’,’\0’;
Char c[10]=’h’,’e’,’l’,’l’,’o’,’\0’;
2. By string literal

Ex:char c[5]=”hello”;

Fixed length strings:

• while implementing fixed length string,we have to declare the size of the
variable.
Ex:char str[5]=”Have a nice day”;\\memory is not sufficient to store
value
Ex:char str[100]=”Hai”; \\memory is wasted

Variable length strings:

• while implementing variable length string,there is no need to declare the


size of the variable.
Ex:char str[]=”Have a nice day”;\\dynamically allocates memory to store
string
Ex:char str[]=”Hai”;

String input and output functions:

1.printf() and scanf()

2.puts and gets-puts is used to write a string onto the output screen.gets is
used to read a string from the keyboard.

Ex1:char str1[]=“hello”;

printf(“%s”,str1);

puts(str1);//%s not recquired

Ex:2 char str1[];

scanf(“%s”,&str1);

gets(str1);//%s not required


Example program to Read & write Strings in C using Printf() and Scanf()
functions:

#include<stdio.h>

#include<conio.h>

main()

char str[];

clrscr();

printf(“enter the string\n”);

scanf(“%s”,&str);

Printf(“%s”,str);

getch();

Output:

enter the string


hai

hai
Example program to Read & Write Strings in C using gets() and puts()
functions :

#include <stdio.h>

#include <conio.h>

main()

char name[20];

clrscr();

puts("Enter your name:\n"); //Console display using puts

gets(name); //Input using gets

puts(name);

getch();

Output:

Enter your name:

Hello

Hello

String Handling/Manipulation Functions:


 C supports a large number of string handling functions in the standard
library "string.h“(#include<string.h>)

1. String length:

 strlen( )-Finds length of String

Syntax: strlen(variable);

#include <stdio.h>

#include<conio.h>

#include <string.h>
main()

char str1[20] = “hello world";

Clrscr();

printf("Length of string str1: %d", strlen(str1));

getch();

Output:

Length of string str1:11


 Sizeof- sizeof(str1) would return value 20 as the array size is 20

Example program:
#include <stdio.h>

#include<conio.h>

#include <string.h>

main()

char str1[20] = “hello world";

clrscr();

printf("size of string str1: %d", sizeof(str1));

getch();

Output:

Size of string str1:20

 strlen vs sizeof
strlen returns you the length of the string stored in array, however sizeof
returns the total allocated size assigned to the array.

2.String copy:
 strcpy( )- Copies the contents of one string into another
Syntax: strcpy(destination,source);a=10;

Example program:
#include <stdio.h>

#include<conio.h>

#include <string.h>

main()

char s1[30] = "hello";

char s2[30] = "world";

printf("string s1 is %s\n",s1);

printf("string s2 is %s\n",s2);

strcpy(s1,s2);

printf("String s1 is: %s\n", s1);

printf("String s2 is: %s\n", s2);

getch();

3.String compare:

• strcmp( )- Compares two Strings

Syntax: strcmp(stringvariable1,stringvariable2);
The strcmp() function return an integer value as the result.
1.result +ve : String variable1 is greater than string variable2.
2.result –ve : String1 is less than string2.
3.result is zero : Both strings are equal.

Example program:

#include <stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[20];
char str2[20];
int result;
clrscr();
printf("Enter the first string : ");
scanf("%s",str1);
printf("Enter the second string : ");
scanf("%s",str2);
result=strcmp(str1,str2);
if(result==0)
printf("strings are same");
else
printf("strings are not same");
getch();
}
4.String concatenation:
• strcat( )- Concatenates two Strings
Example program:

#include <stdio.h>
#include<conio.h>
#include <string.h>
main()
{
char s1[10] = "Hello";
char s2[10] = "World";
clrscr();
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
getch();
}
5.String reverse:
• strrev(): This function is used to get the reverse string of a given string.
Syntax: strrev(string);
Example program:
#include<stdio.h>

#include< string.h>

main()
{
char str[20];
clrscr();
puts(“Enter a string”);
gets(str);
strrev(str);
puts(“Reverse string of the given string is”);
puts(str);
getch();
}

Write a c program to find a sub string in the given string:


#include<stdio.h>
#include<conio.h>
#include< string.h>
main()
{
char str[20]str1[20];
clrscr();
puts(“Enter a string ”);
gets(str);
puts(“Enter substring to find”);
gets(str1);
if(strstr(str,str1))
puts(“Yes it is in the string ”);
else
puts(“String Not found”);
getch();
}

String/ Data Conversion:

1.atoi:-

• This function returns the converted integral number as an int value. If


no valid conversion could be performed, it returns zero.

#include<stdio.h>

#include<conio.h>

#include<stdlib.h.

main()

// Converting a numeric string

char str[10] = "122";

int x = atoi(str);
printf("Converting '122': %d\n", x);
// Converting an alphanumeric string

char str2[10] = "Hello";


int y = atoi(str2);
printf("Converting Hello: %d\n", y);
// Converting a partial string

char str3[10] = "99Hello";

int z = atoi(str3);

printf("Converting 99Hello: %d\n", z);

getch();

2.atof :- This function returns the converted floating point number as a double
value. If no valid conversion could be performed, it returns zero (0.0).

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

main ()

char str[20];

strcpy(str, "98993489");

float x = atof(str);

printf("String value = %s, Float value = %f\n", str, x);

strcpy(str, “hello");

float y = atof(str);

printf("String value = %s, Float value = %f\n", str, y);

getch();

3.atol:

• convert a string to an long integer.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
long int l;
char str[30];
clrscr();
printf("enter a string:\n");
scanf("%s",str);
l=atol(str);
printf("string to long integer is : %ld",l);
getch();
}
A Programming Example – Morse Code:
• Morse code is a method of transmitting text information as a series of on-
off tones, lights, or clicks that can be directly understood by a skilled
listener or observer without special equipment.
• It is named for Samuel F. B. Morse, an inventor of the telegraph.

#include<stdio.h>
#include<string.h>
main()
{
char *alphamorse[]={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---",
"-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-",
"...-",".--","-..-","-.--","--.."};
char *nummorse[]={"-----",".----","..---","...--","....-",".....","-....","--...","---
..","----."};

int i;
char str[1000],str1[1000];
printf("Enter a sentence\n");
gets(str);
i=0;
while(str[i]!='\0')
{
if(str[i]!=' '&&(!isdigit(str[i])))
{
printf("%s ",alphamorse[toupper(str[i])-65]);
}
if(str[i]==' ')
{
printf(" ");
}
if(isdigit(str[i])&&str[i]!=' ')
{
printf("%s ",nummorse[str[i]-48]);
}

i++;
}
printf("\n");

Enumerated ,Structure And Union

The Type Definition(Typedef):

• typedef is a keyword used in C language to assign alternative names


to existing datatypes
• Its mostly used with user defined datatypes, when names of the
datatypes become slightly complicated to use in programs.

Syntax for using typedef:

typedef datatype alias-name/identifier;

Ex: typedef int my_int;

The identifiers doesn’t occupy any space in the computer memory.

Ex:

main()

typedef int my_int;

my_int a=10,b=20,c;

c=a+b;

printf(“sum is %d\n”,c);

}
Typedef usage in arrays:

main()

typedef int Array[5];

int i;

Array x ={10,20,30,40,50};

printf(“Array elements are:\n”);

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

{
printf(“%d\n”,x[i]);

Structures:

• Structure in c is a user-defined data type that enables us to store the


collection of different data types.

• Each element of a structure is called a member.

How to define structures?

• To define a struct, the struct keyword is used.

Syntax of structure:

struct structurename

datatype member1;

datatype member2;

...

};

Ex: struct employee

{
\\ members of structure

int id;

char name[10];

float salary;

};

• Here, struct is the keyword; employee is the name of the


structure; id, name, and salary are the members or fields of the
structure.
The following image shows the memory allocation of the structure
employee that is defined in the above example.

Here in 64 bit both int and float occupies 4 bytes

Typedef declarations:

Syntax:

typedef struct student

int rollno;

char name[20];

char course[20];

float fees;

};

struct stud1;

Initialization of structures:

• Initializing a structure means assigning some constants to the


members of the structure.
• When the user doesn’t explicitly initialize the structure ,then c
automatically does that.
For int and float members,the values are initialized to 0;and char and
string members are initialized to ‘\0’.
Syntax: Ex:
struct student
struct structname {
{ int roll_no;
datatype member_name1; char name[20];
datatype member_name2; char course[20];
…. float fees;
}; };
struct structname struct student
structvariable={constant1,co s1={01,”abcd”,”eee”,45000};
nstant2,..};

OR
struct structname
{
datatype member_name1;
datatype member_name2;
….
}struct_variable={constant1,constant2,..};
Ex:
struct student
{
int roll_no;
char name[20];
char course[20];
float fees;
} stud1={01,”abcd”,”eee”,45000};

Accessing the members of a structure:

• A structure members can be accessed using ‘.’ (dot) operator.

Syntax:

struct variable.member_name;

The dot opertor is used to select a particular member of the structure.

stud1.roll_no=1;

stud1.name=“abcd”;

stud1.course=“eee”;

stud1.fees=45000;
• To input values for data members of the structure variable stud1,we
can write

scanf(“%d”,&stud1.roll_no);

scanf(“%s”,&stud1.name);

• Similarily to print the values of structure variable stud1,we can write

printf(“%s”,stud1.course);

printf(“%f”,stud1.fees);

Example of the structure in C language to store many employees


information:
#include<stdio.h>

struct employee

int id;

char name[50];

float salary;

}e1,e2; //declaring e1 and e2 variables for structure

int main( )

//store first employee information


e1.id=101;

e1.name=“abcd”;

e1.salary=56000;

//store second employee information

e2.id=102;

e2.name=“cdef”;

e2.salary=126000;

//printing first employee information

printf( "employee 1 id : %d\n", e1.id);


printf( "employee 1 name : %s\n", e1.name);

printf( "employee 1 salary : %f\n", e1.salary);

//printing second employee information

printf( "employee 2 id : %d\n", e2.id);

printf( "employee 2 name : %s\n", e2.name);

printf( "employee 2 salary : %f\n", e2.salary);

getch();

Output:
employee 1 id : 101

employee 1 name : abcd

employee 1 salary : 56000.000000

employee 2 id : 102

employee 2 name : cdef

employee 2 salary : 126000.000000

Union:

• Like structure, Union in c language is a user-defined data type that is


used to store the different type of elements.
At once, only one member of
the union can occupy the
memory.
In other words, we can say
that the size of the union in
any instance is equal to the
size of its largest element.

Defining union:

• The union keyword is used to define the union

Syntax to define union in c:

union union_name
{
data_type member1;
data_type member2; .
data_type memeberN;
};

Example to define unionfor an employee in c:

union employee
{
int id;
char name[50];
float salary;
};
Initializing and accessing union members is same as structure.

#include <stdio.h>

union employee

int id;

char name[50];

}e1; //declaring e1 variable for union

int main( )

{
//store first employee information

e1.id=101;

e1.name=“abcd”;

//printing first employee information

printf( "employee 1 id : %d\n", e1.id);

printf( "employee 1 name : %s\n", e1.name);

getch();

Output:

employee 1 id : 1869508435
employee 1 name : abcd
• As you can see, id gets garbage value because name has large memory
size. So only name will have actual value.

Advantage of union over structure:

• It occupies less memory because it occupies the size of the largest


member only.

Disadvantage of union over structure:

• Only the last entered data can be stored in the union. It overwrites
the data previously stored in the union.
Difference between structure and union:

Difference between array and structure:

Enumerated data type:

• An enumerated type is a user defined data type.


• it gives numbers to the name

Creating an enumerated data type:

• To define enumerated data types,we use the keyword enum

Syntax:

enum enumeration_name{identifier1,identifier2,…identifier n};

• The enum keyword is basically used to declare and initialize a sequence


of integer constants.
• There are two ways to define the variables of enum type as follows.
1. enum week{sunday, monday, tuesday, wednesday,thursday, friday,
saturday};
2. enum week day;

Example:

#include<stdio.h>

enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};

enum day{Mond,tues,Wedn, Thurs, Frid=18, Satu=11, Sund};

main()

printf("The value of enum week:%d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon


,Tue, Wed, Thur, Fri, Sat, Sun);

printf("The default value of enum day:%d\t%d\t%d\t%d\t%d\t%d\t%d",Mond


, Tues, Wedn, Thurs, Frid, Satu, Sund);

getch();

Output:

The value of enum week: 10 11 12 13 10 16 17

The default value of enum day: 0 1 2 3 18 11 12

Programming Application:
Mainly C Language is used for Develop Desktop application and system
software. Some application of C language are given below

• C programming language can be used to design the system software like


operating system and Compiler.
• To develop application software like database and spread sheets.
• For Develop Graphical related application like computer and mobile
games.
• To evaluate any kind of mathematical equation use c language.
• C programming language can be used to design the compilers.
• UNIX Kernal is completely developed in C Language.
• For Creating Compilers of different Languages which can take input
from other language and convert it into lower level machine dependent
language.
• C programming language can be used to design Operating System.
• C programming language can be used to design Network Devices

You might also like