Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

Writing C Programs

• A programmer uses a text editor to create or


modify files containing C code.
• Code is also known as source code.
• A file containing source code is called a source
file.
• After a C source file has been created, the
programmer must invoke the C compiler before
the program can be executed (run).

L08IntroToC.ppt 1

3 Stages of Compilation

Stage 1: Preprocessing
• Performed by a program called the preprocessor
• Modifies the source code (in RAM) according to
preprocessor directives (preprocessor
commands) embedded in the source code
• Strips comments and white space from the code
• The source code as stored on disk is not modified.

L08IntroToC.ppt 2
3 Stages of Compilation (con’t)
Stage 2: Compilation
• Performed by a program called the compiler
• Translates the preprocessor-modified source code
into object code (machine code)
• Checks for syntax errors and warnings
• Saves the object code to a disk file, if instructed to
do so (we will not do this).
o If any compiler errors are received, no object code file
will be generated.
o An object code file will be generated if only warnings,
not errors, are received.

L08IntroToC.ppt 3

3 Stages of Compilation (con’t)


Stage 3: Linking
• Combines the program object code with other
object code to produce the executable file.
• The other object code can come from the Run-
Time Library, other libraries, or object files that
you have created.
• Saves the executable code to a disk file. On the
Linux system, that file is called a.out.
o If any linker errors are received, no executable file will
be generated.

L08IntroToC.ppt 4
Program Development Using gcc

Editor
Source File pgm.c

Preprocessor
Modified Source Code in RAM

Compiler
Program Object Code File pgm.o
Other Object Code Files (if any)

Linker

Executable File a.out


L08IntroToC.ppt 5

A Simple C Program

• #include <stdio.h>
• int main ( void )
• {
• printf ( “Hello, World!\n” ) ;
• return 0 ;
• }

L08IntroToC.ppt 6
Anatomy of a C Program
• program header comment

• preprocessor directives (if any)

• int main ( void )


• {
• statement(s)
• return 0 ;
• }

L08IntroToC.ppt 7

What Is a Comment? #1

A comment is a piece of text in a source file that:


• tells human beings (for example, programmers)
something useful about the program, but
• is ignored by the compiler, so it has absolutely
no affect on how the program runs.
In C, the start of a comment is indicated by
/*
and the end of a comment is indicated by
*/
All text appearing between these comment
delimiters are part of the comment, and therefore
are ignored by the compiler.

L08IntroToC.ppt 8
Program Header Comment
• A comment is descriptive text used to help a
reader of the program understand its content.
• All comments must begin with the characters /* and
end with the characters */
• These are called comment delimiters
• The program header comment always comes first.
• Look at the class web page for the required
contents of our header comment.

L08IntroToC.ppt 9

Preprocessor Directives
• Lines that begin with a # in column 1 are
called preprocessor directives
(commands).
• Example: the #include <stdio.h> directive
causes the preprocessor to include a copy of
the standard input/output header file stdio.h
at this point in the code.
• This header file was included because it
contains information about the printf ( )
function that is used in this program.
L08IntroToC.ppt 10
stdio.h

• When we write our programs, there are


libraries of functions to help us so that we
do not have to write the same code over
and over.
• Some of the functions are very complex
and long. Not having to write them
ourselves make it easier and faster to write
programs.
• Using the functions will also make it easier
to learn to program!
L08IntroToC.ppt 11

int main ( void )


• Every program must have a function called main.
This is where program execution begins.
• main() is placed in the source code file as the first
function for readability. There must be a function
with this name or gcc can not successful compile
and link your program.
• The reserved word “int” indicates that main()
returns an integer value.
• The parentheses following the reserved word
“main” indicate that it is a function.
• The reserved word “void” means nothing is there.

L08IntroToC.ppt 12
The Function Body

• A left brace (curly bracket) -- { -- begins the


body of every function. A corresponding
right brace -- } -- ends the function body.
• The style is to place these braces on
separate lines in column 1 and to indent the
entire function body 3 to 5 spaces.

L08IntroToC.ppt 13

