You are on page 1of 62

EKT150 INTRODUCTION TO

COMPUTER PROGRAMMING
Array (String)
Part II

Mdm. Rusnida Romli


Faculty of Electronics Engineering Technology
Recaps…
What is Array? (Example)
Multiple instance with the same data type could be declared as
an array:
Declaration int aiNum[5]; aiNum

Assign 5 to aiNum[0]=5; aiNum[0] 5


Element
element aiNum[1]=10; aiNum[1] 10 aiNum[1] has
with index 15 index 1 and value
number 0 aiNum[2]=15; aiNum[2] 10
20
aiNum[3]=20; aiNum[3]
25
aiNum[4]=25; aiNum[4]

 int is the data type of the array


 5 in squared bracket is the number of components/elements in the
array
 Elements are referred to an index number
 Index number starts with 0 2
Recaps….
Example : 2-Dimensional Array

int aiValue[4][2]; //declaration

aiValue[2][1]=5;//assignment of value

Column
0 1
0 aiValue[0][0] aiValue[0][1]
1 aiValue[1][0] aiValue[1][1]
Row
2 aiValue[2][0] aiValue[2][1]
3 aiValue[3][0] aiValue[3][1]

3
Outline

1. Introduction to Strings
2. Declaration of Strings
3. Fundamentals of Strings & Characters
4. Initialization of Strings
5. Assigning Values to Strings
6. Character and String Manipulations
7. Strings Conversion Functions
8. ASCII Table

4
What is a String?
• A string is a series of characters treated as a single unit.
– Also known as character array
• Strings can be treated as array of type char used to store names
of people, places, or anything that involves a combination of
letters.
- For example: char name[30]; Character String
• A string may include letters, digits and various special characters
such as +, -, *, ? and $.
• String literals, or string constants, in C are written in double
quotation marks ( “ ” ) as follows:
Example:
“John Doe” (a name)
“99999 Main Street” (a street address)
“Kangar, Perlis” (a city and a state)
“(012) 123-8755” (a telephone number)
5
What is a String?
• The data type string is a programmer-defined and is not part
of the C language
• A string with no characters is called a null or empty string.
“ ” is the empty string.
• Every character in a string has a relative position in the
string.
• The position of the first character is 0, position of the second
is 1, and so on.
• The length of a string is the number of character in it.
of a string is the address of its first character.

6
Example
String Position of a Character Length of the String
in the String

“William Jacob” Position of ‘W’ is 0 13


Position of the first ‘i’ is 1
Position of ‘ ’ (the space) is 7
Position of ‘J’ is 8
Position of ‘b’ is 12

“Mickey” Position of ‘M’ is 0 6


Position of ‘i’ is 1
Position of ‘c’ is 2
Position of ‘k’ is 3
Position of ‘e’ is 4
Position of ‘y’ is 5

7
Declaration of Strings
• Declaration of string/character array
char variable_name[length];

• An example of declaration of an array (or string of characters):

char name[10]; //declaration

char name[10];
can store a string up to 10
characters long, and may visualize it as below
name

 can use to store “William”, “John Doe” etc and all strings that shorter than defined
length
 It is not necessary that this max size of 10 characters should at all the times fully used
 The last value in the string will be a null character (‘\0’).
8
Declaration of Strings (cont…)
• name is an array of 10 elements of type char, could
be represented by storing the strings of characters,
e.g. “William” and “John Doe” in the following way:
name
W i l l i a m \0

to indicate indefinite
end of string values

J o h n D o e \0

9
Declaration of Strings (cont…)

• Also can be declared as a character array or a variable of type char *


char name[] = “William";
char *name = “William";

