Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Character Arrays Strings Material

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

Unit:5 Character Arrays, Strings and Files

1) What is character array? How to declare and initialize


it? Answer:
Definition:
 A character array is a sequence of characters with same data type that shares a common name.
Declaration of character array
 A string variable is always declared as an array of characters.
Syntax:
char string_name[size];
 where, size is the number of characters.
Example:
char name[10];
 When the compiler assigns a character string to a character array, it automatically supplies a null
character ‘\0’ at the end of the string.
 Therefore, the size should be equal to the maximum number of characters in the string plus one.
Initialization of character array
Example 1:
char city[9]=“NEW YORK”;
char city[9]={‘N’,’E’,’W’,’ ’,’Y’,’O’,’R’,’K’,’\0’};

Example 2:
char name[10]= “WELL DONE”;

which declares the name as a character array variable that can hold a maximum of 10
characters.

 When the compiler sees a character string, then it terminate it with an additional null character.
So, the element name[9] holds the null character ‘\0’.

 When declaring character arrays, we must allow one extra element space for the null
character(‘\0’).

2) Explain sscanf ( ) and sprintf ( )


function. Answer:
 sscanf() function is used to extract strings from the given string.
Syntax:
sscanf(characterArray, "Conversion specifier", variables);
 This will extract the data from the character array according to the conversion specifier and store
into the respective variables.
 sscanf() will read subsequent characters until a whitespace is found (whitespace characters are
blank, newline and tab).

Page 1
Program of sscanf( ) function.

#include<stdio.h>
#include<conio.h>
void main( )
{
char name[50]={“SACHIN RAMESH TENDULKAR”};
char fname[10],mname[20],lname[10];
sscanf(name,”%s %s
%s”,fname,mname,lname); printf(“First Name =
%s“,fname); printf(“Middle Name =
%s“,mname); printf(“Last Name = %s“,lname);
getch();
}
 sprintf() function is exactly opposite to sscanf() function. Sprint() function writes the formatted
text to a character array.
Syntax:

sprintf (CharacterArray,"Conversion Specifier", variables);


Program for sprintf( ) function.

#include<stdio.h>
#include<conio.h>
void main( )
{
char name[50];
char fname[10]= {“SACHIN”};
char mname[20]={“RAMESH”};
char lname[10]={“TENDULKAR”};
sprintf(name,”%s %s %s”,fname,mname,lname);
printf(“Full Name = %s”,name);
getch();
}

3) What is String? How to declare and define


String? Answer:
 A string is a sequence of characters that is treated as single data item.
 It is written between double quotations.
Declaring of String Variable

 A string variable is always declared as an array of characters.


Syntax:
char string_name[size];
 where, size is the number of characters.
Example:
char name[15];

Page 2
 When the compiler assigns a character string to a character array, it automatically supplies a null
character ‘\0’ at the end of the string.
 Therefore, the size should be equal to the maximum number of characters in the string plus one.
Initialization of String Variable

Example:
char city[9]=“NEW YORK”;
char city[9]={‘N’,’E’,’W’,’ ’,’Y’,’O’,’R’,’K’,’\0’};

When we initialize a character array by listing its elements, we must supply explicitly the null
terminator.

Using scanf function:


Example:
char address[50];
scanf( “%s”, address);

Using gets function:


Example:
char city[10];
gets(city);
printf( “%s”, city);

4) Define string. List standard string functions


Answer:
 A string is a sequence of characters that is treated as single data item.
 It is written between double quotations.
 The operation performed on character strings are
1) Reading & Writing strings
2) Combining strings together
3) Copying one string to another
4) Comparing string for equality

String handling function

Function Action (Use)


strcat( ) Concatenates two strings
strcmp( ) Compares two strings
strcpy( ) Copies one string into another
strlen( ) Find the length of a string

5) Explain Any Three String Handling Function with


Example. Answer:

Page 3
String handling function
Function Action (Use)
strcat( ) Concatenates two strings
strcmp( ) Compares two strings
strcpy( ) Copies one string into another
strlen( ) Find the length of a string

1) strcat( ) function
 It joins two string together.
Syntax:
strcat(string1, string2);
Where, string1 & string2 are character arrays.
Example:
char str1[10] = “Good”;
char str2 [10]= “Morning”;
strcat(str1, str2);
printf(“str1 = %s”,str1);
Output
Str1 = GoodMorning
 strcat function may also append a string constant to a string variable.
strcat(str1, “Morning”);
 C also supports nesting of strcat functions.
strcat(strcat(str1,str2), str3);
 which concatenates all the three string together and the final string is stored in str1.

2) strcmp( ) function
 It compares two strings and return 0 if they are equal.
 If they are not equal, then it has numeric difference between the first nonmatching characters in