printf (“Hello, World!\n”) ;

• This line is a C statement.


• It is a call to the function printf ( ) with a
single argument (parameter), namely the
string “Hello, World!\n”.
• Even though a string may contain many
characters, the string itself should be
thought of as a single quantity.
• Notice that this line ends with a semicolon.
All statements in C end with a semicolon.

L08IntroToC.ppt 14
return 0 ;
• Because function main() returns an integer value, there
must be a statement that indicates what this value is.
• The statement
return 0 ;

indicates that main() returns a value of zero to


the operating system.
• A value of 0 indicates that the program successfully
terminated execution.
• Do not worry about this concept now. Just remember to
use the statement.

L08IntroToC.ppt 15

Another C Program (con’t)


#include <stdio.h>
int main( void )
{
int value1, value2, product ;
printf(“Enter two integer values: “) ;
scanf(“%d%d”, &value1, &value2) ;
product = value1 * value2 ;
printf(“Product = %d\n”, product) ;
return 0 ;
}

L08IntroToC.ppt 16
Keywords
• Sometimes called reserved words.
• Are defined as a part of the C language.
• Can not be used for anything else!
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

L08IntroToC.ppt 17

What is a data type


For each variable you have to attach some data type.
The data type defines:
1. the amount of storage allocated to variables.
2. the values that they can accept.
3. the operations that can be performed on variables.

. Data type determines how much storage space is allocated to


variables.
. Data type determines the permissible operations on variables.
. The variables should be declared by specifying the data type.

L08IntroToC.ppt 18
Data types in C

• Primitive data types


o int, float, double, char
• Aggregate data types
o Arrays come under this category
o Arrays can contain collection of int or float or
char or double data
• User defined data types
o Structures and enum fall under this category.

L08IntroToC.ppt 19

Data types in C
Keyword Variable Type Range
char Character -128 to 127
int Integer -32,768 to 32,767
short Short integer -32,768 to 32,767
short int Short integer -32,768 to 32,767
long Long integer -2,147,483,648 to
2,147,483,647
unsigned char Unsigned character 0 to 255
unsigned int Unsigned integer 0 to 65,535
unsigned short Unsigned short integer 0 to 65,535
unsigned long Unsigned long integer 0 to 4,294,967,295
float Single-precision +/-3.4E10^38 to +/-
3.4E10^38
double Double-precision +/-1.7E10^308 to +/-
L08IntroToC.ppt
1.7E10^308
20
Variables

• Variables are data that will keep on changing


• Declaration
<<Data type>> <<variable name>>;
int a;
• Definition
<<varname>>=<<value>>;
a=10;
• Usage
<<varname>>
a=a+1; //increments the value of a by 1

L08IntroToC.ppt 21

Variable names- Rules

• Should not be a reserved word like int


etc..
• Should start with a letter or an
underscore(_)
• Can contain letters, numbers or
underscore.
• No other special characters are allowed
including space
• Variable names are case sensitive
o A and a are different.
L08IntroToC.ppt 22
Input and Output

• Input
o scanf(“%d”,&a);
o Gets an integer value from the user and stores
it under the name “a”
• Output
o printf(“%d”,a)
o Prints the value present in variable a on the
screen

L08IntroToC.ppt 23

Input and Output


Conversion specifiers are made up of two characters: % and a
special character.

The special character tells the program how to convert the data.
Conversion Specifier Description
%d Displays integer value
%f Displays floating-point numbers
%c Displays character

L08IntroToC.ppt 24
Type Conversion
1. Type conversion occurs when the expression has
data of mixed data types.
2. In type conversion, the data type is promoted from
lower to higher.
3. The hierarchy of data types: double, float, long, int,
short, char.

• Forced conversion occurs when you are


converting the value of the larger data type to the
value of the smaller data type
• When floating points are converted to integers,
truncation occurs

L08IntroToC.ppt 25

Tokens

• The smallest element in the C language is


the token.
• It may be a single character or a sequence
of characters to form a single item.