10
Formatted Input/ Output
• Formatted input
– Use scanf
scanf("%s", name);
• Copies input into name[]
• Does not need & (because a string is a pointer)
– Remember to leave room in the array for the null character ('\0’)

• Formatted output
– Use printf
printf(“%s”,name);

11
Example : Input and Output of String
• Input and output characters using scanf() and printf()
• Example program:

#include<stdio.h>

int main()
{
char name[30];
printf("Enter name: ");
scanf(“%s”,name); //read string from user

printf(“Hi %s\n“,name); //display string


return 0;
}

12
Initialization of String
• Similar to array, but each character is enclosed in ‘ ’ or “ ”.
• Example:
– char newString[]={‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’, ‘\0’};
– char newString[]= “Welcome”;
• ‘\0’ is automatically inserted

• The difference is that single quotes (‘) are used to specify single
character constants and null character must be added at the
end of the sentence.
char newString[]= {‘W’,‘e’,‘l’,‘c’,‘o’,‘m’,‘e’,‘\0’};

Single quotes – null char must be added

13
Initialization of String

• On the other hand, double quotes (“) are constant that


specify sequence of characters and always have a null
character (‘\0’) automatically inserted at the end.

   char newString[] = “Welcome”;

Double quotes – null char automatically inserted

14
Initialization of String (cont…)

• The examples below are NOT VALID for string /


characters array.

newString = “Welcome”; //no [] and data


type

newString [] =“Welcome”; //no data type

newString = {‘W’,‘e’,‘l’,‘c’,‘o’,‘m’,‘e’,‘\0’};
//no [] and data type

15
Assigning Values to String
• The left hand side value of an assignation can only be array items
and not the entire array, a possible way to assign a string of
characters to an array of char can be shown as:

newString[0] = ‘W’;
newString[1] = ‘e’;
newString[2] = ‘l’;
newString[3] = ‘c’;
newString[4] = ‘o’;
newString[5] = ‘m’;
newString[6] = ‘e’;
newString[7] = ‘\0’;

16
Character and String Manipulation
• A program may need to verify/perform, e.g.
– Calculation of the string size:
– Copy one string to another:
– Appends one string to another:

• Built-in functions available – makes it easier.


– Standard input/output library <stdio.h>
– General utilities library <stdlib.h>
– Character handling library <ctype.h>
– String handling library <string.h>
17
Example 1.1: Input and Output of String without using
Built-in Function
• Input and output characters using scanf() and printf()
function from <stdio.h>
• Example program:

#include<stdio.h>

int main()
{
char name[30];
printf("Enter name: ");
scanf(“%s”,name); //Function to read string from user

printf(“Hi ");
printf(“%s\n”,name); //Function to display string
return 0;
}

18
Example 1.1: Input and Output of String without using
Built-in Function
• Input and output characters using scanf() and printf()
function from <stdio.h>
• Example program:

#include<stdio.h> Enter name : John Michael


Hi John
int main()
{
char name[30];
printf("Enter name: ");
scanf(“%s”,name); //Function to read string from user

printf(“Hi ");
printf(“%s\n”,name); //Function to display string
return 0;
}

19
Example 1.2: Input and Output of String using Built-in
Function
• Input and output characters using gets() puts() function from
<stdio.h>
• Example program:

#include<stdio.h>

int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user

printf(“Hi ");
puts(name); //Function to display string
return 0;
}

20
Example 1.2: Input and Output of String using Built-in
Function
• Input and output characters using gets() puts() function from
<stdio.h>
• Example program:

#include<stdio.h> Enter name : John Michael


Hi John Michael
int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user

printf(“Hi ");
puts(name); //Function to display string
return 0;
}

21
Example 2.1: Input and Output of String without using
Build-in Function
• Input and output for array of strings
• Example program:
#include<stdio.h>

int main()
{
char name[3][30];
printf("Enter 3 names:\n");

for(i=0;i<3;i++)
scanf(“%s”,name[i]);//Function to read string from user

printf(“\nName Entered:\n”);
for(i=0;i<3;i++)
printf(“%s\n”,name[i]); //Function to display string

return 0;
} 22
Example 2.1: Input and Output of String without using
Build-in Function
• Input and output for array of strings
• Example program:
Enter 3 names:
#include<stdio.h> Michael
John
int main()
{
Sarah
char name[3][30];
printf("Enter 3 names:\n");Names Entered:
Michael
for(i=0;i<3;i++)
John
scanf(“%s”,name[i]);//Function to read string from user
Sarah
printf(“\nName Entered:\n”);
for(i=0;i<3;i++)
printf(“%s\n”,name[i]); //Function to display string

return 0;
} 23
Example 2.2: Input and Output of String using Build-in
Function
• Input and output of array of strings using gets() puts() function
from <stdio.h>
• Example program:
#include<stdio.h>

int main()
{
char name[3][30];
printf("Enter 3 names:\n");

for(i=0;i<3;i++)
gets(name[i]); //Function to read string from user

printf(“\nName Entered:\n”);
for(i=0;i<3;i++)
puts(name[i]); //Function to display string

return 0;
} 24
Example 2.2: Input and Output of String using Build-in
Function
• Input and output of array of strings using gets() puts() function
from <stdio.h>
• Example program: Enter 3 names:
#include<stdio.h>
Michael Lee
John Doe
int main() Sarah Anne
{
char name[3][30];
printf("Enter 3 names:\n");Names Entered:
Michael Lee
for(i=0;i<3;i++) John Doe
gets(name[i]); //Function to read string from user
Sarah Anne
printf(“\nName Entered:\n”);
for(i=0;i<3;i++)
puts(name[i]); //Function to display string

return 0;
} 25
Example 3.1: Calculation of String Size without Build-in
Function
• Calculation of string size by measuring number of elements from the string
• Example program:

#include <stdio.h>

int main()
{
char newString1[] = {'W','e','l','c','o','m','e','\0'};
char newString2[] = “Bye Bye";
int i,length_newString1=0,length_newString2=0;
for(i=0;newString1[i]!='\0';i++)
length_newString1++;
for(i=0;newString2[i]!='\0';i++)
length_newString2++;
//size of string Welcome
printf ("Size of ‘%s’ is %d\n", newString1,length_newString1);
//size of string Good Bye
printf ("\nSize of ‘%s’ is %d\n",newString2, length_newString2);
return 0;
}
26
Example 3.1: Calculation of String Size without Build-in
Function
• Calculation of string size by measuring number of elements from the string
• Example program:

#include <stdio.h>

int main()
{
char newString1[] = {'W','e','l','c','o','m','e','\0'};
char newString2[] = “Bye Bye";
int i,length_newString1=0,length_newString2=0;
for(i=0;newString1[i]!='\0';i++)
length_newString1++; Size of `Welcome’ is 7
for(i=0;newString2[i]!='\0';i++) Size of `Bye Bye’ is 7
length_newString2++;
//size of string Welcome
printf ("Size of ‘%s’ is %d\n", newString1,length_newString1);
//size of string Good Bye
printf ("\nSize of ‘%s’ is %d\n",newString2, length_newString2);
return 0;
} 27
Example 3.2: Calculation of String Size
using Build-in Function
• Calculation of string size using strlen(char *string) function from
<string.h>
– char is 1 byte, the total number of alphabets would be the size of the string.
– Example program:

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

int main()
{
char newString1[] = {'W','e','l','c','o','m','e','\0'};
char newString2[] = “Bye Bye";

//size of string Welcome


printf ("Size of ‘%s’ is %d\n", newString1,strlen(newString1));

//size of string Good Bye


printf ("\nSize of ‘%s’ is %d\n",newString2,strlen(newString2));

return 0;
}
28
Example 3.2: Calculation of String Size
using Build-in Function
• Calculation of string size using strlen(char *string) function from
<string.h>
– char is 1 byte, the total number of alphabets would be the size of the string.
– Example program:

#include <stdio.h>
#include <string.h> Size of `Welcome’ is 7
Size of `Bye Bye’ is 7
int main()
{
char newString1[] = {'W','e','l','c','o','m','e','\0'};
char newString2[] = “Bye Bye";

//size of string Welcome


printf ("Size of ‘%s’ is %d\n", newString1,strlen(newString1));

//size of string Good Bye


printf ("\nSize of ‘%s’ is %d\n",newString2,strlen(newString2));

return 0;
}
29
Example 4.1: Copy a String to Another String without
Build-in Function
• Example program:

#include <stdio.h>

int main()
{
char newString1[50] = {'W','e','l','c','o','m','e','\0'};
char newString2[50] = “Bye Bye";
int i;

printf(“Before String Copy\n");


printf(“newString1 is %s\n",newString1);
printf(“newString2 is %s\n\n",newString2);
for(i=0;newString1[i]!='\0';i++)
newString2[i]=newString1[i];
printf(“After String Copy\n");
printf(“newString1 is %s\n",newString1);
printf(“newString2 is %s\n",newString2);

return 0;
}
30
Example 4.1: Copy a String to Another String without
Build-in Function
• Example program:

#include <stdio.h>

int main()
{
char newString1[50] = {'W','e','l','c','o','m','e','\0'};
char newString2[50] = “Bye Bye";
int i;

printf(“Before String Copy\n");


printf(“newString1 is %s\n",newString1);
printf(“newString2 is %s\n\n",newString2); Before String Copy
for(i=0;newString1[i]!='\0';i++) newString1 is Welcome
newString2[i]=newString1[i];
newString2 is Bye Bye
printf(“After String Copy\n");
printf(“newString1 is %s\n",newString1);
printf(“newString2 is %s\n",newString2); After String Copy
newString1 is Welcome
return 0; newString2 is Welcome
}
31
Example 4.2: Copy a String to Another String using
Build-in Function
• Example program:

#include <stdio.h>

int main()
{
char newString1[50] = {'W','e','l','c','o','m','e','\0'};
char newString2[50] = “Bye Bye";
int i;

printf(“Before String Copy\n");


printf(“newString1 is %s\n",newString1);
printf(“newString2 is %s\n\n",newString2);
strcpy(newString2,newString1);
printf(“After String Copy\n");
printf(“newString1 is %s\n",newString1);
printf(“newString2 is %s\n",newString2);

return 0;
}

32
Example 4.2: Copy a String to Another String using
Build-in Function
• Example program:

#include <stdio.h>

int main()
{
char newString1[50] = {'W','e','l','c','o','m','e','\0'};
char newString2[50] = “Bye Bye";
int i;

printf(“Before String Copy\n");


printf(“newString1 is %s\n",newString1);
printf(“newString2 is %s\n\n",newString2); Before String Copy
strcpy(newString2,newString1); newString1 is Welcome
printf(“After String Copy\n"); newString2 is Bye Bye
printf(“newString1 is %s\n",newString1);
printf(“newString2 is %s\n",newString2);
After String Copy
return 0; newString1 is Welcome
} newString2 is Welcome
33
Controlling Case of a Character
• In C, upper case letter, e.g. ‘K’ is not equal to lower case ‘k’
• So in C programming, you usually use:
if (cChoice == ‘K’ || cChoice == ‘k’), OR
while (cChoice == ‘Y’ || cChoice == ‘y’)

• The case of a character can be controlled using tolower() and


toupper() functions from <ctype.h>
– temporarily converts a letter/char to uppercase or lowercase before
comparing it
toupper(int c)
tolower(int c)
 Also, can use functions that converts the whole string to upper or
lowercase from <string.h>
strupr(char *string)
strlwr(char *string) 34
Example 5.1: Controlling Case of a
Character
#include<ctype.h>

char cChoice;

printf ( “Continue? (Y or N) : “);


scanf (“%c”, &cChoice);

while(tolower(choice)=='y')
{

scanf("%s",&choice);

}

35
Example 5.2: Controlling Case of a
Character
//To convert a string to uppercase
#include <stdio.h>
#include <string.h>

void main()
{
char acName[20]; //declare an array of
//characters 0-79

printf("Enter in a name in lowercase\n");


scanf( "%s", acName );
strupr(acName);
printf("The name in uppercase is %s",
acName );
}
36
Example 5.2: Controlling Case of a
Character
//To convert a string to uppercase
#include <stdio.h>
#include <string.h>

void main()
{
char acName[20]; //declare an array of
//characters 0-79

printf("Enter in a name in lowercase\n");


scanf( "%s", acName );
strupr(acName); Enter in a name in lowercase
printf("The name in uppercase
john is %s",
acName ); The name in uppercase is JOHN
}
37
Controlling Case of a Character
• Real value does not changed.
• The functions only affect characters of letters or
alphabets.
– does not affect numbers and special characters such as
$ and %
• If the character is already lowercase or uppercase, the
function will not affect the real value
– return the original value
Example:
char cRepeat = ‘Y’;
cLetter = strupr(cRepeat);
cLetter = ?
38
Strings Conversion Functions
• Conversion functions
– In <stdlib.h> (general utilities library)
• Convert strings of digits to integer and floating-point values
– char digits [5] = “12345”;

Prototype Description
double atof( const char *nPtr ) Converts the string nPtr to double.
int atoi( const char *nPtr ) Converts the string nPtr to int.
long atol( const char *nPtr ) Converts the string nPtr to long int.
double strtod( const char *nPtr, Converts the string nPtr to double.
char **endPtr )
long strtol( const char *nPtr, Converts the string nPtr to long.
char **endPtr, int base )
unsigned long strtoul( const char Converts the string nPtr to unsigned
*nPtr, char **endPtr, int base ) long.
39
Strings Comparison Functions
• Comparing strings
– Computer compares numeric ASCII codes of characters in string

int strcmp( const char *s1, const char *s2 );


– Compares string s1 to s2
– Returns a negative number if s1 < s2, zero if s1 == s2 or a positive
number if s1 > s2

int strncmp(const char *s1,const char *s2, size_t


n );
– Compares up to n characters of string s1 to s2
– Returns values as above

40
ASCII Table
ASCII Character Set
0 1 2 3 4 5 6 7 8 9
0 nul soh stx etx eot enq ack bel bs ht
1 If vt ff cr so si dle dc1 dc2 dc3
2 dc4 nak syn etb can em sub esc fs gs
3 rs us sp ! “ # $ % & `
4 ( ) * + , - . / 0 1
5 2 3 4 5 6 7 8 9 : ;
6 < = > ? @ A B C D E
7 F G H I J K L M N O
8 P Q R S T U V W X Y
9 Z [ \ ] ^ _ ’ a b C
10 d e f g h i j k l m
11 n o p q r s t u v u
12 x y z { | } ~ del

‘A’  65, ‘a’  97


41
Example 6.1 : String Comparison
#include <stdio.h>
#include <string.h>

int main()
{
char acString1[20], acString2[20]; //declaration
int iResult;

printf( "Enter two strings: " );


scanf( "%s %s", acString1, acString2 );

iResult = strcmp( acString1, acString2);//comparing acString1 and


acString2

if (iResult > 0 )
printf( "\"%s\" is greater than \"%s\"\n",acString1, acString2 );
else if ( iResult == 0 )
printf( "\"%s\" is equal to \"%s\"\n",acString1, acString2 );
else
printf( "\"%s\" is less than \"%s\"\n",acString1, acString2 );

return 0;
}
42
Example 6.1 : String Comparison
#include <stdio.h>
#include <string.h>

int main()
{
char acString1[20], acString2[20]; //declaration
int iResult;

printf( "Enter two strings: " );


scanf( "%s %s", acString1, acString2 );

iResult = strcmp( acString1, acString2 );//comparing acString1 and


acString2

if ( iResult > 0 )
printf( "\"%s\" is greater than \"%s\"\n",acString1, acString2 );
else if ( iResult == 0 )
Entertotwo
printf( "\"%s\" is equal strings: computer programming
\"%s\"\n",acString1, acString2 );
else "computer" is less than "programming"
printf( "\"%s\" is less than \"%s\"\n",acString1, acString2 );

return 0; Enter two strings: programming computer


} "programming" is greater than "computer"
43
Example 6.2 : String Comparison
#include <stdio.h>
#include <string.h>

int main()
{
char acString1[ 20 ], acString2[ 20 ];
int iResult, iCompareCount;

printf( "Enter two strings: " );


scanf( "%s %s", acString1, acString2 );
printf( "How many characters should be compared: " );
scanf( "%d", &iCompareCount );

iResult = strncmp( acString1, acString2, iCompareCount );

if (iResult > 0 )
printf( "\"%s\" is greater than \"%s\" up to %d characters\n",
acString1, acString2, iCompareCount );
else if ( iResult == 0 )
printf( "\"%s\" is equal to \"%s\" up to %d characters\n",
acString1, acString2, iCompareCount );
else
printf( "\"%s\" is less than \"%s\" up to %d characters\n",
acString1, acString2, iCompareCount );
return 0;
44
}
Example 6.2 : String Comparison
#include <stdio.h>
#include <string.h>

int main()
{
char acString1[ 20 ], acString2[ 20 ];
int iResult, iCompareCount;

printf( "Enter two strings: " );


scanf( "%s %s", acString1, acString2 );
printf( "How many characters should be compared: " );
scanf( "%d", &iCompareCount );

iResult = strncmp( acString1, acString2, iCompareCount );


Enter two strings: computer computer
if (iResult > 0 ) How many characters should be compared: 8
printf( "\"%s\" "computer" is equal
is greater than to “computer"
\"%s\" up to 8 characters
up to %d characters\n",
acString1, acString2, iCompareCount );
Enter
else if ( iResult == 0 ) two strings: computer comp
printf( "\"%s\" How
is equal
manytocharacters
\"%s\" up to %dbecharacters\n",
should compared: 4
acString1, acString2, iCompareCount );
"computer" is equal to “comp" up to 4 characters
else
printf( "\"%s\" is less than \"%s\" up to %d characters\n",
Enter
acString1, two strings:
acString2, comp computer
iCompareCount );
return 0; How many characters should be compared: 5
} “comp" is less than "computer" up to 5 characters 45
Parallel Arrays
• Two (or more) arrays are called parallel if their corresponding
components hold related information
Example :
char acStudentIName[5][10] = {“John”, ”Sarah”, ”David”,
”Haley”, ”Matt” };
float afStudentMark[5]={67, 80, 78, 92, 72};

acStudentName Corresponding afStudentMark


information
acStudentName[0] J o h n \0 afStudentMark[0] 67
acStudentName[1] S a r a h \0 afStudentmark[1] 80
D a v i d \0 78
acStudentName[2] afStudentmark[2]
H a l e y \0 92
acStudentName[3] afStudentMark[3]
72
acStudentName[4] M a t t \0 afStudentmark[4]

46
Built in Functions for String Handling
• strcpy Copies one string to another
• strncpy Copies n characters of one string to another
• strlen Finds length of a string
• strcat Appends a string
• strncat Appends n characters of string
• strcmp Compares two strings
• strncmp Compares n characters of two strings
• strcmpi Compares two strings, non-case sensitive
• strlwr Converts a string to lowercase
• strupr Converts string to uppercase
• strchr Finds first occurrence of a given character
• strnset Sets n characters of string to a given character
• strrchr Finds last occurrence of given character in string
• strrev Reverses string
• strset Sets all characters of string to a given character
• strspn Finds first substring from given character set in string

47
Past Year Questions ( Final 2015/2016)
The following questions are based on C 1. #include<stdio.h>
program in the Figure. 2. #include<string.h>
3.  
a) Trace the output of the program
4. int main ()
5. {
6. char str1[20] = "Hello ";
7. char str2[20] = "World";
8. char str3[20];
b) Suppose you want to measure and 9.  
display the length of str1 and str3 10. strcpy(str3, str1);
BEFORE and AFTER the string 11. printf("strcpy(str3, str1) : %s\n", str3 );
manipulation at line 13 and line 16. 12.  
Write C statements to execute the task 13. strcat(str1, str2);
and state which line those C statements 14. printf("strcat(str1, str2) : %s\n", str1 );
should be placed 15.  
16. strcat( str3, str1);
17. puts(str3);
18.  
19. return 0;
20. }
Past Year Questions ( Final 2015/2016)
The following questions are based on C 1. #include<stdio.h>
program in the Figure. 2. #include<string.h>
3.  
a) Trace the output of the program
4. int main ()
strcpy(str3,str1) : Hello 5. {
strcat(str1,str2) : Hello World 6. char str1[20] = "Hello ";
Hello Hello World 7. char str2[20] = "World";
8. char str3[20];
b) Suppose you want to measure and 9.  
display the length of str1 and str3 10. strcpy(str3, str1);
BEFORE and AFTER the string 11. printf("strcpy(str3, str1) : %s\n", str3 );
manipulation at line 13 and line 16. 12.  
Write C statements to execute the task 13. strcat(str1, str2);
and state which line those C statements 14. printf("strcat(str1, str2) : %s\n", str1 );
should be placed 15.  
16. strcat( str3, str1);
printf("Length str1 : %d\n", strlen(str1)); 17. puts(str3);
printf("Length str3 : %d\n", strlen(str3)); 18.  
Both must be written at line 12 or above to 19. return 0;
display length before concatenation. 20. }
Both must be written at line 18 or below to
display length after concatenation.
Past Year Questions ( Final 2016/2017)
• The C program in Figure 6 performs string manipulation against 2 character array,
string1 and string2. The following questions are based on C program in Figure 6.
#include<stdio.h> for(i=len1;i<len1+len2;i++)
#include<string.h> string1[i]=string2[i-len1];
int main()
{ printf("String1 is changed to %s\n",string1);
int len1=0,len2=0,i,j;
char string1[50]={"Final"}; print("String2 is %s\n",string2);
char string2[50]={"Examination"};
char string3[50]={0}; for(i=0;i<len2;i++)
string3[i]=string2[i];
for(i=0;string1[i]!='\0';i++)
len1++; printf("String3 is %s\n",string3);

for(i=0;string2[i]!='\0';i++) return 0;
len2++; }

