Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: c language for learners
Description: it is very easy to learn c program for beginners.

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


Introduction to the C Programming Language
Science & Technology Support
High Performance Computing
Ohio Supercomputer Center
1224 Kinnear Road
Columbus, OH 43212-1163

Table of Contents










Introduction
C Program Structure
Variables, Expressions, &
Operators
Input and Output
Program Looping
Decision Making Statements
Array Variables
Strings
Math Library Functions











User-defined Functions
Formatted Input and Output
Pointers
Structures
Unions
File Input and Output
Dynamic Memory Allocation
Command Line Arguments
Operator Precedence Table

2
C Programming

Introduction


Why Learn C?

3
C Programming

Why Learn C?










Compact, fast, and powerful
“Mid-level” Language
Standard for program development (wide acceptance)
It is everywhere! (portable)
Supports modular programming style
Useful for all applications
C is the native language of UNIX
Easy to interface with system devices/assembly routines
C is terse

4
C Programming

C Program Structure






Canonical First Program
Header Files
Names in C
Comments
Symbolic Constants

5
C Programming

Canonical First Program


The following program is written in the C programming language:

#include ...
All commands in C must be lowercase
...
End of each statement must be marked
with a semicolon
...
White space is
ignored
...


6
C Programming

Canonical First Program Continued
#include ...




This informs the computer as to where the program actually starts
...

The two braces, { and }, signify the begin and end segments of the
program
...
COMMON ERROR: unbalanced number
of open and close curly brackets!



7
C Programming

More on the Canonical First Program

#include ...
h> is to allow the use of
the printf statement to provide program output
...
Text to be
displayed by printf() must be enclosed in double quotes
...