L08IntroToC.ppt 26
Newline
In C, you can place a newline, also known
as a carriage return, inside a string literal
using:
\n
If a newline appears inside a string literal in
the source code, then when the string
literal is output, the newline causes the
output to move to a new line.

L08IntroToC.ppt 27

Newline Example
#include <stdio.h>

int main ()
{ /* main */
printf("Howdy do!\n");
printf("This string literal contains a newline in the\nmiddle ");
printf("but this string literal contains a newline at the end.\n");
printf("So there!\n");
} /* main */

Note: In general, it’s better programming


practice to put newlines only at the end
of your string literals, not in the middle,
because in the middle they can be difficult
for programmers (e.g., graders) to see.

L08IntroToC.ppt 28
Punctuation

• Semicolons, colons, commas, apostrophes,


quotation marks, braces, brackets, and
parentheses.
• ;:,‘“[]{}()

L08IntroToC.ppt 29

Operators

• There are operators for:


o assignments
o mathematical operations
o relational operations
o Boolean operations
o bitwise operations
o shifting values
o calling functions
o subscripting
o obtaining the size of an object
o obtaining the address of an object
o referencing an object through its address
o choosing between alternate subexpressions

L08IntroToC.ppt 30
Assignment operator
Assigning the value of an expression to a variable.
var = expression.
You can use other formats such as var += expression,
which means var = var + expression.

1. The assignment operators have the lowest


priority.
2. The assignment operators are evaluated from
right to left.
3. The assignment operators include: =, +=, -=, *=, /=,
%=.

L08IntroToC.ppt 31

Arithmetic Operators
Operator Description Example
* Multiplication Result = Operand1 * Operand2;
/ Division Result = Operand1 / Operand2;
% Modulus (remainder) Remainder = Operand1 % Operand2;
+ Addition Result = Operand1 + Operand2;
- Subtraction Result = Operand1 -Operand2;

L08IntroToC.ppt 32
Increment/Decremental operator ++ --
Prefix: the value is incremented/decremented first and then applied.
Postfix: the value is applied and the value is
incremented/decremented.
#include<stdio.h>
main( )
{
int i = 3,j = 4,k;
k = i++ + --j;
printf("i = %d, j = %d, k = %d",i,j,k);
}

L08IntroToC.ppt 33

Relational operators
1. Relational operators are used in Boolean conditions or
expressions.
2. Boolean conditions or expressions return either true or false.
3. The relational operator returns zero values or nonzero values.
4. The zero value is taken as false while the nonzero value is taken
as true.

1. The relational operators are as follows: <, <=, >, >=, ==, !=.
2. The priority of the first four operators is higher than that of the later
two operators.

L08IntroToC.ppt 34
Boolean Operator in C
Character Set Boolean Operator
&& and
|| or

• && Operator
1. && operator: evaluate a Boolean expression from left to right.
2. Both sides of the operator must evaluate to true before the entire
expression becomes true.
• || Operator
1. || operator: evaluate from left to right.
2. If either side of the condition is true, the whole expression results
in true.

L08IntroToC.ppt 35

Conditional Statements
IF STATEMENT: To conditionally execute statements, you can use
the if or the if...else statement.
The general form of the if statement is
if(expr) {
....
}else{
...
}
• expr is a Boolean expression that returns true (nonzero) or false
(zero).

L08IntroToC.ppt 36
Conditional Statements
SWITCH STATEMENT: To take one of a number of possible
actions.
switch is preferred over multiple if...else statements.
• The general form of a switch statement is
• switch(switch_expr)
{
case constant expr1 : S1; break;
case constant expr1 : S2; break;
.....
default : S5; break;
}
The clause 'default' is optional.

L08IntroToC.ppt 37

Loop Statement in C
Loops are basically means to do a task multiple
times, without actually coding all
statements over and over again. For example, loops
can be used for displaying a string
many times, for counting numbers and of course for
displaying menus. Loops in C are three types:
• 'for' loop
• 'while' loop
• 'do while' loop