a) Predict the output of the program described in Figure 6.


Past Year Questions ( Final 2016/2017)
• The C program in Figure 6 performs string manipulation against 2 character array,
string1 and string2. The following questions are based on C program in Figure 6.
#include<stdio.h> for(i=len1;i<len1+len2;i++)
#include<string.h> string1[i]=string2[i-len1];
int main()
{ printf("String1 is changed to %s\n",string1);
int len1=0,len2=0,i,j;
char string1[50]={"Final"}; print("String2 is %s\n",string2);
char string2[50]={"Examination"};
char string3[50]={0}; for(i=0;i<len2;i++)
string3[i]=string2[i];
for(i=0;string1[i]!='\0';i++)
len1++; printf("String3 is %s\n",string3);

for(i=0;string2[i]!='\0';i++) return 0;
len2++; }

a) Predict the output of the program described in Figure 6.


String1 is changed to FinalExamination
String2 is Examination
String3 is Examination
 
Past Year Questions ( Final 2016/2017)
• The C program in Figure 6 performs string manipulation against 2 character array,
string1 and string2. The following questions are based on C program in Figure 6.
1 #include<stdio.h> 15 for(i=len1;i<len1+len2;i++)
2 #include<string.h> 16 string1[i]=string2[i-len1];
3 int main() 17
4 { 18 printf("String1 is changed to %s\n",string1);
5 int len1=0,len2=0,i,j; 19
6 char string1[50]={"Final"}; 20 print("String2 is %s\n",string2);
7 char string2[50]={"Examination"}; 21
8 char string3[50]={0}; 22 for(i=0;i<len2;i++)
9 23 string3[i]=string2[i];
10 for(i=0;string1[i]!='\0';i++) 24
11 len1++; 25 printf("String3 is %s\n",string3);
12 26
13 for(i=0;string2[i]!='\0';i++) 27 return 0;
14 len2++; }
b) C statements in the following lines can be written in one single line C statement using
string handling function. Write those C statements.
(i) Line 10 and line 11 , (ii) Line 15 and line 16 and (iii) Line 22 and line 23
Past Year Questions ( Final 2016/2017)
• The C program in Figure 6 performs string manipulation against 2 character array,
string1 and string2. The following questions are based on C program in Figure 6.
1 #include<stdio.h> 15
2 #include<string.h> 16 strcat(string1,string2); // Answer
3 int main() 17
4 { 18 printf("String1 is changed to %s\n",string1);
5 int len1=0,len2=0,i,j; 19
6 char string1[50]={"Final"}; 20 print("String2 is %s\n",string2);
7 char string2[50]={"Examination"}; 21
8 char string3[50]={0}; 22
9 23 strcpy(string3, string2); //Answer
10 len1=strlen(string1);//Answer 24
11 25 printf("String3 is %s\n",string3);
12 26
13 for(i=0;string2[i]!='\0';i++) 27 return 0;
14 len2++; }
b) C statements in the following lines can be written in one single line C statement using
string handling function. Write those C statements.
(i) Line 10 and line 11 , (ii) Line 15 and line 16 and (iii) Line 22 and line 23
Past Year Questions ( Final 2017/2018)
#include<stdio.h>
C program in the Figure read input of 5 student
int main()
names and their examination marks and store the {
information into parallel array student_name[] float mark[3]={0},sum=0,average=0;
and mark[]. The following questions are based on char first_name[3][50]={0},second_name[3][50]={0};
C program in the Figure. int i,max_index;
for(i=0;i<3;i++)
{
a) Process 1 in the figure is a programming task printf("Please enter student’s first name: ");
to compute average mark after all test marks gets(first_name[i]);
are added. Write C statements that should be printf("Please enter student’s second name: ");
included in line 18 to implement Process 1. gets(second_name[i]);
  printf("Please enter student marks: ");
  scanf("%f",&mark[i]);
  }
 