• printf() is actually a function (procedure) in C that is used for printing
variables and text
...
There are some exceptions however
...
These characters are modifiers, and for the present the
\ followed by the n character represents a newline character
...
As we shall see later on,
what follows the \ character will determine what is printed (i
...
, a tab, clear
screen, clear line, etc
...
As will be discussed later, comments are useful for a variety of
reasons
...


9
C Programming

Header Files








Header files contain definitions of functions and variables which can be
incorporated into any C program by using the pre-processor #include statement
...

To use any of the standard functions, the appropriate header file should be included
...
For example, to use the function
printf() in a program, the line
#include ...
h
...
h and generally reside
in the /usr/include subdirectory
...
h>
#include ...
h"
The use of angle brackets <> informs the compiler to search the compiler’s include
directories for the specified file
...

10
C Programming

Names in C


Identifiers in C must begin with a character or underscore, and may be
followed by any combination of characters, underscores, or the digits 0-9
...
The reasons for this are to make the program easier to read and
self-documenting
...

Keywords are reserved identifiers that have strict meaning to the C compiler
...
Example keywords are:
if, else, char, int, while



11
C Programming

Comments


The addition of comments inside programs is desirable
...

*/



Note that the /* opens the comment field and the */ closes the comment
field
...
Comments may not be nested one
inside the another
...
/* this comment is inside */ wrong */



In the above example, the first occurrence of */ closes the comment
statement for the entire line, meaning that the text wrong is interpreted as a C
statement or variable, and in this example, generates an error
...


13
C Programming

Symbolic Constants









Names given to values that cannot be changed
...

#define N 3000
#define FALSE 0
#define PI 3
...
Traditionally, preprocessor statements are listed at
the beginning of the source file
...
All # statements are processed first, and the
symbols (like N) which occur in the C program are replaced by their value
(like 3000)
...

In general, preprocessor constants are written in UPPERCASE
...

In the program itself, values cannot be assigned to symbolic constants
...

#include ...
10
main ()
{
float balance;
float tax;
balance = 72
...
2f is %
...
10 is 7
...
Considering the above program as an example, what
changes would you need to make if the TAXRATE was changed to 20%?

15
C Programming

Use of Symbolic Constants




Obviously, the answer is one, where the #define statement which declares
the symbolic constant and its value occurs
...
20
Without the use of symbolic constants, you would hard code the value 0
...


16
C Programming

Variables, Expressions, and Operators















Declaring Variables
Basic Format
Basic Data Types: Integer
Basic Data Types: Float
Basic Data Types: Double
Basic Data Types: Character
Expressions and Statements
Assignment Operator
Assignment Operator Evaluation
Initializing Variables
Initializing Variables Example
Arithmetic Operators
Increment/Decrement Operators
Prefix versus Postfix












Advanced Assignment Operators
Precedence & Associativity of
Operators
Precedence & Associativity of
Operators Examples
The int Data Type
The float and double Data
Types
The char Data Type
ASCII Character Set
Automatic Type Conversion
Automatic Type Conversion with
Assignment Operator
Type Casting

17
C Programming

Declaring Variables




A variable is a named memory location in which data of a certain type can be
stored
...
User defined
variables must be declared before they can be used in a program
...
All
variables in C must be declared before use
...

Remember that C is case sensitive, so even though the two variables listed
below have the same name, they are considered different variables in C
...

main()
{
int sum;



It is possible to declare variables elsewhere in a program, but lets start simply
and then get into variations later on
...
Examples are
int i,j,k;
float length,height;
char midinit;

19
C Programming

Basic Data Types: INTEGER


INTEGER: These are whole numbers, both positive and negative
...
In addition, there are short
and long integers
...




The keyword used to define integers is
int



An example of an integer value is 32
...




The keyword used to define float variables is
float



Typical floating point values are 1
...
932e5 (1
...
An example
of declaring a float variable called x is
float x;

21
C Programming

Basic Data Types: DOUBLE


DOUBLE: These are floating point numbers, both positive and negative,
which have a higher precision than float variables
...




The keyword used to define character variables is
char



Typical character values might be the letter A, the character 5, the symbol “,
etc
...
Sample expressions are:
a + b
3
...
66553
tan(angle)



Most expressions have a value based on their contents
...
For
example:
sum = x + y + z;
printf("Go Buckeyes!");

24
C Programming

The Assignment Operator


In C, the assignment operator is the equal sign = and is used to give a variable
the value of an expression
...
8;
sum=a+b;
slope=tan(rise/run);
midinit='J';
j=j+3;



When used in this manner, the equal sign should be read as “gets”
...


25
C Programming

The Assignment Operator Evaluation


In the assignment statement
a=7;



two things actually occur
...
This allows a shorthand for multiple
assignments of the same value to several variables in a single statement
...
0;

26
C Programming

Initializing Variables


C Variables may be initialized with a value when they are declared
...

int count = 10;



In general, the user should not assume that variables are initialized to some
default value “automatically” by the compiler
...


27
C Programming

Initializing Variables Example


The following example illustrates the two methods for variable initialization:
#include ...
12;
char letter;
double pressure;
letter='E'; /* assign character value */
pressure=2
...
119999
letter is E
pressure is 2
...
For example:
1/2
0
3/2
1
The modulus operator % only works with integer operands
...
For example
7 % 2
1
12 % 3
0
29
C Programming

Increment/Decrement Operators


In C, specialized operators have been set aside for the incrementing and
decrementing of integer variables
...
These operators allow a form of shorthand in C:
++i;
--i;



is equivalent to
is equivalent to

i=i+1;
i=i-1;

The above example shows the prefix form of the increment/decrement
operators
...

– If ++k is used in an expression, k is incremented before the expression is
evaluated
...

Assume that the integer variables m and n have been initialized to zero
...
For example, the following
statement
k=k+5; can be written as k += 5;



The general syntax is
variable = variable op expression;



can alternatively be written as
variable op= expression;



common forms are:
+=
-=

*=

Examples:
j=j*(3+x);
a=a/(s-5);

j *= 3+x;
a /= s-5;



/=

%=

32
C Programming

Precedence & Associativity of Operators


The precedence of operators determines the order in which operations are
performed in an expression
...
If two operators in an expression have the same precedence, associativity
determines the direction in which the expression will be evaluated
...

Operators higher up in the following diagram have higher precedence
...

- ++ -* / %
+ =

R
L
L
R

L
R
R
L

33
C Programming

Precedence & Associativity of Operators Examples


This is how the following expression is evaluated
1 + 2 * 3 - 4
1 + 6 - 4
7 - 4
3



The programmer can use parentheses to override the hierarchy and force a
desired order of evaluation
...
For example:
(1 + 2) * (3 - 4)
3 * -1
-3

34
C Programming

The int Data Type


A typical int variable is in the range +-32,767
...
It is possible in C to
specify that an integer be stored in more memory locations thereby increasing
its effective range and allowing very large integers to be stored
...

long int national_debt;
• long int variables typically have a range of +-2,147,483,648
...
All that C guarantees is that a short int
will not take up more bytes than int
...
Negative integers
cannot be assigned to unsigned integers, only a range of positive values
...

35
C Programming

The float and double Data Types


As with integers the different floating point types available in C correspond to
different ranges of values that can be represented
...
The more bytes used the higher the
number of decimal places of accuracy in the stored value
...




The three C floating point types are:
float
double
long double



In general, the accuracy of the stored real values increases as you move down
the list
...
The ASCII code is used to
associate each character with an integer (see next page)
...
Internally, C
treats character variables as integers
...

/
0
1
2
3
4
5
6
7
8
9
:
;
<
=
>
?

Decimal
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

Char
sp
!
"
#
$
%
&
(
)
*
+
,

...
NOTE: the value of i stored in memory is unchanged
...

This automatic conversion takes place in two steps
...
In the
second step “lower” types are promoted to “higher” types
...
The type hierarchy is as
follows
long double
double
unsigned long
long
unsigned
39
int
C Programming

Automatic Type Conversion with Assignment Operator


Automatic conversion even takes place if the operator is the assignment
operator
...
For example, if x is double
and i an integer, then
x=i;

• i is promoted to a double and resulting value given to x


On the other hand say we have the following expression:
i=x;



A conversion occurs, but result is machine-dependent

40
C Programming

Type Casting


Programmers can override automatic type conversion and explicitly cast
variables to be of a certain type when used in an expression
...
The general syntax is
(type) expression



Some examples,
(char) 3 + 'A'
x = (float) 77;
(double) k * 57

41
C Programming

Input and Output








Basic Output
printf Function
Format Specifiers Table
Common Special Characters for Cursor Control
Basic Output Examples
Basic Input
Basic Input Example

42
C Programming

Basic Output


Now, let us look more closely at the printf() statement
...
When
the printf is executed, it starts printing the text in the control string until it
encounters a % character
...
A format specifier controls how the value of
a variable will be displayed on the screen
...
The d character that follows the % indicates that a (d)ecimal
integer will be displayed
...

43
C Programming

printf Function


General form of printf function
printf(control string,argument list);



where the control string consists of 1) literal text to be displayed, 2)
format specifiers, and 3)special characters
...
Number of arguments must match the number of
format identifiers
...


44
C Programming

Format Specifiers Table


The following table show what format specifiers should be used with what
data types:
Specifier

Type

%c

character

%d

decimal integer

%o

octal integer (leading 0)

%x

hexadecimal integer (leading 0x)

%u

unsigned decimal integer

%ld

long int

%f

floating point

%lf

double or long double

%e

exponential floating point

%s

character string
45
C Programming

Common Special Characters for Cursor Control


Some common special characters for cursor control are:

\n

newline

\t

tab

\r

carriage return

\f

form feed

\v

vertical tab

\b

backspace

\”

Double quote (\ acts as an “escape” mark)

\nnn

octal character value

46
C Programming

Basic Output Examples

printf(“ABC”);
printf(“%d\n”,5);
printf(“%c %c %c”,’A’,’B’,’C’);
printf(“From sea ”);
printf(“to shining “);
printf (“C”);
printf(“From sea \n”);
printf(“to shining \n“);
printf (“C”);
leg1=200
...
4;
printf(“It was %f
miles”,leg1+leg2);
num1=10; num2=33;
printf(“%d\t%d\n”,num1,num2);
big=11e+23;
printf(“%e \n”,big);
printf(“%c \n”,’?’);
printf(“%d \n”,’?’);
printf(“\007 That was a beep\n”);

ABC (cursor after the C)
5 (cursor at start of next line)
A B C
From sea to shining C

From sea
to shining
C
It was 557
...
100000e+24
?
63
try it yourself

47
C Programming

Basic Input


There is a function in C which allows the programmer to accept input from a
keyboard
...

#include ...
A prompt to
enter in a number is then printed with the first printf statement
...

In the control string, the format specifier %d shows what data type is expected
...
After the scanf routine completes, the variable pin will
be initialized with the input integer
...
The & character has a very special meaning in C
...
(Much more with & when we get to pointers…)
48
C Programming

Basic Input Example
#include ...
If you are inputting values for a
double variable, use the %lf format identifier
...
A blank is valid character input
...
In C, there are
statements that allow iteration of this type
...
An unconditional loop is
repeated a set number of times
...
Thus the actual number of iterations
performed can vary each time the loop is executed
...
Relational operators allow the comparison of two
expressions
...
If a is less than 4, this expression will evaluate to
TRUE
...




Exactly what does it mean to say an expression is TRUE or FALSE? C uses
the following definition
– FALSE means evaluates to ZERO
– TRUE means evaluates to any NON-ZERO integer(even negative integers)

52
C Programming

Relational Operators Table


The following table shows the various C relational operators
Operator

Example

==

Equal to

count == 10

!=

Not equal to

flag != DONE

<

Less than

a < b

<=

Less than or equal to

i <= LIMIT

>

Greater than

pointer > end_of_list

>=



Meaning

Greater than or equal to

lap >= start

The relational operators have a precedence below the arithmetic operators
...
The basic syntax of the for
statement is,
for (initialization expression; test expr; increment expr)
program statement;



Here is an example
sum=10;
for (i=0; i<6; ++i)
sum = sum+i;



The operation for the loop is as follows
1) The initialization expression is evaluated
...
If it is TRUE, body of the loop is executed
...