the strings.
Syntax:
strcmp(string1, string2);
.
Example 1:
char
str1[10]=“ram”;
char
str2[10]=“ram”;
strcmp(str1, str2);
Example 2:
strcmp(“RAJA”, “ROJA”)
 In example 1 both the strings are same so the function strcmp return 0.
 In example 2 both strings are different so the function strcmp returns the numeric difference
between ASCII “A” and ASCII “O”. Which is -14.
 If the return value is negative it means string1 is alphabetically above to string2.

3) strcpy( ) function
 It is a one type of string-assignment operator.
Page 4
Syntax:

Page 5
strcpy(string1, string2);
Example:
strcpy(subject, “PC”);
 Which assign the string “PC” to string variable subject.
 Similarly, the statement strcpy(name1, name2); will assign the contents of the string variable
name2 to the string variable name1.
 But, the size of array name1 should be large enough to store the content of name2.

6) Explain strlen( ) and strcpy ( )function.


Answer:
strcpy( ) function
 It is a one type of string-assignment operator.
Syntax:
strcpy(string1, string2);
Example:
strcpy(subject, “PC”);
 Which assign the string “PC” to string variable subject.
 Similarly, the statement strcpy(name1, name2); will assign the contents of the string variable
name2 to the string variable name1.
 But, the size of array name1 should be large enough to store the content of name2.

strlen( ) function
 It is used to count the length of string or number of characters in a string.
Syntax:
int n = strlen(string);
 Where n is an integer variable, which stores the length of the string.
 The counting end at the first null character.

7) Explain strcmp( ) and strcat( ) function


Answer:
strcat( ) function
 It joins two string together.
Syntax:
strcat(string1, string2);
Where, string1 & string2 are character arrays.
Example:
char str1[10] = “Good”;
char str2 [10]= “Morning”;
strcat(str1, str2);
printf(“str1 = %s”,str1);
Output
Str1 = GoodMorning
 strcat function may also append a string constant to a string variable.
strcat(str1, “Morning”);
 C also supports nesting of strcat functions.
strcat(strcat(str1,str2), str3);
 which concatenates all the three string together and the final string is stored in str1.
Page 6
strcmp( ) function
 It compares two strings and return 0 if they are equal.
 If they are not equal, then it has numeric difference between the first nonmatching characters in
the strings.
Syntax:
strcmp(string1, string2);
.
Example 1:
char
str1[10]=“ram”;
char
str2[10]=“ram”;
strcmp(str1, str2);
Example 2:
strcmp(“RAJA”, “ROJA”)
 In example 1 both the strings are same so the function strcmp return 0.
 In example 2 both strings are different so the function strcmp returns the numeric difference
between ASCII “A” and ASCII “O”. Which is -14.
 If the return value is negative it means string1 is alphabetically above to string2.

8) Write a program to reverse a given


string. Answer:
#include<stdio.h>
#include<string.h>
main()
{
char str[50],revstr[50];
int i,j=0,n;
printf("Enter the string to be reversed : ");
gtes(str);
N=strlen(str);
for(i=n-1;i>=0;i--)
{
revstr[j]=str[i]; j+
+;
}
revstr[j]='\0';
printf("Input String : %s",str);
printf("\nOutput String : %s",revstr);
getch();
}

9) Write a Program to find out Given String is Palindrome or


not. Answer:
#include<stdio.h>
#include<string.h>
main()
Page 7
{

Page 8
char str[50],revstr[50];
int i,j=0,n;
printf("Enter the string to be reversed : ");
gets(str);
n=strlen(str);
for(i=n-1;i>=0;i--)
{
revstr[j]=str[i]; j+
+;
}
revstr[j]='\0';
if(strcmp(revstr,str)==0)
{
printf("\nThe string is a palindrome");
}
else
{
printf("\nThe string is not a palindrome");
}
getch();
}

10) Give the syntax of gets () and puts () function and Explain with Example.
Answer:
gets() function
 gets() accepts any line of string including spaces from the keyboard.
 gets() stops reading character from keyboard only when the enter key is pressed.
Syntax:
gets (variable_name);
puts () function
 puts displays a single / paragraph of text to the standard output device.
Syntax:
puts (variable_name);
Example: #include<stdio.h>
#include<conio.h>
void main()
{
char a[20];
gets(a);
puts(a);
getch();
}

Page 9
Files
1) What is File Management?
Answer:

 The printf() and scanf() function are used for to read and write the data.
 With the use of these functions, the entire data is lost when either the program is terminated or the
computer is turned off.
 With the help of Files, we can store data on disks and read when necessary.
 A file is a place on the disk where a group of related data is stored.
 Text Files are human readable and it is a stream of plain English characters.
 Binary Files are not human readable. It is a stream of processed characters and ASCII symbols.
 C supports basic file operations which includes,