L08IntroToC.ppt 38
For Loop
The for statement is typically used to count a number of items. At its regular structure,
it is divided in three parts. The first section specifies the starting point for the count.
The second section sets the counting limit. The last section determines the counting
frequency. The syntax of the for statement is:
for( Start; End; Frequency) {
Statement;
}
The Start expression is a variable assigned the starting value. This could be Count =
0; The End expression sets the criteria for ending the counting. An example would be
Count < 24; this means the counting would continue as long as the Count variable is
less than 24.
For example:
int count, num, total = 0;
for (count = 1; count <= 10; count++) {
cout << "Enter integer #" << count << ": ";
cin >> num;
total = total + num;
} //end for
Note: The "++" operator adds one to a number, so count++; is equivalent to count =
count + 1
L08IntroToC.ppt 39

While Loop
while (<stopping condition>) {
<one or more statements>
} end while
The while loop checks to see if the <stopping condition> is true (or not -). If so, the
statements inside the while loop are executed, then the <stopping condition> is checked
again, and so on. When the <stopping condition> is found to be false (or -), execution
continues with whatever statements follow at the end of the while loop.
For example:
#include<iostream>
void main(){
int i=0;
while(i<3){
i++;
cout<<”ABC”<<endl;
}}

L08IntroToC.ppt 40
Do-While
It is very similar to the 'while' loop shown above. The only difference
being, in a 'while',loop, the condition is checked beforehand, but in a
'do while' loop, the condition is checked after one execution of the
loop.Example code for the same problem using a 'do while' loop
would be :
void main(){
int i=0;
do{
i++; cout <<”ABC”<< endl;
}while(i<3)
}

L08IntroToC.ppt 41

What is a C Function?
A function receives zero or more parameters, performs
a specific task, and returns zero or one value.
1. A function is invoked by its name and parameters.
2. No two functions have the same name in your C program.
3. No two functions have the same name AND parameter types in
your C++ program.
4. The communication between the function and invoker is through
the parameters and the return value.
5. A function is independent:
6. It is “completely” self-contained.
7. It can be called at any places of your code and can be ported to
another program.
8. Functions make programs reusable and readable.
42
Standard function libraries
<stdio.h> printf(), scanf(),
printf(), scanf(), etc.
<string.h> strcmp(), etc.
strcmp(),
<ctype.c> isspace(), etc.
isspace(),
<math.h> sqrt(), etc.
sqrt(),

09/10/10 Stroustrup/Programming
43 43

Example
int max(int a, int b); int max(int a, int b){
return a>b?a:b;
int main(){ }
int x;
x = max(5,8);
x = max(x,7);
}

44
Syntax
Function Prototype:
return_type function_name (type1 name1, type2 name2,
..., typen namen);

Function Definition:
return_type function_name (type1 name1, type2 name2,
...,typen namen)
{
....statements...
}

The parameters
Function header
45

Some Examples
Function Prototype Examples
double squared (double number);
void print_report (int);
int get _menu_choice (void);
Function Definition Examples
void parameter list means
double squared (double number)
it takes no parameters
{
return (number * number);
}

void print_report (int report_number)


{
if (report_nmber == 1)
return type void means
printf(“Printer Report 1”);
else it returns nothing
printf(“Not printing Report 1”);
}
46
Passing Arguments

Function call:
func1 (a, b, c);
Function header
int func1 (int x, int y, int z)
Each argument can be any valid C expression that has a value:
For example:
x = func1(x+1,func1(2,3,4),5);
Parameters x y z are initialized by the value of a b c
Type conversions may occur if types do not match.

47

Parameters are Passed by Value


All parameters are #include<stdio.h>
passed by value!! int twice(int x)
This means they are basically {
local variables initialized to x=x+x;
the values that the function is return x;
called with. }
They can be modified as you int main()
wish but these modifications
{
will not be seen in the calling
routine! int x=10,y;
y=twice(x);
printf("%d,%d\n",x,y);
}
48
Returning a Value
To return a value from a C function you must explicitly
return it with a return statement.
Syntax:

return <expression>;