3) Assume test expression is TRUE
...

4) Evaluate the increment expression and return to step 2
...

54
C Programming

for Loop Example


Sample Loop:
sum = 10;
for (i=0; i<6; ++i)
sum=sum+i;



We can trace the execution of the sample loop as follows
Iteration

i

i<6

sum

1st
2nd
3rd
4th
5th
6th
7th

0
1
2
3
4
5
6

TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
FALSE

10
11
13
16
20
25
25
55
C Programming

for Loop Diagram


The following diagram illustrates the operation of a for loop

for (
{

1
1

;

2
2

;

4
4

)

TRUE

}
5
5

3
3

FALSE

56
C Programming

General Comments about for Loop


Some general comments regarding the use of the for statement:
– Control expressions are separated by ; not ,
– If there are multiple C statements that make up the loop body, enclose them in
brackets (USE INDENTATION FOR READABILITY)

for (x=100; x!=65; x-=5)
{
z=sqrt(x);
printf("The square root of %d is %f\n",x,z);
}
– Control expressions can be any valid expression
...

– Any of the control expressions can be omitted (but always need the two
semicolons for syntax sake)
...
Its format is
while(control expression)
program statement;



The while statement works as follows:
1) Control expression is evaluated (“entry condition”)
2) If it is FALSE, skip over the loop
...

4) Go back to step 1

59
C Programming

while Loop Example


Example while loop
i=1; factorial=1;
while (i<=n) {
factorial *= i;
i=i+1;
}



Programmer is responsible for initialization and incrementation
...
Otherwise: infinite loop
...
This guarantees that
the loop is executed at least once
...

2) The control expression is evaluated (“exit condition”)
...
If it is FALSE, exit loop
...
\n");
scanf("%d", &value);
do {
r_digit = value % 10;
printf("%d", r_digit);
value = value / 10;
} while (value != 0);
printf("\n");
}

62
C Programming

do while Loop Example: Error Checking


A common use of the do while statement is input error checking
...
A sample session using this loop looks
like this
Input a positive integer: -4
Input a positive integer: -34
Input a positive integer: 6

63
C Programming

Decision Making Statements











Introduction to Decision Making Statements
if Statement
if Statement Examples
if-else Statement
if-else Ladder
switch Statement
switch Statement Example
switch Statement Operation
switch Statement Example: Characters
switch Statement Example: Menus






Conditional Operator
Conditional Operator Examples
Logical Operators
Logical Operators Precedence
64
C Programming

Introduction to Decision Making Statements


Used to have a program execute different statements depending on certain
conditions
...
In C, there are three decision making statements
...
Program code is executed or skipped
...
If it is
FALSE, the body of the if is skipped
...
Avoid trying to compare real
variables for equality, or you may encounter unpredictable results
...
The syntax of the if-else
statement is
if (expression)
statement1;
else
statement2;
If the expression is TRUE, statement1 is executed; statement2 is
skipped
...

Some examples
if (xif (letter == 'e') {
min=x;
++e_count;
else
++vowel_count; }
min=y;
else
++other_count;
68
C Programming

if-else Ladder


What if we wanted to extend the task shown in the previous example and not
just counts how many e’s there are in a piece of text, but also make counts of
the other vowels? This is possible by nesting if-else statements together to
make what is called an if-else ladder
...
If no control expressions
are found to be TRUE, the final else statement acts as a default
...
It is C’s built-in multiple branch decision statement
...

default:
statement;
}



The keyword break should be included at the end of each case statement
...
In the switch statement, it causes an exit from the
switch shunt
...
The right brace at the end
marks the end of switch statement
...

2) A match is looked for between this expression value and the case
constants
...
If a
match is not found, execute the default statement
...




Some things to be aware of when using a switch statement:
– case values must be unique (How to decide otherwise?)
– switch statement only tests for equality
– The control expression can be of type character since they are
internally treated as integers

72
C Programming

switch Statement Example: Characters
switch(ch) {
case 'a':
++a_count;
break;
case 'b':
++b_count;
break;
case 'c':
case 'C':
/* multiple values, same statements */
++c_count; }