(1) Naming a file
(2) Opening a file
(3) Reading data from a file
(4) Writing data to a file
(5) Closing a file

2) List out Function name and its Operations for

File. Answer:

Function Operation
Name
fopen() Creates s new file for use OR Opens an existing file for use
fclose() Closes a file which has been opened for use
fgetc() Reads a character from a file
fputc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
fgetw() Reads an integer from a file
fputw() Writes an integer to a file
fseek() Sets the position to a desired point in the file
ftell() Gives the current position in the file
rewind() Sets the position to the beginning of the fie

Page 10
3) Explain File Opening Mode.

Answer:

Mode Working

“r” Open an existing file for reading purpose only.


“w” Open a new file for writing only.f file exists overwrite it.
“a” Open file for adding new data at the end of file.(If file doesnot exists then it
creates new file)
“r+” Open existing file for both reading and writing.(Start at Beginning)
“w+” Open existing file for reading and writing.(Overwrite file)
“a+” Open existing file for reading and appending(at the end)

4) Explain File Handling Functions with

Example. Answer:

 fopen():
 Creates s new file for use OR Opens an existing file for use
 Syntax: FILE *fp;
fp=fopen(“Filename”,”mode”);
 Here, FP is a pointer to the data type FILE.
 Second statement open a file named filename and assign an identifier to the FILe type.
 Mode specify the purpose of opening this file.
 Example: FILE *fp;
fp=fopen(“pr1.c”,”r”);

 fclose():
 Closes a file which has been opened for use
 A file must be closed as soon as all operation are over.
 Syntax: fclose(File Pointer);
 Example: FILE *fp;
fp=fopen(“pr1.c”,”r”);
- - - - -
fclose(fp);
 fgetc():
 Reads a character from a file.
 This function handle one character at a time.

Page 11
 Syntax: c= fgetc(fp);
 Here c is a character type variable and fp is a file pointer.
 This statement reads a character from a file that has been open in read mode.

 putc():
 Writes a character to a file
 Syntax:fputc(c, fp);
 Here c is a character type variable and fp is a file pointer.
 This statement writes a character contained in the character variable c to the file ,which is pointed
by fp.

 fgetw():
a. Reads an integer from a file
 Syntax: integer variable=getw(fp);

 fputw():
 Writes an integer to a file
 Syntax: putw(integer,fp);

 feof():
 It returns non zero value only if end of file has reached, otherwise return zero.
 Syntax: feof(fp);

 fprintf():
 fprintf() write all the data written in list to the file.
 Syntax: fprintf(fp, “control string”, list);

 Where, fp is a file pointer associated with a file.


 The control string contains output specifications for the items of the list.
 The list may include variables, constants and strings.

 fscanf():
 fscanf() reads data from file and store in variables declared in list.
 Syntax: fscanf(fp, “control string”, list);
 Where, fp is a file pointer associated with a file.

5) Explain functions for Random Access to File.


 If we want to access only a part of file and not reading the other part, then fseek(),ftell() and
rewind() functions are used.

Page 12
 fseek():Sets the position to a desired point in the file
 It is used to move the file position to a desired location within the file.
 Syntax: fseek (fp, offset, position);
 Offset specify number of bytes to be moved from the location specified by position.
 Position can take one of the three value.
 0 beginning of the file, 1 Current position, 2End of file.
 Offset may be positive, means move forward or negative means move backward.

 ftell():Gives the current position in the file.


 This functions are used in saving the current position of a file, which can be used later in
the program.
 Example: n= ftell(fp);
 Here, ftell() takes a fp pointer and return number of bytes, correspond to the current position.
 It means n bytes already been read or written.

 rewind():Sets the position to the beginning of the file.


 The function takes a file pointer and resets the position to the start of the file.
 Function help us in reading a file more than once, without having to close and open the file.
 Syntax: rewind(fp);

6) Explain Command line Argument with

example. Answer:

 A command line argument is a parameter which is passed to a program at the time when it is
executed from the command line.
 Program execution always start with main() Function.
 Main() can have arguments.
 After successful compilation and linking, compiler generates exe file.
 These arguments are passed with executable file.

 It takes two arguments called argc and argv.


 void main (int argc, char *argv[ ])
 The first argument is argc known as argument count which tells the total numbers of arguments are to be
given.
 The second argument argv known as an array of character pointer pointing to argument string.
 In command line argument the first parameter is always the program name and therefore argv[0] always
represents the program name.
 Example:
 Suppose we create a c file test.c.
 After alt+F9 and ctrl + F9 , exe file test.exe is generated.
 In command line,