The expression can be any valid C expression that resolves


to the type defined in the function header.
Type conversion may occur if type does not match.
Multiple return statements can be used within a single
function (eg: inside an “if-then-else” statement…)

49

Local Variables / Global Variables


Local variables : are declared within the body of a function, and can only be
used within that function. This is usually no problem, since when another
function is called, all required data is passed to it as arguments. Alternatively, a
variable can be declared globally so it is available to all functions.
A global variable : declaration looks normal, but is located outside any of the
program's functions. This is usually done at the beginning of the program file, but
after preprocessor directives. The variable is not declared again in the body of the
functions which access it.
Local Variables
int func1 (int y)
{
int a, b = 10;
float rate;
double cost = 12.55;
.......
}

50
A Simple Example
#include <stdio.h>
int x=1; /* global variable - bad! */
void demo(void);
int main() {
int y=2; /* local variable to main */
printf ("\nBefore calling demo(), x = %d and y = %d.",x,y);
demo();
printf ("\nAfter calling demo(), x = %d and y = %d.\n",x,y);
return 0;
}
void demo () {
int x = 88, y =99; /* local variables to demo */
printf ("\nWithin demo(), x = %d and y = %d.",x,y);
}
51

Placement of Functions
For large programs mymath.h
int min(int x,int y);
#include the header file in the files int max(int x,int y);
that uses the functions.
mymath.c
For small programs, use the int min(int x,int y)
following order in the only
{
one file:
All prototypes return x>y?y:x;
main() function }
Other functions int max(int x,int y)
{
return x>y?x:y;
}

52
Recursion Functions
1. A recursive function is a function that calls itself.
2. The speed of a recursive program is slower because of
stack overheads.
3. In recursive function we need to specify recursive
conditions, terminating conditions, and recursive
expressions.

53