\\Process 1
 
max_index=0;
\\Process 2
 
for(i=0;i<3;i++)
printf("%s \t %.2f\n”,first_name[i],mark[i]);
 
printf("Highest Score Student: %s \t %.2f marks\
n" ,full_name[max_index],mark[max_index]);
printf("Average score is %.2f\n",average);
return 0;
}
Past Year Questions ( Final 2017/2018)
#include<stdio.h>
C program in the Figure read input of 5 student
int main()
names and their examination marks and store the {
information into parallel array student_name[] float mark[3]={0},sum=0,average=0;
and mark[]. The following questions are based on char first_name[3][50]={0},second_name[3][50]={0};
C program in the Figure. int i,max_index;
for(i=0;i<3;i++)
{
a) Process 1 in the figure is a programming task printf("Please enter student’s first name: ");
to compute average mark after all test marks gets(first_name[i]);
are added. Write C statements that should be printf("Please enter student’s second name: ");
included in line 18 to implement Process 1. gets(second_name[i]);
  printf("Please enter student marks: ");
  scanf("%f",&mark[i]);
Answer: }
 
 
\\Process 1
for(i=0;i<3;i++)  
sum=sum+mark[i]; max_index=0;
  \\Process 2
average=sum/5.0;  
  for(i=0;i<3;i++)