73
C Programming

switch Statement Example: Menus


A common application of the switch statement is to control menu-driven
software:
switch(choice) {
case 'S':
check_spelling();
break;
case 'C':
correct_errors();
break;
case 'D':
display_errors();
break;
default:
printf("Not a valid option\n"); }

74
C Programming

Conditional Operator


Short-hand notation for an if-else statement that performs assignments
...
The two symbols
used to denote this operator are the ? and the :
...
The general syntax is thus
condition ? expression1 : expression2;



If the result of condition is TRUE (non-zero), expression1 is evaluated
and the result of the evaluation becomes the result of the operation
...
Consider the example on the next page:

75
C Programming

Conditional Operator Examples
s = (x<0) ? -1 : x*x;


If x is less than zero, then s=-1
...




The following code sets the logical status of the variable even
if (number%2==0)
even=1;
else
even=0;



Identical, short-hand code to perform the same task is
even=(number%2==0) ? 1 : 0;
76
C Programming

Logical Operators


These operators are used to create more sophisticated conditional expressions
which can then be used in any of the C looping or decision making statements
we have just discussed
...
e
...
e
...


Operator

Symbol Usage

Operation

LOGICAL
AND

&&

exp1 && exp2 Requires both exp1 and exp2 to be
TRUE to return TRUE
...


LOGICAL
OR

||

LOGICAL
NOT

!

exp1 || exp2 Will be TRUE if either (or both) exp1 or
exp2 is TRUE
...

!exp
Negates (changes from TRUE to FALSE
and visa versa) the expression
...
The remaining logical operators have a precedence
below relational operators
...

Arrays are an example of a structured variable in which 1) there are a
number of pieces of data contained in the variable name, and 2) there is an
ordered method for extracting individual data items from the whole
...
Her first approach might be to create a
specific variable for each user
...
Arrays offer a solution to this problem
...
In C, indexing starts at
zero
...




The replacement of the previous example using an array looks like this:
int id[3];
/* declaration of array id */
id[0] = 101;
id[1] = 232;
id[2] = 231;



In the first line, we declared an array called id, which has space for three
integer variables
...
Thus,
array id has three elements
...

81
C Programming

Array Elements


The syntax for an element of an array called a is
a[i]



where i is called the index of the array element
...




In memory, one can picture the array id as in the following diagram:

id

101

232

231

id[0] id[1]

id[2]

82
C Programming

Declaring Arrays


Arrays may consist of any of the valid data types
...
Some examples are
int
float



array_name[n];

final[160];
distance[66];

During declaration consecutive memory locations are reserved for the array
and all its elements
...
Random junk is at each element’s memory
location
...
The initial values are enclosed in braces
...
g
...
0,7
...
2,3
...
8};



Some rules to remember when initializing during declaration
1 If the list of initial elements is shorter than the number of array elements, the
remaining elements are initialized to zero
...

3 If a static array is declared without a size specification, its size equals the
length of the initialization list
...


static int

a[]={-6,12,18,2,323};
84
C Programming

Using Arrays


Recall that indexing is the method of accessing individual array elements
...
A
common programming error is out-of-bounds array indexing
...
You could write over important memory locations, for example
...

Array variables and for loops often work hand-in-hand since the for loop
offers a convenient way to successively access array elements and perform
some operation with them
...
For this 2D array element,
image[i][j]



the first index value i specifies a row index, while j specifies a column index
...
Array c contains 6x4x2=48 doubles
...
Picture array b as
0th
column

2nd
column

3rd
column

4th
column

0th row

b[0][0]

b[0][1]

b[0][2]

b[0][3]

b[0][4]

1st row

b[1][0]

b[1][1]

b[1][2]

b[1][3]

b[1][4]

2nd row



1st
column

b[2][0]

b[2][1]

b[2][2]

b[2][3]

b[2][4]

In C, 2D arrays are stored by row
...

87
C Programming

Initializing Multi-Dimensional Arrays


This procedure is entirely analogous to that used to initialize 1D arrays at their
declaration
...
That is, the array is
initialized row by row
...

To make your program more readable, you can explicitly put the values to be
assigned to the same row in inner curly brackets:
static int age[2][3]={{4,8,12},{19,6,-1}};





In addition if the number of rows is omitted from the actual declaration, it is
set equal to the number of inner brace pairs:
static int age[][3]= ]={{4,8,12},{19,6,-1}};
88
C Programming

Using Multi-Dimensional Arrays


Again, as with 1D arrays, for loops and multi-dimensional arrays often work
hand-in-hand
...

Some examples
Summation of array elements
double temp[256][3000],sum=0;
int i,j;
for (i=0; i<256; ++i)
for (j=0; j<3000; ++j)
sum += temp[i][j];

Trace of Matrix
int voxel[512][512][512];
int i,j,k,trace=0;
for (i=0; i<512; ++i)
for (j=0; j<512; ++j)
for (k=0; k<512; ++k)
if (i==j && j==k)
trace += voxel[i][j][k];
89
C Programming

Strings











Arrays of Characters
Initializing Strings
Copying Strings
String I/O Functions
More String Functions
More String Functions Continued
Examples of String Functions
Character I/O Functions
More Character Functions
Character Functions Example

90
C Programming

Arrays of Characters







Strings are 1D arrays of characters
...
Don’t
forget to remember to count the end-of-string character when you calculate the
size of a string
...
Unlike
other 1D arrays the number of elements set for a string set during declaration
is only an upper limit
...
Consider the following code:
static char name[18] = "Ivanova";
The string called name actually has only 8 elements
...
String constants marked with
double quotes automatically include the end-of-string character
...

91
C Programming

Initializing Strings


Initializing a string can be done in three ways: 1) at declaration, 2) by reading
in a value for the string, and 3) by using the strcpy function
...
The following code would
produce an error:
char name[34];
name = "Erickson";



/* ILLEGAL */

To read in a value for a string use the %s format identifier:
scanf("%s",name);



Note that the address operator & is not needed for inputting a string variable
(explained later)
...