Recursion - An Example
unsigned int factorial(unsigned int a); unsigned int factorial (unsigned int a) {
if (a==1)
int main () {
unsigned int f,x; return 1;
printf("Enter value between 1 & 8: "); else {
scanf("%d", &x); a *= factorial(a-1);
if (x > 8 || x < 1)
return a;
printf (”Illegal input!\n");
else { }
f = factorial(x); }
printf ("%u factorial equals %u\n",
x,f);
}
}

54
Arrays in C

55

Single-Dimensional Arrays
Generic declaration:
typename variablename[size]
– typename is any type
– variablename is any legal variable name
– size is a number the compiler can figure out
For example
int a[10];
Defines an array of ints with subscripts ranging from 0 to 9
There are 10*sizeof(int) bytes of memory reserved for this array.
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

You can use a[0]=10; x=a[2]; a[3]=a[2]; etc.


You can use scanf("%d",&a[3]); 56
Array-Bounds Checking
C, unlike many languages, does NOT check array bounds subscripts
during:
Compilation (some C compilers will check literals)
Runtime (bounds are never checked)
If you access off the ends of any array, it will calculate the address it
expects the data to be at, and then attempts to use it anyways
may get “something…”
may get a memory exception (segmentation fault, bus error, core dump error)
It is the programmer’s responsibility to ensure that their programs are
correctly written and debugged!
This does have some advantages but it does give you all the rope you need to
hang yourself!

57

Initializing Arrays
Initialization of arrays can be done by a comma separated
list following its definition.
For example:
int array [4] = { 100, 200, 300, 400 };
This is equivalent to:
int array [4];
array[0] = 100;
array[1] = 200;
array[2] = 300;
array[3] = 400;
You can also let the compiler figure out the array size for
you:
int array[] = { 100, 200, 300, 400};
58
A Simple Example
#include <stdio.h>
int main() {
float expenses[12]={10.3, 9, 7.5, 4.3, 10.5, 7.5, 7.5, 8, 9.9, 10.2,
11.5, 7.8};
int count,month;
float total;
for (month=0, total=0.0; month < 12; month++)
{
total+=expenses[month];
}
for (count=0; count < 12; count++)
printf ("Month %d = %.2f K$\n", count+1, expenses[count]);
printf("Total = %.2f K$, Average = %.2f K$\n", total, total/12);
return 0;
}
59

Multidimensional Arrays
Arrays in C can have virtually as many dimensions as
you want.
Definition is accomplished by adding additional
subscripts when it is defined.
For example:
int a [4] [3] ;
• defines a two dimensional array
• a is an array of int[3];
In memory:
a[0][0] a[0][1] a[0][2]

a[0] a[1] a[2] 60 a[3]


Initializing Multidimensional Arrays
The following initializes a[4][3]:
int a[4] [3] = { {1, 2, 3} , { 4, 5, 6} , {7, 8, 9} , {10, 11, 12} };
Also can be done by:
int a[4] [3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
is equivalent to
a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[1][0] = 4;
...
a[3][2] = 12;

61

An Example
#include <stdio.h>
#include <stdlib.h>
int main () {
int random1[8][8];
int a, b;
for (a = 0; a < 8; a++)
for (b = 0; b < 8; b++)
random1[a][b] = rand()%2;
for (a = 0; a < 8; a++)
{
for (b = 0; b < 8; b++)
printf ("%c " , random1[a][b] ? 'x' : 'o');
printf("\n");
}
return 0;
62
}
The value of the array name
#include <stdio.h> for (i=0; i<3; i++) {
int main(){ printf( "a[%d] <- ",i);
int i; scanf( "%d", &a[i]);
int a[3] = { 1, 2, 3 }; }
printf( "a ? %d\n", a); printf( "a ? %d\n", a);
printf( "a[0] ? %d\na[1] ? %d\na[2] ? printf( "a[0] ? %d\na[1] ? %d\na[2]
%d\n", a[0], a[1], a[2]); ? %d\n", a[0], a[1], a[2]);
printf( "&a[0] ? %d\n&a[1] ? printf( "&a[0] ? %d\n&a[1] ?
%d\n&a[2] ? %d\n", &a[0], &a[1], %d\n&a[2] ? %d\n", &a[0],
&a[2]); &a[1], &a[2]);
}
printf( "\na[0] <- 4 \n");
a[0] = 4; When the array name is used alone,
printf( "a ? %d\n", a); its value is the address of the
printf( "a[0] ? %d\na[1] ? %d\na[2] ? array (a pointer to its address).
%d\n", a[0], a[1], a[2]);
&a has no meaning if used in this
printf( "&a[0] ? %d\n&a[1] ?
%d\n&a[2] ? %d\n\n", &a[0], &a[1], program.
&a[2]);
63

Arrays as Function Parameters


In this program, the array addresses void inc_array(int a[ ],int size);
(i.e., the values of the array names), main()
are passed to the function
{
inc_array().
int test[3]={1,2,3};
This does not conflict with the rule
that “parameters are passed by int ary[4]={1,2,3,4};
values”. int i;
void inc_array(int a[ ], int size) inc_array(test,3);
{ for(i=0;i<3;i++)
int i; printf("%d\n",test[i]);
for(i=0;i<size;i++) inc_array(ary,4);
{ for(i=0;i<4;i++)
a[i]++; printf("%d\n",ary[i]);
} return 0;
} }
64
An Example -- Sorting
void mysort(int a[ ],int size) int main()
{ {
int i,j,x;
for(i=0; i<size; i++) int i;
{ int tab[10] = {3,6,3,5,9,2,4,5,6,0};
for(j=i; j>0; j--)
{ for(i=0;i<10;i++)
if(a[ j ] < a[ j-1]) printf("%d ",tab[i]);
{ /* Change the order of a[ j ] and
a[ j-1] */
x=a[ j ];a[ j ]=a[ j-1]; a[j-1]=x; printf("\n");
} mysort(tab,10);
}
}
} for(i=0;i<10;i++)
printf("%d ",tab[i]);

printf("\n");
return 0;
} 65

Strings in C are Character Arrays


Strings in C are simply arrays of characters.
Example:char s [10];
This is a ten (10) element array that can hold a character
string consisting of £ 9 characters.
This is because C does not know where the end of an
array is at run time.
By convention, C uses a NULL character '\0' to terminate all
strings in its library functions
For example:
char str [10] = {'u', 'n', 'I', 'x', '\0'};
It’s the string terminator (not the size of the array) that
determines the length of the string.
66
Accessing Individual Characters
The first element of any array in C is at index 0. The second
is at index 1, and so on ...
char s[10];
s[0] = 'h';
s[1] = 'i’; h i ! \0 ? ? ? ? ? ?
s[2] = '!'; s [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
s[3] = '\0';
This notation can be used in all kinds of statements and
expressions in C:
For example:
c = s[1];
if (s[0] == '-') …
switch (s[1]) ...
67

String Literals
String literals are given as a string quoted by
double quotes.
printf("Long long ago.");
Initializing char array ...
char s[10]="unix"; /* s[4] is '\0'; */
char s[ ]="unix"; /* s has five elements */

68
Printing with printf ( )
Example:
char str[ ] = "A message to display";
printf ("%s\n", str);

printf expects to receive a string as an additional


parameter when it sees %s in the format string
Can be from a character array.
Can be another literal string.
Can be from a character pointer (more on this later).

printf knows how much to print out because of the NULL


character at the end of all strings.
When it finds a \0, it knows to stop.
69

Example
char str[10]="unix and c";

printf("%s", str);
printf("\n");
str[6]='\0';
printf("%s", str);
printf("\n");

printf("\n");
printf(str);
printf("\n");
str[2]='%';
printf(str);
printf("\n");
70
Printing with puts( )
The puts function is a much simpler output function than
printf for string printing.
Prototype of puts is defined in stdio.h
int puts(const char * str)
This is more efficient than printf
• Because your program doesn't need to analyze the format
string at run-time.
For example:
char sentence[] = "The quick brown fox\n";
puts(sentence);
Prints out:
The quick brown fox
71

Inputting Strings with gets( )


gets( ) gets a line from the standard input.
The prototype is defined in stdio.h
char *gets(char *str)
str is a pointer to the space where gets will store the line to, or a
character array.
Returns NULL upon failure. Otherwise, it returns str.
char your_line[100];
printf("Enter a line:\n");
gets(your_line);
puts("Your input follows:\n");
puts(your_line);
You can overflow your string buffer, so be careful!

72
Inputting Strings with scanf ( )
To read a string include:
%s scans up to but not including the “next” white space character
%ns scans the next n characters or up to the next white space
character, whichever comes first
Example:
scanf ("%s%s%s", s1, s2, s3);
scanf ("%2s%2s%2s", s1, s2, s3);
Note: No ampersand(&) when inputting strings into character arrays!
(We’ll explain why later …)
Difference between gets
gets( ) read a line
scanf("%s",…) read up to the next space
73

An Example
#include <stdio.h>
int main () {
char lname[81], fname[81];
int count, id_num;
puts ("Enter the last name, firstname, ID number
separated");
puts ("by spaces, then press Enter \n");
count = scanf ("%s%s%d", lname, fname,&id_num);
printf ("%d items entered: %s %s %d\n",
count,fname,lname,id_num);
return 0;
}
74
The C String Library
String functions are provided in an ANSI
standard string library.
Access this through the include file:
#include <string.h>
Includes functions such as:
• Computing length of string
• Copying strings
• Concatenating strings
This library is guaranteed to be there in any ANSI
standard implementation of C.
75

strlen
strlen returns the length of a NULL terminated character
string:
size_t strlen (char * str) ;
Defined in string.h
size_t
A type defined in string.h that is equivalent to an unsigned int
char *str
Points to a series of characters or is a character array ending with
'\0'
The following code has a problem!
char a[5]={‘a’, ’b’, ’c’, ’d’, ’e’};
strlen(a);
76
strcpy
Copying a string comes in the form:
char *strcpy (char * destination, char * source);
A copy of source is made at destination
source should be NULL terminated
destination should have enough room
(its length should be at least the size of source)
The return value also points at the destination.

77

strcat
Included in string.h and comes in the form:
char * strcat (char * str1, char * str2);
• Appends a copy of str2 to the end of str1
• A pointer equal to str1 is returned
Ensure that str1 has sufficient space for the
concatenated string!
Array index out of range will be the most popular bug
in your C programming career.

78
Example
#include <string.h>
#include <stdio.h>
int main() {
char str1[27] = "abc";
char str2[100];
printf("%d\n",strlen(str1));
strcpy(str2,str1);
puts(str2);
puts("\n");
strcat(str2,str1);
puts(str2);
}
79

Comparing Strings
C strings can be compared for equality or
inequality
If they are equal - they are ASCII identical
If they are unequal the comparison function will
return an int that is interpreted as:
< 0 : str1 is less than str2
0 : str1 is equal to str2
> 0 : str1 is greater than str2

80
strcmp
Four basic comparison functions:
int strcmp (char *str1, char *str2) ;
• Does an ASCII comparison one char at a time until a
difference is found between two chars
– Return value is as stated before
• If both strings reach a '\0' at the same time, they are
considered equal.
int strncmp (char *str1, char * str2, size_t n);
• Compares n chars of str1 and str2
– Continues until n chars are compared or
– The end of str1or str2 is encountered
Also have strcasecmp() and strncasecmp() which do the same as
above, but ignore case in letters.
81

Example
An Example - strncmp

int main() {
char str1[] = "The first string.";
char str2[] = "The second string.";
size_t n, x;
printf("%d\n", strncmp(str1,str2,4) );
printf("%d\n", strncmp(str1,str2,5) );
}

82
Searching Strings (1)
There are a number of searching functions:
char * strchr (char * str, int ch) ;
• strchr search str until ch is found or NULL character
is found instead.
• If found, a (non-NULL) pointer to ch is returned.
– Otherwise, NULL is returned instead.
You can determine its location (index) in the string by:
• Subtracting the value returned from the address of the
start of the string
– More pointer arithmetic … more on this later!
83

Example
Example use of strchr:
#include<stdio.h>
#include<string.h>
int main() {
char ch='b', buf[80];
strcpy(buf, "The quick brown fox");
if (strchr(buf,ch) == NULL)
printf ("The character %c was not found.\n",ch);
else
printf ("The character %c was found at position %d\n", ch,
strchr(buf,ch)-buf+1);
}

84
Searching Strings (2)
Another string searching function:
char * strstr (char * str, char * query) ;
• strstr searches str until query is found or a NULL
character is found instead.
• If found, a (non-NULL) pointer to str is returned.
– Otherwise, NULL is returned instead.

85

sprintf
#include <stdio.h>
int sprintf( char *s, const char *format, …);
Instead of printing to the stdin with printf(…),
sprintf prints to a string.
Very useful for formatting a string, or when one
needs to convert integers or floating point
numbers to strings.
There is also a sscanf for formatted input from a
string in the same way scanf works.
86
Example:
#include <stdio.h>
#include <string.h>
int main()
{
char result[100];
sprintf(result, "%f", (float)17/37 );
if (strstr(result, "45") != NULL)
printf("The digit sequence 45 is in 17
divided by 37. \n");
return 0;
} 87

Converting Strings to Numbers (1)


Contained in <stdlib.h> and are often used
int atoi (char *ptr);
Takes a character string and converts it to an integer.
White space and + or - are OK.
Starts at beginning and continues until something non-convertible is
encountered.
Some examples:
String Value returned
"157" 157
"-1.6" -1
"+50x" 50
"twelve" 0
"x506" 0 88
Converting Strings to Numbers (2)
long atol (char *ptr) ;
Same as atoi except it returns a long.
double atof (char * str);
Handles digits 0-9.
A decimal point.
An exponent indicator (e or E).
If no characters are convertible a 0 is returned.
Examples:
String Value returned
"12" 12.000000
"-0.123" -0.123000
"123E+3" 123000.000000
"123.1e-5" 0.001231
89

You might also like