printf("%s \t %.2f\n”,first_name[i],mark[i]);
 
printf("Highest Score Student: %s \t %.2f marks\
n" ,full_name[max_index],mark[max_index]);
printf("Average score is %.2f\n",average);
return 0;
}
Past Year Questions ( Final 2017/2018)
#include<stdio.h>
C program in the Figure read input of 5 student
int main()
names and their examination marks and store the {
information into parallel array student_name[] float mark[3]={0},sum=0,average=0;
and mark[]. The following questions are based on char first_name[3][50]={0},second_name[3][50]={0};
C program in the Figure. int i,max_index;
  for(i=0;i<3;i++)
{
b) Process 2 in the Figure is a programming task printf("Please enter student’s first name: ");
to find index value of the array test[] which gets(first_name[i]);
contains the maximum value of test marks printf("Please enter student’s second name: ");
from array are retrieved. Write C statements gets(second_name[i]);
that should be included in line 24 to printf("Please enter student marks: ");
scanf("%f",&mark[i]);
implement Process 2.
}
 
 
\\Process 1
 
max_index=0;
\\Process 2
 
for(i=0;i<3;i++)
printf("%s \t %.2f\n”,first_name[i],mark[i]);
 
printf("Highest Score Student: %s \t %.2f marks\
n" ,full_name[max_index],mark[max_index]);
printf("Average score is %.2f\n",average);
return 0;
}
Past Year Questions ( Final 2017/2018)
#include<stdio.h>
C program in the Figure read input of 5 student
int main()
names and their examination marks and store the {
information into parallel array student_name[] float mark[3]={0},sum=0,average=0;
and mark[]. The following questions are based on char first_name[3][50]={0},second_name[3][50]={0};
C program in the Figure. int i,max_index;
  for(i=0;i<3;i++)
{
b) Process 2 in the Figure is a programming task printf("Please enter student’s first name: ");
to find index value of the array test[] which gets(first_name[i]);
contains the maximum value of test marks printf("Please enter student’s second name: ");
from array are retrieved. Write C statements gets(second_name[i]);
that should be included in line 24 to printf("Please enter student marks: ");
scanf("%f",&mark[i]);
implement Process 2.
}
Answer:  
  \\Process 1
 