92
C Programming

Copying Strings


The strcpy function is one of a set of built-in string handling functions
available for the C programmer to use
...
h header file at the beginning of your program
...
The previous contents of string1 are overwritten
...
h>
main ()
{
char job[50];
strcpy(job,"Professor");
printf("You are a %s \n",job);
}
You are a Professor
93
C Programming

String I/O Functions






There are special functions designed specifically for string I/O
...
When the user hits a
carriage return the string is inputted
...

The function puts displays a string on the monitor
...

Here is a sample program demonstrating the use of these functions:
char phrase[100];
printf("Please enter a sentence\n");
gets(phrase);
puts(phrase);



A sample session would look like this

Please enter a sentence
The best lack all conviction, while the worst are passionate
...

94
C Programming

More String Functions


Included in the string
...
Here is a brief table of some of the more popular ones
Function

Operation

strcat
strchr
strcmp
strcmpi
strcpy
strlen
strncat
strncmp
strncpy
strnset
strrchr
strspn

Appends to a string
Finds first occurrence of a given character
Compares two strings
Compares two, strings, non-case sensitive
Copies one string to another
Finds length of a string
Appends n characters of string
Compares n characters of two strings
Copies n characters of one string to another
Sets n characters of string to a given character
Finds last occurrence of given character in string
Finds first substring from given character set in string
95
C Programming

More String Functions Continued


Most of the functions on the previous page are self-explanatory
...
Take for example,
strcmp which has this syntax
strcmp(string1,string2);



It returns an integer that is less than zero, equal to zero, or greater than zero
depending on whether string1 is less than, equal to, or greater than
string2
...
The following program
illustrates their use:
#include ...
The file ctype
...
Here is a partial list
Function
isalnum
isalpha
isascii
iscntrl
isdigit
isgraph
islower
isprint
ispunct
isspace
isupper
isxdigit
toascii
tolower
toupper

Operation
Tests for alphanumeric character
Tests for alphabetic character
Tests for ASCII character
Tests for control character
Tests for 0 to 9
Tests for printable character
Tests for lowercase character
Tests for printable character
Tests for punctuation character
Tests for space character
Tests for uppercase character
Tests for hexadecimal
Converts character to ASCII code
Converts character to lowercase
Converts character to upper
99
C Programming

Character Functions Example


In the following program, character functions are used to convert a string to all
uppercase characters:
#include ...
h>
main() {
char name[80];
int loop;
printf ("Please type in your name\n");
gets(name);
for (loop=0; name[loop] !=0; loop++)
name[loop] = toupper(name[loop]);
printf ("You are %s\n",name);
}



A sample session using this program looks like this:
Please type in your name
Dexter Xavier
You are DEXTER XAVIER

100
C Programming

Math Library Functions



“Calculator-class” Functions
Using Math Library Functions

101
C Programming

“Calculator-class” Library Functions


You may have started to guess that there should be a header file called
math
...
Well there is! Some functions found in math
...
h include file, the
user must explicitly load the math library during compilation
...
c -lm

103
C Programming

User-defined Functions













Introduction to User-defined
Functions
Reasons for Use
User-defined Functions Usage
Function Definition
User-defined Function Example 1
User-defined Function Example 2
return Statement
return Statement Example
Using Functions
Considerations when Using
Functions
Using Functions Example
Introduction to Function Prototypes









Function Prototypes
Recursion
Storage Classes
auto Storage Class
extern Storage Class
extern Storage Class Example
static and register Storage Class

104
C Programming

Introduction to User-defined Functions


A function in C is a small “sub-program” that performs a particular task, and
supports the concept of modular programming design techniques
...




We have already been exposed to functions
...
It is called by the operating system when the program is loaded, and
when terminated, returns to the operating system
...




But can the user define and use their own functions? Absolutely YES!

105
C Programming

Reasons for Use


There are many good reasons to program in a modular style:
– Don’t have to repeat the same block of code many times in your code
...

– Function portability: useful functions can be used in a number of programs
...
Make an
outline and hierarchy of the steps needed to solve your problem and create a
function for each step
...
Get one function working well then move on to the others
...
Just add more functions to extend program
capability
– For a large programming project, you will code only a small fraction of the
program
...


106
C Programming

User-defined Function Usage


In order to use functions, the programmer must do three things
– Define the function
– Declare the function
– Use the function in the main code
...


107
C Programming

Function Definition


The function definition is the C code that implements what the function does
...


108
C Programming

Function Definition Example 1


Here is an example of a function that calculates n!
int factorial (int n)
{
int i,product=1;
for (i=2; i<=n; ++i)
product *= i;
return product;
}

109
C Programming

Function Definition Example 2


Some functions will not actually return a value or need any arguments
...
Here is an example:
void write_header(void) {
printf("Navier-Stokes Equations Solver ");
printf("v3
...




The 2nd void keyword indicates that no arguments are needed for the
function
...

110
C Programming

return Statement




A function returns a value to the calling program with the use of the keyword
return, followed by a data variable or constant value
...
Some examples
return 3;
return n;
return ++a;
return (a*b);
When a return is encountered the following events occur:
1 execution of the function is terminated and control is passed back to the
calling program, and
2 the function call evaluates to the value of the return expression
...


111
C Programming

return Statement Examples


The data type of the return expression must match that of the declared
return_type for the function
...
0;
/*legal*/ }



It is possible for a function to have multiple return statements
...
0)
return x;
else
return -x;
}
112
C Programming

Using Functions


This is the easiest part! To invoke a function, just type its name in your
program and be sure to supply arguments (if necessary)
...
When the function is completed, control passes back to the main
program
...
In the above example, upon return from the factorial
function the statement
factorial(9)
362880
and that integer is assigned to the variable number
...

– The type of the arguments in the function call must match the type of the
arguments in the function definition
...

– The actual arguments are passed by-value to the function
...
Any changes made to the dummy argument in the function will NOT
affect the actual argument in the main program
...


