//The talkback.c Program
#include <stdio.h>
#include <cstring>
#define DENDITY 62.4
int main(void) {
float weight, volume;
int size, letters;
char name[40];
printf("Hi! What's your name?
");
scanf("%s", &name);
printf("%s", "what's your weight in pounds?
");
scanf("%f", &weight);
size = sizeof(name);
letters = strlen(name);
volume = weight / DENDITY;
printf("Well, %s, your volume is %2.2f cubic feet.
", name, volume);
printf("Also, your first name has %d letters.
", letters);
printf("and we have %d bytes to store it.
", size);
return 0;
}
Running talkback.c produces results such as the following:
Hi! What's your name?
Christine
what's your weight in pounds?
154
Well, Christine, your volume is 2.47 cubic feet.
Also, your first name has 9 letters.
and we have 40 bytes to store it.
Here are the main new features of this program:
■ It uses an array to hold a character string . Here, someone’s name is read into the array, which, in this case, is a series of 40 consecutive bytes in memory, each able to hold a single character value.
■ It uses the %s conversion specification to handle the input and output of the string. Note that name , unlike weight , does not use the & prefix when used with scanf(). (As you’ll see later, both &weight and name are addresses.)
■ It uses the C preprocessor to define the symbolic constant DENSITY to represent the value
62.4 .■ It uses the C function strlen() to find the length of a string.
Character Strings: An Introduction
A character string is a series of one or more characters. Here is an example of a string:
"Zing went the strings of my heart!"
The double quotation marks are not part of the string. They inform the compiler that they enclose a string, just as single quotation marks identify a character.
Type char Arrays and the Null Character
C has no special variable type for strings. Instead, strings are stored in an array of type char . Characters in a string are stored in adjacent memory cells, one character per cell, and an array consists of adjacent memory locations, so placing a string in an array is quite natural.
Note that the figure shows the character