for(i=0;i<3;i++)
max_index=0;
{ \\Process 2
if(mark[i]>mark[max_index])  
for(i=0;i<3;i++)
max_index=i;
printf("%s \t %.2f\n”,first_name[i],mark[i]);
   
} printf("Highest Score Student: %s \t %.2f marks\
  n" ,full_name[max_index],mark[max_index]);
printf("Average score is %.2f\n",average);
return 0;
}
Past Year Questions ( Final 2017/2018)
#include<stdio.h>
C program in the Figure read input of 5 student
int main()
names and their examination marks and store the {
information into parallel array student_name[] float mark[3]={0},sum=0,average=0;
and mark[]. The following questions are based on char first_name[3][50]={0},second_name[3][50]={0};
C program in the Figure. int i,max_index;
for(i=0;i<3;i++)
{
c) Using a built-in string handling function, write printf("Please enter student’s first name: ");
a C statements to append names from array gets(first_name[i]);
second_name[] to array first_name[]. The printf("Please enter student’s second name: ");
statements should contain loop in order to gets(second_name[i]);
append all elements from the array. printf("Please enter student marks: ");
scanf("%f",&mark[i]);
  }
 
  \\Process 1
 
max_index=0;
\\Process 2
 
for(i=0;i<3;i++)
printf("%s \t %.2f\n”,first_name[i],mark[i]);
 
printf("Highest Score Student: %s \t %.2f marks\
n" ,full_name[max_index],mark[max_index]);
printf("Average score is %.2f\n",average);
return 0;
}
Past Year Questions ( Final 2017/2018)
#include<stdio.h>
C program in the Figure read input of 5 student
int main()
names and their examination marks and store the {
information into parallel array student_name[] float mark[3]={0},sum=0,average=0;
and mark[]. The following questions are based on char first_name[3][50]={0},second_name[3][50]={0};
C program in the Figure. int i,max_index;
for(i=0;i<3;i++)
{
c) Using a built-in string handling function, write printf("Please enter student’s first name: ");
a C statements to append names from array gets(first_name[i]);
second_name[] to array first_name[]. The printf("Please enter student’s second name: ");
statements should contain loop in order to gets(second_name[i]);
append all elements from the array. printf("Please enter student marks: ");
scanf("%f",&mark[i]);
  }