#include ...
Consider the program on the
previous page
...
All the secondary
functions are defined first, and then we see the main program that shows the
major steps in the program
...
h>
int compute_sum(int n); /* Function Prototype */
main() {
int n=8,sum;
printf ("Main n (before call) is %d\n",n);
sum=compute_sum(n);
printf ("Main n (after call) is %d\n",n);
printf ("\nThe sum of integers from 1 to %d is %d\n",n,sum);}
int compute_sum(int n) {
int sum=0;
for(;n>0;--n)
sum+=n;
printf("Local n in function is %d\n",n);
return sum; }
116
C Programming

Function Prototypes


Now the program reads in a "natural" order
...
Perhaps you don’t care about the details of how the sum is
computed and you won’t need to read the actual function definition
...
The
prototype tells the compiler the number and type of the arguments to the
function and the type of the return value
...
The function definitions can then
follow the main program
...
h -- you will see the prototypes for all the string functions available!



In addition to making code more readable, the use of function prototypes
offers improved type checking between actual and dummy arguments
...

117
C Programming

Recursion


Recursion is the process in which a function repeatedly calls itself to perform
calculations
...

Recursive algorithms are not mandatory, usually an iterative approach can be
found
...
The storage class refers to the manner in which memory is allocated
for the variable
...
In C, the
four possible Storage classes are
– auto
– extern
– static
– register

119
C Programming

auto Storage Class


This is the default classification for all variables declared within a function
body [including main()]
...




They exist and their names have meaning only while the function is being
executed
...




When the function is exited, the values of automatic variables are not retained
...




They are recreated each time the function is called
...




If a variable is declared at the beginning of a program outside all functions
[including main()] it is classified as an external by default
...




Their storage is in permanent memory, and thus never disappear or need to be
recreated
...


121
C Programming

extern Storage Class Example


The following program illustrates the global nature of extern variables:
#include ...
First, the
function is much less portable to other programs
...
If a local variable has the same name as a global variable,
only the local variable is changed while in the function
...

122
C Programming

static and register Storage Class
static Storage Class
• A static variable is a local variable that retains its latest value when a
function is recalled
...
Basically, static variables are created and initialized once on
the first call to the function
...
(Consider a function that counts the number of times
it has been called)
...
So for performance reasons, it
is sometimes advantageous to store variables directly in registers
...

register int i;
for (i=0; i
...

You can control how many columns will be used to output the contents of a
particular variable by specifying the field width
...
Thus the format specifier %5d is interpreted as use 5 columns to
display the integer
...
If left adjustment is preferred use the syntax %-3c
...

Nice Feature:
If the value to be printed out takes up more columns than the specified field
width, the field is automatically expanded
...

#include ...
A sample format specifier would
look like this
%10
...
Don’t
forget to count the column needed for the decimal point when calculating the
field width
...
4f",4
...
0);



----1
...

127
C Programming

e Format Identifier


When using the e format identifier, the second number after the decimal point
determines how many significant figures (SF) will be displayed
...
4e",4
...
0);





_1
...
Remember that now the field
size must include the actual numerical digits as well as columns for ‘
...

It is possible to print out as many SFs as you desire
...
The following
table shows a rough guideline applicable to some machines:
Data Type
float
double
long double

# Mantissa bits
16
32
64

