Characters and Strings
Characters and Strings
AND STRINGS
OBJECTIVES:
• Learn how characters are represented in C
• Explore string handling in C
• Master the input and output operations for characters and
strings in C
STRINGS
• A string in C is an array of characters.
• The length of a string is determined by a terminating null character: '\0' .
• So, a string with the contents, say, “hello" has six characters:
‘h' , ‘e' , ‘l' , ‘l' , ‘o' and the terminating null ( '\0‘ ) character.
• The terminating null character has the value zero.
• Series of characters treated as a single unit
- Can include letters, digits and special characters (*, /, $)
Syntax:
char stringName [numOfCharacters];
Example:
char s1[10]; char lname[15],fname[15],mi[2];
String Initialization:
Syntax:
char stringName[ ]=“stringValue”;
Example:
char name[]={‘L’, ‘a’, ‘d’, ‘\0’};
is the same as
char name[]=“Lad”;
char name[]=“Lad”;
Or alternatively, we can write
char name[]={‘L’, ‘a’, ‘d’, ‘\0’};
String Input/Output:
• Input Function:
-We use the scanf() or the gets() functions. Example: scanf(“%s”,&s1); or gets(s1);
• Output Function:
-We use the printf() or the puts() functions. Example: printf(“\n s1=%s”,s1); or
puts(s1);
• Format Specifier:
%s
Fundamentals of Strings:
• String definitions
-Define as a character array or a variable of type char *
char color[] = "blue";
char *colorPtr = "blue";
-Remember that strings represented as character arrays end with '\0’
color has 5 elements
• Inputting strings
-Use scanf
scanf("%s", word);
• Copies input into word[]
• Do not need & (because a string is a pointer)
-Remember to leave room in the array for '\0'
Character Handling Library:
• Character handling library
-Includes functions to perform useful tests and manipulations
of character data
Instructions:
1. Open a Python development environment and write the following code:
# Simple Calculator
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("Sum:", num1 + num2)
print("Difference:", num1 - num2)
print("Product:", num1 * num2)
print("Quotient:", num1 / num2)
2. Run the program and experiment with different numbers
3. Observe the output