Page 13
C:\ > test.exe hello good morning
Here, argc=4
argv[0] store test.exe
argv[1] store hello
argv[2] store good
argv[3] store morning
Program:
#include<stdio.h>
#include<conio.h>
void main (int argc, char * argv [])
{
int i;
clrscr ();
printf (“argc=%d\n\n”argc);
for(i=0;i<argc;i++)
{
printf(”argv[%d]:%s\n”,i,argv[i]);
}
getch();
}

7) Explain Input/output Functions.


Answer:
1. scanf()
 It is used to read all types of data.
 It cannot read whitespace between strings.
 It can read multiple data at a time by multiple format specifier in one scanf().
 Example: scanf(“%d%d”,&a,&b);

2. printf()
 It is used to display all types of data and messages.
 It can display multiple data at a time by multiple format specifier in one printf().
 Example: printf(“a=%d b=%d” ,a, b);

3. gets()
 It is unformatted input function.
 It is used to read a single string with white spaces.
 Example: char str[10];
gets(str);

4. getchar(),getche(),getch()
 It is unformatted input function.

Page 14
 It is used to read single character at a time.
 getchar() function requires enter key to terminate input while getche() and getch() does
not require.
 getch() doesnot display the input character while getchar() and getche() display the input
character on the screen.
 Example:
char ch;
ch=getchar();
ch=getche();
ch=getch();
5. puts()
 It is unformatted output function.
 It is used to display a string at a time.
 Example: char str[10]=”Hello”;

puts(str);

6. putchar()
 It is unformatted output function.
 It is used to display single character at a time.
 Example: putchar(ch);

8) Explain Error Handling During I/O


Operations Answer:

 To detect I/O errors in the file, we can use the feof and ferror function.

FEOF():

 It is used to test for end of file condition.


 It takes file pointer as argument.
 If all the data from the specified file has been read then return nonzero integer otherwise returns a
zero value.
 Example:
if (feof(fp))
printf(“End of data\n”);

 It display the message End of data, on reaching the end of file condition.

Page 15
FERROR ():
 It reports the status of the file indicated.
 It takes FILE pointer as argument and error has been detected ,then return non zero, otherwise it
return zero.
 Example:
if (ferror(fp)!=0)
printf(“An error has occured\n”);
 If the reading is not successful, then an error has occurred.

9) Explain File Pointer and its usage in detail.

 A file pointer is a pointer to a structure, which contains information about the file, including its name,
current position of the file, whether the file is being read or written, and whether errors or end of the file
have occurred.
 Example: FILE *fp;
 Here, fp is the file pointer that points to a FILE structure.

10) Give the difference between text mode file and binary mode file.

AnsText Mode File Binary Mode File


It can be read by human. It cannot be read by human.
It is a stream of plain English characters. It is a stream of processed characters and
Data is in the form of alphabets and ASCII symbols.
numerals Data is in the form of 0 and 1.
Accessing time is more as compared to Accessing time is less as compared to text
binary Mode File. Files
Extension is .txt Extension is .doc
Consume more space in memory than
Consume less space in memory than text files.
binary files.

11) Write a C Program to write character in File.

#include<stdio.h>
#include<conio.h>
void main()
{
char c;
FILE *fp;
clrscr();
fp=fopen("a.txt","r");
c='A';
putc(c,fp);

fclose(fp);
getch();
}

Page 16
12) Write a C Program to read character from File.

#include<stdio.h>
#include<conio.h>
void main()
{
char c;
FILE *fp;
clrscr();
fp=fopen("a.txt","r");

c = getc(fp);
printf(“ % c”, c);

fclose(fp);
getch();
}

13) Write a C Program to write data in File(using fputc()).

#include<stdio.h>
#include<conio.h>
void main()
{
char c;
FILE *fp;
clrscr();
fp=fopen("abc.txt","w");
printf("Enter string\n");
c= getchar();

while( c != EOF)
{
fputc(c,fp);
c=getchar();
}
fclose(fp);
getch();
}

Page 17
14) Write a C Program to read data from File(using fgetc()). Or
Write a C Program that read and display content of a given
file.

#include<stdio.h>
#include<conio.h>
void main()
{
char c;
FILE *fp;
clrscr();
fp=fopen("abc.txt","w");

c=fgetc(fp);
while( c != EOF)
{ printf("%c",c);
c=fgetc(fp);

}fclose(fp); getch();
}

15) Write a C Program to copy a File.

Page 18
#include<stdio.h>
#include<conio.h>
void main()
{
char c;
FILE *r,*w;
clrscr();
r=fopen("pro.txt","r");
w=fopen("pronew.txt","w");

c=fgetc(r);
while( c != EOF)
{ fputc(c,w);
c=fgetc(r);

}
fclose(r);
fclose(w);
getch();
}

Page 19
Page 20
Page 21

You might also like