Precision (#SF)
~7
~16
~21
128
C Programming

Real Formatted Output Example
#include ...
123456;
double y=333
...
1f\n",x);
printf ("%20
...
3f\n",x);
printf ("%020
...
9f\n",y);
printf ("%
...
4e\n",y);
}
333
...
1
333
...
123
0000000000000333
...
123457
333
...
12345678901232304270
3
...
A more sophisticated
string format specifier looks like this
%6
...




For example;
printf("3
...
h>
main() {
static char s[]="an evil presence";
printf ("%s\n",s);
printf ("%7s\n",s);
printf ("%20s\n",s);
printf ("%-20s\n",s);
printf ("%
...
12s\n",s);
printf ("%15
...
12s\n",s);
printf ("%3
...
The formatting features that can be inserted
into the control string are
– Ordinary characters (not just format identifiers) can appear in the scanf
control string
...

These “normal” characters will not be read in as input
...

– As with formatted output, a field width can be specified for inputting values
...


132
C Programming

Formatted Input Examples
#include ...
h>
main() {
int m,n,o;
scanf("%d : %d : %d",&m,&n,&o);
printf("%d \n %d \n %d\n",m,n,o);
}
10 : 15 : 17
10
15
17
133
C Programming

Pointers









Introduction to Pointers
Memory Addressing
The Address Operator
Pointer Variables
Pointer Arithmetic
Indirection Operator
“Call-by-Reference” Arguments
“Call-by-Reference” Example









Pointers and Arrays
Pointers and Arrays Illustration
Pointers and Arrays Examples
Arrays as Function Arguments
Arrays as Function Arguments
Example
Pointers and Character Strings
Pointers and Character Strings
Example

134
C Programming

Introduction to Pointers


Pointers are an intimate part of C and separate it from more traditional
programming languages
...
Pointers enable us to







effectively represent sophisticated data structures
change values of actual arguments passed to functions (“call-by-reference”)
work with memory which has been dynamically allocated
more concisely and efficiently deal with arrays

On the other hand, pointers are usually difficult for new C programmers to
comprehend and use
...
We thus have the following picture:
memory
location



FFD2

?

i

variable name

After the statement i=35; the location corresponding to i will be filled
FFD2

35

i

136
C Programming

The Address Operator


You can find out the memory address of a variable by simply using the
address operator &
...




The following simple program demonstrates the difference between the
contents of a variable and its memory address:
#include ...
171828;
printf("The value of x is %f\n",x);
printf("The address of x is %X\n",&x); }
The value of x is 2
...
Like all other C
variables, pointers must be declared before they are used
...
In the above example,
p is the type “pointer to integer” and offset is the type “pointer to double”
...
This is usually
done with the address operator
...
The pointer p contains the memory address
of the variable count
...
The "unit" for the
arithmetic is the size of the variable being pointed to in bytes
...

– Integers and pointers can be added and subtracted from each other, and
– incremented and decremented
...
It returns the contents of the address stored in a pointer
variable
...
What is returned is the value
stored at the memory address p
...
h>
main() {
int a=1,b=78,*ip;
ip=&a;
b=*ip;
/* equivalent to b=a */
printf("The value of b is %d\n",b); }
The value of b is 1



Note that b ends up with the value of a but it is done indirectly; by using a
pointer to a
...




What if we would like the function to change the main variable’s contents?
– To do this we use pointers as dummy arguments in functions and indirect
operations in the function body
...


141
C Programming

“Call-by-Reference” Example


The classic example of “call-by-reference” is a swap function designed to
exchange the values of two variables in the main program
...
h>
void swap(int *p,int *q);
main() {
int i=3,j=9876;
swap(&i,&j);
printf("After swap, i=%d j=%d\n",i,j);
}
void swap(int *p,int *q) {
int temp;
temp=*p;
*p=*q;
*q=temp;
}
After swap, i=9876 j=3
142
C Programming

Pointers and Arrays


Although this may seem strange at first, in C an array name is an address
...




We have actually seen this fact before: when using scanf to input a character
string variable called name the statement looked like

• scanf("%s",name);



NOT

scanf("%s",&name);

Given this fact, we can use pointer arithmetic to access array elements
...
Once the function has the base address of the array, it
can use pointer arithmetic to work with all the array elements
...




Consider the following function designed to take the sum of elements in a 1D
array of doubles:
double sum(double *dp, int n) {
int i; double res=0
...
A very efficient
argument list
...
0;
for(i=0; ires += *(dp+i);
return res;
}



In the main program, the sum function could be used as follows
double position[150],length;
length=sum(position,150); /* sum entire array */
length=sum(position,75); /* sum first half */
length=sum(&position[10],10);/* sum from element
10 to element 20 */

147
C Programming

Pointers and Character Strings


As strange as this sounds, a string constant -- such as “Happy Thanksgiving” -is treated by the compiler as an address (Just like we saw with an array name)
...




Thus, we can use pointers to work with character strings, in a similar
manner that we used pointers to work with “normal” arrays
...
h>
main() {
char *cp;
cp="Civil War";
printf("%c\n",*cp);
printf("%c\n",*(cp+6));
}
C
W
148
C Programming

Pointers and Character Strings Example


Another example illustrates easy string input using pointers:
#include ...
Consider the data a teacher might need for a
high school student: Name, Class, GPA, test scores, final score, ad final course
grade
...
It is not a
variable declaration, but a type declaration
...
Consider the
following structure representing playing cards
...
To
access a given member the dot notation is use
...
Say we wanted to initialize the structure card1
to the two of hearts
...
pips=2;
card1
...
For example the following code:
card2
...
pips+5;
would make card2 the seven of some suit
...
In other words, each member of card3 gets assigned the value of
the corresponding member of card1
...
This is similar to the
initialization of arrays; the initial values are simply listed inside a pair of braces,
with each value separated by a comma
...
95,100,87,92,96,'A'};



The same member names can appear in different structures
...
For example:
struct fruit {
char *name;
int calories; } snack;
struct vegetable {
char *name;
int calories; } dinner_course;
snack
...
name="broccoli";
154
C Programming

Structures Example




What data type are allowed to structure members? Anything goes: basic types,
arrays, strings, pointers, even other structures
...

Consider the program on the next few pages which uses an array of structures
to make a deck of cards and deal out a poker hand
...
h>
struct playing_card {
int pips;
char *suit;
} deck[52];
void make_deck(void);
void show_card(int n);
main() {
make_deck();
show_card(5);
show_card(37);
show_card(26);
show_card(51);
show_card(19);
}
155
C Programming

Structures Example Continued
void make_deck(void) {
int k;
for(k=0; k<52; ++k) {
if (k>=0 && k<13) {
deck[k]
...
pips=k%13+2; }
if (k>=13 && k<26) {
deck[k]
...
pips=k%13+2; }
if (k>=26 && k<39) {
deck[k]
...
pips=k%13+2; }
if (k>=39 && k<52) {
deck[k]
...
pips=k%13+2; }
}
}

156
C Programming

More on Structures Example Continued
void show_card(int n) {
switch(deck[n]
...
suit);
break;
case 12:
printf("%c of %s\n",'Q',deck[n]
...
suit);
break;
case 14:
printf("%c of %s\n",'A',deck[n]
...
pips,deck[n]
...
Say
you wanted to make a structure that contained both date and time information
...
For example,
struct date {
int month;
int day;
int year; };
struct time {
int hour;
int min;
int sec; };
struct date_time {
struct date today;
struct time now; };



This declares a structure whose elements consist of two other previously
declared structures
...
The now element of the structure is initialized to eleven
hours, eleven minutes, eleven seconds
...
For example,
++veteran
...
sec;
if (veteran
...
month == 12)
printf("Wrong month! \n");

159
C Programming

Pointers to Structures


One can have pointer variable that contain the address of complete structures,
just like with the basic data types
...
pips=8;
(*card_pointer)
...




The type of the variable card_pointer is “pointer to a playing_card
structure”
...
It is officially called the structure pointer
operator
...
member is the same as struct_ptr->member



Thus, the last two lines of the previous example could also have been written
as:
card_pointer->pips=8;
card_pointer->suit="Clubs";
Question: What is the value of *(card_pointer->suit+2)?
Answer: ‘u’



As with arrays, use structure pointers as arguments to functions working
with structures
...

161
C Programming

Unions




Introduction to Unions
Unions and Memory
Unions Example

162
C Programming

Introduction to Unions




Unions are C variables whose syntax look similar to structures, but act in a
completely different manner
...
The union syntax is:
union tag_name {
type1 member1;
type2 member2;

};
For example, the following code declares a union data type called intfloat
and a union variable called proteus:
union intfloat {
float f;
int i;
};
union intfloat proteus;

163
C Programming

Unions and Memory


Once a union variable has been declared, the amount of memory reserved is
just enough to be able to represent the largest member
...




In the previous example, 4 bytes are set aside for the variable proteus since
a float will take up 4 bytes and an int only 2 (on some machines)
...
But only one member of a union can contain valid data at a
given point in the program
...


164
C Programming

Unions Example


The following code illustrates the chameleon-like nature of the union variable
proteus defined earlier
...
h>
main() {
union intfloat {
float f;
int i;
} proteus;
proteus
...
10e\n”,proteus
...
f);
proteus
...
0;
/* Statement 2 */
printf(“i:%12d f:%16
...
i,proteus
...
2273703755e-42
1166792216 f:4
...

After Statement 2, the data stored in proteus is a float, and the integer
value is meaningless
...
Similarly all
input has come from standard input (usually associated with the keyboard)
...
To work with files, the following steps must be taken:
1 Declare variables to be of type FILE
...
This association of a FILE variable with a file name is done with the
fopen() function
...

4 Break the connection between the internal FILE variable and actual disk
file
...

167
C Programming

Declaring FILE variables


Declarations of the file functions highlighted on the previous page must be
included into your program
...
h>



as the first statement in your program
...
This
variable must be of type FILE (which is a predefined type in C) and it is a
pointer variable
...

168
C Programming

Opening a Disk File for I/O


Before using a FILE variable, it must be associated with a specific file name
...
The following statement
in_file = fopen("myfile
...
dat for read
access
...
dat will only be read from
...




These functions take an additional (first) argument which is the FILE pointer
that identifies the file to which data is to be written to or read from
...
dat -- real and integer values into the
variables x and m respectively
...
This allows the
operating system to cleanup any resources or buffers associated with the file
...
Here is a
list of these functions
Function
Result
fgets
file string input
fputs
file string output
getc(file_ptr) file character input
putc(file_ptr) file character output



Another useful function for file I/O is feof() which tests for the end-of-file
condition
...
It returns zero (FALSE) otherwise
...
It is
an inventory program that reads from the following file
lima beans
1
...
76
5
10
Greaters ice-cream
3
...
58
12
10



which contains stock information for a store
...
h>
#include ...
h>
struct goods {
char name[20];
float price;
int quantity;
int reorder;
};
FILE *input_file;
void processfile(void);
void getrecord(struct goods *recptr);
void printrecord(struct goods record);
main() {
char filename[40];
printf("Example Goods Re-Order File Program\n");
printf("Enter database file \n");
scanf("%s",filename);
input_file = fopen(filename, "r");
processfile();
}
174
C Programming

Sample File I/O Program: processfile

void processfile(void) {
struct goods record;
while (!feof(input_file)) {
getrecord(&record);
if (record
...
reorder)
printrecord(record);
}
}

175
C Programming

Sample File I/O Program: getrecord

void getrecord(struct goods *recptr) {
int loop=0,number,toolow;
char buffer[40],ch;
float cost;
ch=fgetc(input_file);
while (ch!='\n') {
buffer[loop++]=ch;
ch=fgetc(input_file);
}
buffer[loop]=0;
strcpy(recptr->name,buffer);
fscanf(input_file,"%f",&cost);
recptr->price = cost;
fscanf(input_file,"%d",&number);
recptr->quantity = number;
fscanf(input_file,"%d",&toolow);
recptr->reorder = toolow;
}

176
C Programming

Sample File I/O Program: printrecord

void printrecord (struct goods record) {
printf("\nProduct name \t%s\n",record
...
price);
printf("Product quantity \t%d\n",record
...
reorder);
}

177
C Programming

Sample File I/O Program: sample session

Example Goods Re-Order File Program
Enter database file food
...
76
quantity
5
reorder level

Product
Product
Product
Product

name Greaters ice-cream
price
3
...
Consider a grading program used by a professor which
keeps track of student information in structures
...




Thus, it is desirable to create correct-sized array variables at runtime
...
The functions that accomplish this are calloc()
which allocates memory to a variable, sizeof(), which determines how
much memory a specified variable occupies, and free(), which deallocates
the memory assigned to a variable back to the system
180
C Programming

Dynamic Memory Allocation: sizeof


The sizeof() function returns the memory size (in bytes) of the requested
variable type
...
Consider the following code fragment:
struct time {
int hour;
int min;
int sec;
};
int x;
x=sizeof(struct time);

• x now contains how many bytes are taken up by a time structure (which
turns out to be 12 on many machines)
...
For example, it is valid to
write sizeof(double)
...
The function takes two arguments that specify the number
of elements to be reserved, and the size of each element in bytes (obtained
from sizeof)
...
The storage area is also initialized to zeros
...
The
above function call will allocate just enough memory for one hundred time
structures, and appt will point to the first in the array
...
hour=10;
appt[5]
...
sec=0;
182
C Programming

Dynamic Memory Allocation: free


When the variables are no longer required, the space which was allocated to
them by calloc should be returned to the system
...
The main function is allowed to have
dummy arguments and they match up with command-line arguments used
when the program is run
...

– argc contains the number of command-line arguments passed to the main
program and
– argv[] is an array of pointers-to-char, each element of which points
to a passed command-line argument
...
h>
main(int argc, char *argv[]) {
if (argc == 2)
printf("The argument supplied is %s\n", argv[1]);
else if (argc > 2)
printf("Too many arguments supplied
...
\n");
}



Note that *argv[0] is the program name itself, which means that
*argv[1] is a pointer to the first “actual” argument supplied, and
*argv[n] is the last argument
...
Thus for n arguments, argc will be equal to n+1
...
h>
main(int argc, char *argv[]) {
if (argc == 2)
printf("The argument supplied is %s\n", argv[1]);
else if (argc > 2)
printf("Too many arguments supplied
...
\n");
}
a
...

a
...
out help verbose
Too many arguments supplied
...

Equal, Not Equal
Bitwise AND
Bitwise Exclusive OR
Bitwise OR
Logical AND
Logical OR
Conditional Expression
Assignment
Comma

Represented by
() []

Title: c language for learners
Description: it is very easy to learn c program for beginners.