for(i=0;i<3;i++)  
\\Process 1
strcat(first_name[i],second_name[i]);  
max_index=0;
  \\Process 2
 
for(i=0;i<3;i++)
printf("%s \t %.2f\n”,first_name[i],mark[i]);
 
printf("Highest Score Student: %s \t %.2f marks\
n" ,full_name[max_index],mark[max_index]);
printf("Average score is %.2f\n",average);
return 0;
}
Past Year Questions ( Final 2017/2018)
#include<stdio.h>
d) Suppose that tasks in (a), (b) and (c) are
int main()
correctly completed. Based on Table 1, the {
user inputs the information into the program float mark[3]={0},sum=0,average=0;
in Figure 5. Trace the final output of the char first_name[3][50]={0},second_name[3][50]={0};
program. int i,max_index;
  for(i=0;i<3;i++)
First name Second Test marks {
name printf("Please enter student’s first name: ");
Siti Saleha 85 gets(first_name[i]);
Jason Lee 94 printf("Please enter student’s second name: ");
Priya Morgan 71 gets(second_name[i]);
printf("Please enter student marks: ");
scanf("%f",&mark[i]);
}
    
\\Process 1
 
max_index=0;
\\Process 2
 
for(i=0;i<3;i++)
printf("%s \t %.2f\n”,first_name[i],mark[i]);
 
printf("Highest Score Student: %s \t %.2f marks\
n" ,full_name[max_index],mark[max_index]);
printf("Average score is %.2f\n",average);
return 0;
}
Past Year Questions ( Final 2017/2018)
#include<stdio.h>
d) Suppose that tasks in (a), (b) and (c) are
int main()
correctly completed. Based on Table 1, the {
user inputs the information into the program float mark[3]={0},sum=0,average=0;
in Figure 5. Trace the final output of the char first_name[3][50]={0},second_name[3][50]={0};
program. int i,max_index;
  for(i=0;i<3;i++)
First name Second Test marks {
name printf("Please enter student’s first name: ");
Siti Saleha 85 gets(first_name[i]);
Jason Lee 94 printf("Please enter student’s second name: ");
Priya Morgan 71 gets(second_name[i]);
printf("Please enter student marks: ");
scanf("%f",&mark[i]);
}
Answer:  
  \\Process 1
SitiSaleha 85.00  
max_index=0;
JasonLee 94.00 \\Process 2
PriyaMorgan 71.00  
Highest score student : JasonLee 94 marks for(i=0;i<3;i++)
printf("%s \t %.2f\n”,first_name[i],mark[i]);
Average score : 83.33 marks  
printf("Highest Score Student: %s \t %.2f marks\
n" ,full_name[max_index],mark[max_index]);
  
printf("Average score is %.2f\n",average);
return 0;
}
End
Arrays & Strings

62

You might also like