Full C Programming Material
Full C Programming Material
2
C Programming
Introduction
Why Learn C?
3
C Programming
Why Learn C?
4
C Programming
C Program Structure
5
C Programming
Canonical First Program
#include <stdio.h>
main()
{
/* My first program */
printf("Hello World! \n");
}
6
C Programming
Canonical First Program
#include <stdio.h>
main()
{
/* My first program */
printf("Hello World! \n");
}
7
C Programming
Canonical First Program
#include <stdio.h>
main()
{
/* My first program */
printf("Hello World! \n");
}
8
C Programming
Canonical First Program Output & Comments
/* My first program */
Comments can be inserted into C programs by bracketing text with the /* and
*/ delimiters. As will be discussed later, comments are useful for a variety of
reasons. Primarily they serve as internal documentation for program structure
and functionality.
9
C Programming
Header Files
Header files contain declarations of functions and variables which can be
incorporated into any C program by using the pre-processor #include statement.
Standard header files are provided with each compiler, and cover a range of areas:
string handling, mathematics, data conversion, printing and reading of variables, etc.
To use any of the standard functions, the appropriate header file should be included.
This is done at the beginning of the C source file. For example, to use the function
printf() in a program, the line
#include <stdio.h>
should be at the beginning of the source file, because the declaration for printf() is
found in the file stdio.h. All header files have the extension .h and generally reside
in the /usr/include subdirectory. Some examples:
#include <string.h>
#include <math.h>
#include "mylib.h"
The use of angle brackets <> informs the compiler to search the compilers include
directories for the specified file. The use of the double quotes "" around the filename
informs the compiler to start the search in the current directory for the specified file.
10
C Programming
Names in C
11
C Programming
Comments
12
C Programming
Why use comments?
Best programmers comment as they write the code, not after the fact.
13
C Programming
Symbolic Constants
Symbolic constants are names given to values that cannot be changed.
Implemented with the #define preprocessor directive.
#define N 3000
#define FALSE 0
#define PI 3.14159
#define FIGURE "triangle"
Note that preprocessor statements begin with a # symbol, and are NOT
terminated by a semicolon. Traditionally, preprocessor statements are listed at
the beginning of the source file.
Preprocessor statements are handled by the compiler (or preprocessor) before
the program is actually compiled. All # statements are processed first, and the
symbols (like N) which occur in the C program are replaced by their value
(3000). Once these substitutions has taken place by the preprocessor, the
program is then compiled.
By convention, preprocessor constants are written in UPPERCASE. This acts
as a form of internal documentation to enhance program readability and
reuse.
In the program itself, values cannot be assigned to symbolic constants.
14
C Programming
Use of Symbolic Constants
The whole point of using #define in your programs is to make them easier
to read and modify. Considering the above program as an example, what
changes would you need to make if the TAXRATE was changed to 20%?
Obviously, the answer is one, edit the #define statement which declares the
symbolic constant and its value. You would change it to read
#define TAXRATE 0.20
Without the use of symbolic constants, you hard code the value 0.20 in
your program, and this might occur several times (or tens of times).
15
C Programming
Variables, Expressions, and Operators
16
C Programming
Declaring Variables
17
C Programming
Basic Format
where data_type is one of the four basic types, an integer, character, float,
or double type. Examples are
int i,j,k;
float length,height;
char midinit;
18
C Programming
Basic Data Types: INTEGER
INTEGER: These are whole numbers, both positive and negative. Unsigned
integers(positive values only) are also supported. In addition, there are short
and long integers. These specialized integer types will be discussed later.
int
int age;
19
C Programming
Basic Data Types: FLOAT
FLOATING POINT: These are positive and negative REAL numbers which
contain fractional parts. They can be written in either floating point notation or
scientific notation.
float
Typical floating point values are 1.73 and 1.932e5 (1.932 x 105). An example
of declaring a float variable called x is
float x;
20
C Programming
Basic Data Types: DOUBLE
DOUBLE: These are floating point numbers, both positive and negative,
which have a higher precision than float variables.
double
double voltage;
21
C Programming
Basic Data Types: CHARACTER
char
Typical character values might be the letter A, the character 5, the symbol ,
etc. An example of declaring a character variable called letter is
char letter;
22
C Programming
Expressions and Statements
a + b
3.0*x - 9.66553
tan(angle)
sum = x + y + z;
printf("Go Buckeyes!");
23
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. For example:
i=0;
x=34.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. Note that
when assigning a character value the character should be enclosed in single
quotes.
24
C Programming
The Assignment Operator Evaluation
a=7;
two things actually occur. The integer variable a gets the value of 7, and the
expression a=7 evaluates to 7. This allows a shorthand for multiple
assignments of the same value to several variables in a single statement. Such
as
x=y=z=13.0;
as opposed to
x=13.0;
y=13.0;
z=13.0;
25
C Programming
Initializing Variables
C variables may be initialized with a value when they are declared. Consider
the following declaration, which declares an integer variable count and sets
its starting value to 10.
In general, the user should not assume that variables are initialized to some
default value automatically by the compiler. Programmers must ensure that
variables have proper values before they are used in expressions.
26
C Programming
Initializing Variables Example
27
C Programming
Arithmetic Operators
Negation - Modulus %
Multiplication * Addition +
Division / Subtraction -
When the / operator is used to perform integer division the resulting integer
is obtained by discarding (or truncating) the fractional part of the actual
floating point value. For example:
1/2 0
3/2 1
The modulus operator % only works with integer operands. The expression
a%b is read as a modulus b and evaluates to the remainder obtained after
dividing a by b. For example
7 % 2 1
12 % 3 0
28
C Programming
Increment/Decrement Operators
29
C Programming
Prefix versus Postfix
The difference between prefix and postfix forms is apparent when the
operators are used as part of a larger expression.
If ++k is used in an expression, k is incremented before the expression is
evaluated.
If k++ is used in an expression, k is incremented after the expression is
evaluated.
The above distinction is also true of the decrement operator --
Assume that the integer variables m and n have been initialized to zero. Then
in the following statement
a=++m + ++n; m 1, n 1, then a 2
whereas in this form of the statement
a=m++ + n++; a 0 then m 1, n 1
30
C Programming
Advanced Assignment Operators
31
C Programming
Precedence & Associativity of Operators
- ++ -- R L
* / % L R Precedence
+ - L R
= R L
32
C Programming
Precedence & Associativity of Operators: Examples
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. Expressions enclosed in parentheses are
evaluated first. For example:
(1 + 2) * (3 - 4)
3 * -1
-3
33
C Programming
The int Data Type
A typical int variable is in the range 32,767. This value differs from
computer to computer and is thus machine-dependent. It is possible in C to
specify that an integer variable be stored using more memory bytes thereby
increasing its effective range and allowing very large integers to be
represented. This is accomplished by declaring the integer variable to have
type long int.
long int national_debt;
long int variables typically have a range of 2,147,483,648.
There are also short int variables which may or may not have a smaller
range than normal int variables. All that C guarantees is that a short int
will not take up more bytes than int.
There are unsigned versions of all three types of integers. Negative integers
cannot be assigned to unsigned integers, only a range of positive values. For
example
unsigned int salary;
typically has a range of 0 to 65,535.
34
C Programming
The float and double Data Types
float
double
long double
In general, the accuracy of the stored real values increases as you move down
the list.
35
C Programming
The char Data Type
Variables of type char take up exactly one byte in memory and are used to
store printable and non-printable characters. The ASCII code is used to
associate each character with an integer (see next page). For example the
ASCII code associates the character m with the integer 109. Internally, C
treats character variables as integers.
36
C Programming
ASCII Character Set
Ctrl Decimal Code Decimal Char Decimal Char Decimal Char Decimal Char
^@ 0 NUL 32 sp 32 sp 64 @ 96 `
^A 1 SOH 33 ! 33 ! 65 A 97 a
^B 2 STX 34 " 34 " 66 B 98 b
^C 3 ETX 35 # 35 # 67 C 99 c
^D 4 EOT 36 $ 36 $ 68 D 100 d
^E 5 ENQ 37 % 37 % 69 E 101 e
^F 6 ACK 38 & 38 & 70 F 102 f
^G 7 BEL 39 39 71 G 103 g
^H 8 BS 40 ( 40 ( 72 H 104 h
^I 9 HT 41 ) 41 ) 73 I 105 I
^J 10 LF 42 * 42 * 74 J 106 j
^K 11 VT 43 + 43 + 75 K 107 k
^L 12 FF 44 , 44 , 76 L 108 l
^M 13 CR 45 - 45 - 77 M 109 m
^N 14 SOH 46 . 46 . 78 N 110 n
^O 15 ST 47 / 47 / 79 O 111 o
^P 16 SLE 48 0 48 0 80 P 112 p
^Q 17 CS1 49 1 49 1 81 Q 113 q
^R 18 DC2 50 2 50 2 82 R 114 r
^S 19 DC3 51 3 51 3 83 S 115 s
^T 20 DC4 52 4 52 4 84 T 116 t
^U 21 NAK 53 5 53 5 85 U 117 u
^V 22 SYN 54 6 54 6 86 V 118 v
^W 23 ETB 55 7 55 7 87 W 119 w
^X 24 CAN 56 8 56 8 88 X 120 x
^Y 25 EM 57 9 57 9 89 Y 121 y
^Z 26 SIB 58 : 58 : 90 Z 122 z
^[ 27 ESC 59 ; 59 ; 91 [ 123 {
^\ 28 FS 60 < 60 < 92 \ 124 |
^] 29 GS 61 = 61 = 93 ] 125 }
^^ 30 RS 62 > 62 > 94 ^ 126 ~
^_ 31 US 63 ? 63 ? 95 _ 127 DEL
37
C Programming
Automatic Type Conversion
How does C evaluate and type expressions that contain a mixture of different
data types? For example, if x is a double and i an integer, what is the type of
the expression
x+i
In this case, i will be converted to type double and the expression will
evaluate to a double. NOTE: the value of i stored in memory is unchanged.
A temporary copy of i is converted to a double and used in the expression
evaluation.
This automatic conversion takes place in two steps. First, all floats are
converted to doubles and all characters and shorts are converted to ints. In the
second step lower types are promoted to higher types. The expression
itself will have the type of its highest operand. The type hierarchy is as
follows
long double
Higher types
double
unsigned long
long
unsigned Lower types
int
38
C Programming
Automatic Type Conversion: The Assignment Operator
x=i;
i=x;
39
C Programming
Type Casting
(double) i
(type) expression
Some examples,
x = (float) 77;
(double) k * 57
40
C Programming
Input and Output
Basic Output
printf Function
Format Specifiers Table
Special Characters for Cursor Control
Basic Output Examples
Basic Input
Basic Input Example
41
C Programming
Basic Output
42
C Programming
printf Function
43
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
44
C Programming
Special Characters for Cursor Control
\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
45
C Programming
Basic Output Examples
printf(ABC); ABC (cursor after the C)
printf(%d\n,5); 5 (cursor at start of next line)
printf(%c %c % c,A,B,C); A B C
printf(From sea ); From sea to shining C
printf(to shining );
printf (C);
printf(From sea \n); From sea
printf(to shining \n); to shining
printf (C); C
leg1=200.3; leg2=357.4;
printf(It was %f miles It was 557.700012 miles
,leg1+leg2);
num1=10; num2=33;
printf(%d\t%d\n,num1,num2); 10 33
big=11e+23;
printf(%e \n,big); 1.100000e+24
printf(%c \n,?); ?
printf(%d \n,?); 63
printf(\007 That was a beep\n); try it yourself
46
C Programming
Basic Input
There is a function in C which allows the program to accept input from the
keyboard. The following program illustrates the use of this function.
#include <stdio.h>
main() {
int pin;
printf("Please type in your PIN\n");
scanf("%d",&pin);
printf("Your access code is %d\n",pin);}
What happens in this program? An integer called pin is defined. A prompt to
enter in a number is then printed with the first printf statement. The scanf
routine, which accepts the response, has a control string and an address list.
In the control string, the format specifier %d shows what data type is expected.
The &pin argument specifies the memory location of the variable the input
will be placed in. After the scanf routine completes, the variable pin will
be initialized with the input integer. This is confirmed with the second
printf statement. The & character has a very special meaning in C. It is the
address operator. (Much more with & when we get to pointers)
47
C Programming
Basic Input Example
#include <stdio.h>
main() {
int pin;
printf("Please type in your PIN\n");
scanf("%d",&pin);
printf("Your access code is %d\n",pin);}
The format identifier used for a specific C data type is the same as for the
printf statement, with one exception. If you are inputting values for a
double variable, use the %lf format identifier.
White space is skipped over in the input stream (including carriage return)
except for character input. A blank is valid character input.
48
C Programming
Basic Input Example (Two Variables)
The following code inputs two float values using one scanf statement:
#include <stdio.h>
main() {
float x,y;
printf("Please type the coordinates\n");
scanf("%f%f",&x,&y);
printf(The position is (%f,%f)\n",x,y);
}
A session using the above code would look like this:
49
C Programming
Program Looping
50
C Programming
Introduction to Program Looping
51
C Programming
Relational Operators
Our first use of relational operators will be to set up the condition required to
control a conditional loop. Relational operators allow the comparison of two
expressions. Such as
a < 4
which reads a less than 4. If a is less than 4, this expression will evaluate to
TRUE. If not it will evaluate to FALSE.
52
C Programming
Relational Operators Table
53
C Programming
for Loop
54
C Programming
for Loop Example
sum = 10;
for (i=0; i<6; ++i)
sum=sum+i;
for ( 11 ; 22 ; 44 )
{
TRUE
} 33
55 FALSE
56
C Programming
for Loop: General Comments
Some common observations regarding the use of the for statement:
Control expressions are separated by ; (semicolon) not , (comma)
If there are multiple C statements that make up the loop body, enclose them in
brackets (USE INDENTATION FOR READABILITY)
Control expressions can be any valid expression. They dont necessarily have
to perform initialization, testing, and incrementation.
Any of the control expressions can be omitted (but always need the two
semicolons for syntax sake).
product=1;
for (i=1;i<=6;)
product*=i++; 57
C Programming
for Loop: General Comments
Since testing is performed at the beginning of the loop, the body may never get
executed
x=10;
for (y=10;y!=x;++y)
printf ("%d",y);
58
C Programming
while Loop
while(control expression){
program statement 1;
program statement 2;
}
The while statement works as follows:
59
C Programming
while Loop Example
60
C Programming
do while Loop
The do while statement is a variant of the while statement in which the
conditional test is performed at the bottom of the loop. This guarantees that
the loop is executed at least once.
62
C Programming
do while Loop Example: Error Checking
The user will remain in this loop continually being prompted for and entering
integers until a positive one is entered. A sample session using this loop looks
like this
63
C Programming
Decision Making Statements
64
C Programming
Introduction to Decision Making Statements
65
C Programming
if Statement
if (control expression)
program statement;
Because of the way in which floating point types are stored, it makes it less
reliable to compare such types for equality. Avoid trying to compare real
variables for equality, especially if the values are nearly identical.
66
C Programming
if Statement Examples
Customize output
if (grade >= 90)
printf("\nCongratulations!");
printf("\nYour grade is "%d",grade);
Nested ifs
if (letter >= 'A')
if (letter <= 'Z')
printf("The letter is a capital \n");
67
C Programming
if-else Statement
Used to decide between two courses of action. The syntax of the if-else
statement is
if (expression)
statement1;
else
statement2;
If the expression is TRUE, statement1 is executed; statement2 is
skipped.
If the expression is FALSE, statement2 is executed; statement1 is
skipped.
Some examples
if (x < y) if (letter == 'e') {
min=x; ++e_count;
else printf(Found an e\n);
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 es 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. For example, consider the following
code if (letter == 'a')
++a_count;
else if (letter == 'e')
++e_count;
else if (letter == 'i')
++i_count;
else if (letter == 'o')
++o_count;
else if (letter == 'u')
++u_count;
else
++const_count;
As soon as a TRUE control expression is found, the statement associated with
it is executed and the rest of the ladder is bypassed. If no control expressions
are found to be TRUE, the final else statement acts as a default.
69
C Programming
switch Statement
The switch statement is a alternate way of writing a program which employs
an if-else ladder. It is Cs built-in multiple branch decision statement.
The syntax for the switch statement is as follows:
The keyword break should be included at the end of each case statement. In
general, whenever a break statement is encountered in C, it interrupts the
normal flow of control. In the switch statement, it causes an exit from the
switch. The default clause is optional. The right brace at the end marks the
end of switch statement.
70
C Programming
switch Statement Example
switch(n) {
case 12:
printf("value is 12\n");
break;
case 25:
printf("value is 25\n");
break;
case 03:
printf("value is 03\n");
break;
default:
printf("number is not part of the Xmas date\n");
}
71
C Programming
switch Statement Operation
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
switch(choice) {
case 'S':
check_spelling(); /* User-written function */
break;
case 'C':
correct_errors(); /* ditto */
break;
case 'D':
display_errors(); /* ditto */
break;
default:
printf("Not a valid option\n");
}
74
C Programming
Conditional Operator
75
C Programming
Conditional Operator Examples
s = (x<0) ? -1 : x*x;
If x is less than zero, then s=-1. If x is greater than or equal to zero, then
s=x*x.
The following code sets the logical status of the variable even
if (number%2==0)
even=1;
else
even=0;
even=(number%2==0) ? 1 : 0;
76
C Programming
Logical Operators
The negation operator, !, has the highest precedence and is always performed
first in a mixed expression. The remaining logical operators have a precedence
below relational operators.
done=0;
while(!done) {
}
78
C Programming
Array Variables
79
C Programming
Introduction to Array Variables
Arrays are a data structure which hold multiple values of the same data type.
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.
Consider the case where a programmer needs to keep track of the ID numbers
of people within an organization. Her first approach might be to create a
specific variable for each user. This might look like
It becomes increasingly more difficult to keep track of the IDs as the number
of personnel increases. Arrays offer a solution to this problem.
80
C Programming
Array Variables Example
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. Each piece of data in an array is called an element. Thus,
array id has three elements. After the first line, each element of id is
initialized with an ID number.
81
C Programming
Array Elements
where i is called the index of the array element. The array element id[1] is
just like any normal integer variable and can be treated as such.
82
C Programming
Declaring Arrays
Arrays may consist of any of the valid data types. Arrays are declared along
with all other variables in the declaration section of the program and the
following syntax is used
type array_name[n];
int final[160];
float distance[66];
During declaration consecutive memory locations are reserved for the array
and all its elements. After the declaration, you cannot assume that the elements
have been initialized to zero. Random junk is at each elements memory
location.
83
C Programming
Initializing Arrays during Declaration
If the declaration of an array is preceded by the word static, then the array can
be initialized at declaration. The initial values are enclosed in braces. e.g.,
1 If the list of initial elements is shorter than the number of array elements, the
remaining elements are initialized to zero.
2 If a static array is not explicitly initialized at declaration, its elements are
automatically initialized to zero.
3 If a static array is declared without a size specification, its size equals the
length of the initialization list. In the following declaration, a has size 5.
84
C Programming
Using Arrays
85
C Programming
Multi-Dimensional Arrays
Multi-dimensional arrays have two or more index values which are used to
specify a particular element in the array. For this 2D array element,
image[i][j]
the first index value i specifies a row index, while j specifies a column index.
Declaring multi-dimensional arrays is similar to the 1D case:
86
C Programming
Multi-Dimensional Array Illustration
In C, 2D arrays are stored in memory by row. Which means that first the
0th row is put into its memory locations, the 1st row then takes up the next
memory locations, the 2nd row takes up the next memory locations, and so on.
87
C Programming
Initializing Multi-Dimensional Arrays
88
C Programming
Using Multi-Dimensional Arrays
Again, as with 1D arrays, for loops and multi-dimensional arrays often work
hand-in-hand. In this case, though, loop nests are what is most often used.
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
String Library Functions
Using String Functions
Character I/O Functions
Character Library Functions
Character Functions Example
90
C Programming
Arrays of Characters
91
C Programming
Initializing Strings
char name[34];
name = "Erickson"; /* ILLEGAL */
scanf("%s",name);
Note that the address operator & is not needed for inputting a string variable
(explained later). The end-of-string character will automatically be appended
during the input process.
92
C Programming
Copying Strings
These are special functions designed specifically for string I/O. They do not
have the above restriction: input strings may have spaces.
gets(string_name);
puts(string_name);
The gets function reads in a string from the keyboard. When the user hits a
carriage return the string is inputted. The carriage return is not part of the
string and the end-of-string character is automatically appended.
The function puts displays a string on the monitor. It does not print the end-
of-string character, but does output a carriage return at the end of the string.
94
C Programming
String I/O Sample Program
char phrase[100];
printf("Please enter a sentence\n");
gets(phrase);
puts(phrase);
95
C Programming
More String Functions
Declared in the string.h file are several more string-related functions that
are free for you to use. Here is a brief table of some of the more popular ones
Function Operation
strcat Appends to a string
strchr Finds first occurrence of a given character
strcmp Compares two strings
strcmpi Compares two, strings, non-case sensitive
strcpy Copies one string to another
strlen Finds length of a string
strncat Appends n characters of string
strncmp Compares n characters of two strings
strncpy Copies n characters of one string to another
strnset Sets n characters of string to a given character
strrchr Finds last occurrence of given character in string
strspn Finds first substring from given character set in string
96
C Programming
More String Functions Continued
Most of the functions on the previous page are self-explanatory. The UNIX
man pages provide a full description of their operation. 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.
97
C Programming
Examples of String Functions
Function Result
strlen(s1) 15 /* e-o-s not counted */
strlen(s2) 9
strcmp(s1,s2) negative number
strcmp(s3,s2) positive number
strcat(s2, tonight) blue moon tonight
98
C Programming
Character I/O Functions
Analogous to the gets and puts functions there are the getchar and
putchar functions specially designed for character I/O. The following
program illustrates their use:
#include <stdio.h>
main() {
int n; char lett;
putchar('?');
n=45;
putchar(n-2);
lett=getchar();
putchar(lett);
putchar('\n');
}
99
C Programming
More Character Functions
100
C Programming
Character Functions Example
In the following program, character functions are used to convert a string to all
uppercase characters:
#include <stdio.h>
#include <ctype.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);
}
101
C Programming
Math Library Functions
Calculator-class Functions
Using Math Library Functions
102
C Programming
Calculator-class Library Functions
You may have started to guess that there should be a header file called
math.h which contains declarations of useful calculator-class
mathematical functions. Well there is! Some functions found in math.h are
acos asin atan
cos sin tan
cosh sinh tanh
exp log log10
pow sqrt
ceil floor
erf
gamma
j0 j1 jn
y0 y1 yn
103
C Programming
Using Math Library Functions
double c, a, b
c=sqrt(pow(a,2)+pow(b,2));
In some cases, to use the math functions declared in the math.h include file,
the user must explicitly load the math library during compilation. On most
systems the compilation would look like this:
cc myprog.c -lm
104
C Programming
User-defined Functions
105
C Programming
Introduction to User-defined Functions
But can the programmer define and use their own functions? Absolutely YES!
106
C Programming
Reasons for Modular Programming
Dont have to repeat the same block of code many times in your code. Make
that code block a function and reference it when needed.
Function portability: useful functions can be used in a number of programs.
Supports the top-down technique for devising a program algorithm. Make an
outline and hierarchy of the steps needed to solve your problem and create a
function for each step.
Easy to debug. Get one function working correctly then move on to the others.
Easy to modify and expand. Just add more functions to extend program
capability
For a large programming project, a specific programmer will code only a
small fraction of the program.
Makes program self-documenting and readable.
107
C Programming
Three Steps Required
In order to use their own functions, the programmer must do three things (not
necessarily in this order):
108
C Programming
Function Definition
The function definition is the C code that implements what the function does.
Function definitions have the following syntax
109
C Programming
Function Definition Example 1
110
C Programming
Function Definition Example 2
Some functions will not actually return a value or need any arguments. For
these functions the keyword void is used. Here is an example:
void write_header(void) {
printf("Navier-Stokes Equations Solver ");
printf("v3.45\n");
printf("Last Modified: ");
printf("12/04/95 - viscous coefficient added\n");
}
The 2nd void keyword indicates that no arguments are needed for the
function.
This makes sense because all this function does is print out a header statement.
111
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. The return statement
can even contain an expression. 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 reference evaluates to the value of the return
expression.
If there is no return statement control is passed back when the closing brace
of the function is encountered (falling off the end).
112
C Programming
return Statement Examples
The data type of the return expression must match that of the declared
return_type for the function.
double absolute(double x) {
if (x>=0.0)
return x;
else
return -x;
}
113
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 actual arguments (if necessary). A statement
using our factorial function would look like
number=factorial(9);
114
C Programming
Considerations when using Functions
Some points to keep in mind when referencing functions (your own or a
librarys):
The number of actual arguments in the function reference must match the
number of dummy arguments in the function definition.
The type of the actual arguments in the function reference must match the
type of the dummy arguments in the function definition. (Unless automatic
type conversion occurs).
The actual arguments in the function reference are matched up in-order with
the dummy arguments in the function definition.
The actual arguments are passed by-value to the function. The dummy
arguments in the function are initialized with the present values of the actual
arguments.
Any changes made to a dummy argument inside the function
will NOT affect the corresponding actual argument in the main
program. 115
C Programming
Pass-by-Value
int factorial(int n) {
int result;
if (n<=1)
result=1;
else
result = n * factorial(n-1);
return result;
}
119
C Programming
Storage Classes
Every variable in C actually has two attributes: its data type and its storage
class. The storage class refers to the manner in which memory is allocated
for the variable. The storage class also determines the scope of the variable,
that is, what parts of a program the variables name has meaning. In C, the
four possible Storage classes are
auto
extern
static
register
120
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.
121
C Programming
extern Storage Class
122
C Programming
extern Storage Class Example
124
C Programming
Formatted Input and Output
Formatted Output
char and int Formatted Output Example
f Format Identifier
e Format Identifier
Real Formatted Output Example
s Format Identifier
Strings Formatted Output Example
Formatted Input
Formatted Input Examples
125
C Programming
Formatted Output
Can you control the appearance of your output on the screen? Or do you have
to accept the default formatting provided by the C compiler? It turns out you
can format your output in a number of ways.
You can control how many columns will be used to output the contents of a
particular variable by specifying the field width. The desired field width is
inserted in the format specifier after the % and before the letter code indicating
the data type. Thus, the format specifier %5d is interpreted as use 5 columns to
display the integer. Further examples:
126
C Programming
char and int Formatted Output Example
This program and it output demonstrate various-sized field widths and their
variants.
#include <stdio.h>
main() {
char lett='w';
int i=1,j=29;
printf ("%c\n",lett); w
printf ("%4c\n",lett); w
printf ("%-3c\n",lett); w
printf ("%d\n",i); 1
printf ("%d\n",j); 29
printf ("%10d\n",j); 29
printf ("%010d\n",j); 0000000029
printf ("%-010d\n",j); 29
printf ("%2o\n",j); 35
printf ("%2x\n",j); 1d
}
127
C Programming
f Format Identifier
For floating-point values, in addition to specifying the field width, the number
of decimal places can also be set. A sample format specifier would look like
this
%10.4f
field number of
width decimal places
Note that a period separates the two numbers in the format specifier. Dont
forget to count the column needed for the decimal point when calculating the
field width. We can use the above format identifier as follows:
printf("%10.4f",4.0/3.0); ----1.3333
128
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. For example
printf("%10.4e",4.0/3.0); _1.333e+10
130
C Programming
s Format Identifier
For strings, the field length specifier works as before and will automatically
expand if the string size is bigger than the specification. A more sophisticated
string format specifier looks like this
%6.3s
where the value after the decimal point specifies the maximum number of
characters printed.
For example;
printf(%3.4s\n","Sheridan"); Sher
131
C Programming
Strings Formatted Output Example
#include <stdio.h>
main() {
static char s[]="an evil presence";
132
C Programming
Formatted Input
Modifications can be made to the control string of the scanf function which
enables more sophisticated input. 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. They must exactly match corresponding characters in the input.
These normal characters will not be read in as input.
As with formatted output, a field width can be specified for inputting values.
The field width specifies the number of columns used to gather the input.
133
C Programming
Formatted Input Examples
#include <stdio.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
#include <stdio.h>
main() {
int i; char lett; char word[15];
scanf("%d , %*s %c %5s",&i,&lett,word);
printf("%d \n %s \n %s\n",i,lett,word);
}
45 , ignore_this C read_this
45
C
read_
134
C Programming
Pointers
135
C Programming
Pointer Uses
On the other hand, pointers are usually difficult for new C programmers to
comprehend and use. If you remember the following simple statement,
working with pointers should be less painful
136
C Programming
Memory Addressing
a memory location with a certain address is set aside for any values that will be
placed in i. We thus have the following picture:
FFD2 35 i
137
C Programming
The Address Operator
You can find out the memory address of a variable by simply using the
address operator &. Here is an example of its use:
&v
Consider the artificial example shown on the previous page, &i would be the
memory address FFD2
As will be shown, when using pointers the programmer never needs to know
actual value of any memory address. Only that a pointer variable contains a
memory address.
138
C Programming
Pointer Variables
139
C Programming
Pointer Arithmetic
Some examples,
140
C Programming
Indirection Operator
141
C Programming
Memory Point-of-View
The following diagrams illustrate what occurred in memory while our sample
program (previous slide) was run:
1 a 78 b
ip 1 a 78 b
ip 1 a 1 b
142
C Programming
Call-by-Reference Arguments
143
C Programming
Tripling Function
#include <stdio.h>
main() {
float x=43.15;
triple_value(&x);
printf(x is now %0.4f\n",x);
}
144
C Programming
Swap Function
main() {
int i=3,j=9876;
swap(&i,&j);
printf("After swap, i=%d j=%d\n",i,j);
}
145
C Programming
Pointers and Arrays
We have actually seen this fact before: when using scanf to input a character
array called name the statement looked like
Given this fact, we can use pointer arithmetic to access array elements.
Adding one to the array name can move a pointer to the next array element,
add another one and the pointer moves to the element after that, and so on
In this manner the entire array can be indirectly accessed with a pointer
variable.
146
C Programming
Pointers and Arrays Figure
147
C Programming
Pointers and Arrays Examples
The next examples show how to sum up all the elements of a 1D array using
different approaches:
Normal way (element notation)
int a[100],i,*p,sum=0;
148
C Programming
Arrays as Function Arguments
When you are writing functions that work on arrays, it is efficient to use
pointers as dummy arguments. Once the function has the base address of the
array, it can use pointer arithmetic to indirectly work with all the array
elements. The alternative is to use global array variables or -- more horribly --
pass all the array elements into the function.
Note that all the sum function needed was a starting address in the array
and the number of elements to be summed together (n). A compact argument
list.
149
C Programming
Arrays as Function Arguments Example
In the main program, the sum function could be used in any of these ways:
double position[150],length;
150
C Programming
Pointers and Character Strings
main() {
char *cp;
cp="Civil War"; /* Now this is legal */
printf("%c\n",*cp);
printf("%c\n",*(cp+6));
}
C
W
151
C Programming
Alternate Definition of a String
main() {
char *name;
printf("Who are you?\n");
scanf("%s",name);
printf("Hi %s welcome to the party, pal\n",name);
}
Who are you?
Seymour
Hi Seymour welcome to the party, pal
152
C Programming
Structures
Introduction to Structures
Structure Variable Declaration
Structure Members
Initializing Structure Members
Array of Structures
Structures within Structures
Initializing Structures within Structures
Pointers to Structures
Structure Pointer Operator
153
C Programming
Introduction to Structures
struct student {
char name[45];
keyword char class;
float gpa;
structure
data type name int test[3]; member name & type
int final;
char grade;
}; /* Easy to forget this semicolon */
154
C Programming
Structure Variable Declaration
To actually declare a structure variable, the standard syntax is used:
You can declare a structure type and variables simultaneously. Consider the
following structure representing playing cards.
struct playing_card {
int number;
char *suit;
} card1,card2,card3;
Notice that in both the structure type declaration and the structure variable
declaration the keyword struct must precede the meaningful name you
chose for the structure type.
155
C Programming
Structure Members
The different variable types stored in a structure are called its members. To
access a given member the dot notation is use. The dot is officially called
the member access operator. Say we wanted to initialize the structure card1
to the two of hearts. It would be done this way:
card1.number = 2;
card1.suit = "Hearts";
Once you know how to name of a member, it can be treated the same as any
other variable of that type. For example the following code:
card2.number = card1.number + 5;
would make card2 the seven of some suit.
Structure variables can also be assigned to each other, just like with other
variable types:
card3 = card1;
would fill in the card3 number member with 2 and the suit member with
Hearts. In other words, each member of card3 gets assigned the value of
the corresponding member of card1.
156
C Programming
Initializing Structure Members
157
C Programming
Array of Structures
What data type are allowed to be structure members? Anything goes: basic
types, arrays, strings, pointers, even other structures. You can even make an
array of 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.
#include <stdio.h>
struct playing_card {
int number;
char *suit;
};
struct playing_card 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); 158
} C Programming
Array of Structures
void make_deck(void) {
int k;
for(k=0; k<52; ++k) {
if (k>=0 && k<13) {
deck[k].suit="Hearts";
deck[k].number=k%13+2; }
if (k>=13 && k<26) {
deck[k].suit="Diamonds";
deck[k].number=k%13+2; }
if (k>=26 && k<39) {
deck[k].suit="Spades";
deck[k].number=k%13+2; }
if (k>=39 && k<52) {
deck[k].suit="Clubs";
deck[k].number=k%13+2; }
}
}
159
C Programming
Array of Structures
void show_card(int n) {
switch(deck[n].number) {
case 11:
printf("%c of %s\n",'J',deck[n].suit);
break;
case 12:
printf("%c of %s\n",'Q',deck[n].suit);
break;
case 13:
printf("%c of %s\n",'K',deck[n].suit);
break;
case 14:
printf("%c of %s\n",'A',deck[n].suit);
break;
default:
printf("%c of %s\n",deck[n].number,deck[n].suit);
}
}
7 of Hearts
K of Spades
2 of Spades
A of Clubs
8 of Diamonds
160
C Programming
Structures within Structures
As mentioned earlier, structures can have as members other structures. Say
you wanted to make a structure that contained both date and time information.
One way to accomplish this would be to combine two separate structures; one
for the date and one for the time. 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.
161
C Programming
Initializing Structures within Structures
which sets the today element of the structure veteran to the eleventh of
November, 1918. The now element of the structure is initialized to eleven
hours, eleven minutes, eleven seconds. Each item within the structure can be
referenced if desired. The dot notation will be used twice. For example,
++veteran.now.sec;
if (veteran.today.month == 12)
printf("Wrong month! \n");
162
C Programming
Pointers to Structures
One can have pointer variable that contain the address of a structure variable,
just like with the basic data types. Structure pointers are declared and used in
the same manner as simple pointers:
The above code has indirectly initialized the structure down_card to the
Eight of Clubs through the use of the pointer card_pointer.
163
C Programming
Pointers to Structures: ->
164
C Programming
Unions
Introduction to Unions
Unions and Memory
Unions Example
165
C Programming
Introduction to Unions
Unions are C variables whose syntax look similar to structures, but act in a
completely different manner. A union is a variable that can take on different
data types in different situations. 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;
};
166
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. (Unlike a structure
where memory is reserved for all members).
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).
Data actually stored in a unions memory can be the data associated with any
of its members. But only one member of a union can contain valid data at a
given point in the program.
It is the users responsibility to keep track of which type of data has most
recently been stored in the union variable.
167
C Programming
Unions Example
The following code illustrates the chameleon-like nature of the union variable
proteus defined on the previous page.
#include <stdio.h>
main() {
union intfloat {
float f;
int i;
} proteus;
proteus.i=4444 /* Statement 1 */
printf(i:%12d f:%16.10e\n,proteus.i,proteus.f);
proteus.f=4444.0; /* Statement 2 */
printf(i:%12d f:%16.10e\n,proteus.i,proteus.f);
}
i: 4444 f:6.2273703755e-42
i: 1166792216 f:4.440000000e+03
After Statement 1, data stored in proteus is an integer the the float member
is full of junk.
After Statement 2, the data stored in proteus is a float, and the integer
value is meaningless.
168
C Programming
File Input and Output
169
C Programming
Introduction to File Input and Output
So far, all the output (formatted or not) in this course has been written out to
what is called standard output (which is traditionally the monitor). Similarly
all input has come from standard input (commonly assigned to the
keyboard). A C programmer can also read data directly from files and write
directly to files. To work with a file, the following steps must be taken:
2 Connect the internal FILE variable with an actual data file on your hard
disk. This association of a FILE variable with a file name is done with the
fopen() function.
3 Perform I/O with the actual files using fprint() and fscanf()
functions. (All you have learned still works).
4 Break the connection between the internal FILE variable and actual disk
file. This disassociation is done with the fclose() function.
170
C Programming
Declaring FILE variables
#include <stdio.h>
The first step is using files in C programs is to declare a file variable. This
variable must be of type FILE (which is a predefined type in C) and it is a
pointer variable. For example, the following statement
FILE *in_file;
171
C Programming
Opening a Disk File for I/O
Before using a FILE variable, it must be associated with a specific file name.
The fopen() function performs this association and takes two arguments:
1) the pathname of the disk file
2) the access mode which indicates how the file is to be used.
The following statement
in_file = fopen("myfile.dat","r");
connects the local variable in_file to the disk file myfile.dat for read
access. Thus, myfile.dat will only be read from. Two other access modes
are also useful:
w indicating write-mode
a indicating append_mode
172
C Programming
Reading and Writing to Disk Files
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. Thus the
statement,
fscanf(in_file,"%f%d",&x,&m);
will input -- from the file myfile.dat -- real and integer values into the
variables x and m respectively.
173
C Programming
Closing a Disk File
The fclose function in a sense does the opposite of what the fopen does: it
tells the system that we no longer need access to the file. This allows the
operating system to cleanup any resources or buffers associated with the file.
fclose(in_file);
174
C Programming
Additional File I/O Functions
Many of the specialized I/O functions for characters and strings that we have
described in this course have analogs which can be used for file I/O. 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. feof takes one argument -- the FILE pointer -- and returns a
nonzero integer value (TRUE) if an attempt has been made to read past the end
of a file. It returns zero (FALSE) otherwise. A sample use:
while( !feof(in_file) ) {
printf (Still have lines of data\n");
}
175
C Programming
Sample File I/O Program
The program on the next few pages illustrates the use of file I/O functions. It is
an inventory program that reads from the following file
lima beans
1.20
10
5
thunder tea
2.76
5
10
Greaters ice-cream
3.47
5
5
boneless chicken
4.58
12
10
which contains stock information for a store. The program will output those
items which need to be reordered because their number-on-hand is below a
certain limit
176
C Programming
Sample File I/O Program: main
#include <stdio.h>
#include <ctype.h>
#include <string.h>
struct goods {
char name[20];
float price;
int quantity;
int reorder;
};
FILE *stock_list;
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);
stock_list = fopen(filename, "r");
processfile();
} 177
C Programming
Sample File I/O Program: processfile
void processfile(void) {
struct goods record;
while (!feof(stock_list)) {
getrecord(&record);
if (record.quantity <= record.reorder)
printrecord(record);
}
}
178
C Programming
Sample File I/O Program: getrecord
fscanf(stock_list,"%f",&cost);
recptr->price = cost;
fscanf(stock_list,"%d",&number);
recptr->quantity = number;
fscanf(stock_list,"%d",&toolow);
recptr->reorder = toolow;
}
179
C Programming
Sample File I/O Program: printrecord
180
C Programming
Sample File I/O Program: sample session
181
C Programming
Dynamic Memory Allocation
182
C Programming
Introduction to Dynamic Memory Allocation
183
C Programming
Dynamic Memory Allocation: sizeof
The sizeof() auxillary function returns the memory size (in bytes) of a
requested variable type. This call should be used in conjunction with the
calloc() function call, so that the correct amount of memory on that
machine is allocated. 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). sizeof can also be used to determine
the memory size of basic data type variables as well. For example, it is valid to
write sizeof(double).
184
C Programming
Dynamic Memory Allocation: calloc
185
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. This is done by,
free(appt);
186
C Programming
Command-Line Arguments
187
C Programming
Introduction to Command-Line Arguments
In every program seen so far, the main function has had no dummy arguments
between its parentheses. The main function is allowed to have dummy
arguments and they match up with command-line arguments used when the
program is run.
The two dummy arguments to the main function are called argc and argv.
188
C Programming
Command-Line Arguments Example
Note that *argv[0] is the program name itself, which means that
*argv[1] is a string containing the first actual argument supplied, and
*argv[n] is the last argument string. If no arguments are supplied, argc
will be one. Thus for n arguments, argc will be equal to n+1.
189
C Programming
Command-Line Arguments: Sample Session
#include <stdio.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");
else
printf("One argument expected.\n");
}
$ a.out
One argument expected.
$ a.out help
The argument supplied is help
$ a.out help verbose
Too many arguments supplied.
190
C Programming
String-to-Number Conversion
Lets say one the command line arguments is the string 200. In your
program, you (probably) want to use this command line argument as the
integer 200.
To perform the conversion, a useful function is sscanf, a member of the
scanf family of functions. sscanf allows reading input from a string.
The syntax for sscanf is
sscanf(input string, control string, address list);
Consider this sample program (convert.c) and a demonstration of using it:
#include <stdio.h>
void main(int argc, char *argv[]) {
int limit;
printf(First command line arg is %s\n,argv[1];
sscanf(argv[1],%d,&limit);
limit += 100;
printf(Integer limit is now %d\n,limit);
}
$ cc o convert convert.c
$ convert 200
First command line arg is 200
Integer limit is now 300
191
C Programming
Software Engineering
Structured Programming
Inheriting Weaknesses
Top-down With C
Example: Dithering Pallets
Makefiles
Platform independent packages
192
C Programming
Structured Programming
194
C Programming
Top-down with C
195
C Programming
Example: Dithering Pallets
196
C Programming
Example: Dithering Pallets
struct PixelData {
int greyval;
char dithval;
};
Declare macros and static variables
#define minval(x, y) (x < y) ? x : y
Functions grouped in four files
img_dither.c
main procedure
convert.c
void CnvrtImage(struct PixelData *d, char *pal, int n, int w, int h, int max )
Take the PixelData structure, palette, passed by reference
Take the width, height, and maxval, passed by value
197
C Programming
Example: Dithering Pallets
198
C Programming
Example: Dithering Pallets
Compile command
Previous exercises main() and subroutines in one file
Link to math library
-lm, shorthand for libm.so or libm.a
For many functions use man pages, man sqrt
Compiler looks in standard locations
/usr/lib
/usr/local/lib
Can direct to special purpose libraries
-L/myown/libraries/
Compiler looks in the directory path for linked library
199
C Programming
Example: Dithering Pallets
200
C Programming
Example: Dithering Pallets
201
C Programming
Makefiles
202
C Programming
Platform independent packages
Cmake
Cross-platform, open-source make system
Used to control the software compilation process
uses simple platform and compiler independent configuration files
Generates native makefiles and workspaces
Can be used in the compiler environment of your choice
Used in projects like VTK and Paraview
Imake
imake is a Makefile-generator
Easier to develop software portably for multiple systems
Makefiles are inherently non-portable
Instead of writing a Makefile, you write an Imakefile
machine-independent description of what targets you want to build
Both are not too widely used
203
C Programming
Platform independent packages
Gnu autoconf
Extensible package of m4 macros
Produces shell scripts
automatically configure software source code packages.
Can adapt the packages to many kinds of UNIX-like systems without manual user
intervention
Autoconf creates a configuration script for a package
A template file lists the operating system features that the package can use
In the form of m4 macro calls.
GNU m4 is an implementation of the traditional UNIX macro processor
It is mostly SVR4 compatible
Becoming more popular
204
C Programming
Operator Precedence Table
Description Represented by
1 Parenthesis () []
1 Structure Access . ->
2 Unary ! ++ -- - * &
3 Multiply, Divide, Modulus * / %
4 Add, Subtract + -
5 Shift Right, Left >> <<
6 Greater, Less Than, etc. > < => <=
7 Equal, Not Equal == !=
8 Bitwise AND &
9 Bitwise Exclusive OR ^
10 Bitwise OR |
11 Logical AND &&
12 Logical OR ||
13 Conditional Expression ? :
14 Assignment = += -= etc
15 Comma ,
205
C Programming
Problem Set
1) Write a program that sets the length and width of a rectangle to 13.5 and
5.375. Your program should then calculate and output the area and
perimeter of the rectangle.
2) Write a program that works with two Cartesian points (3.4,12.3) and
(5.6,15.0). Compute the slope of the straight line between these two points
and their midpoint. Output your results. (If you need help with any math
formulae, just ask your instructor).
3) Write a program that converts a temperature of 35 Celsius to degrees
Fahrenheit. The conversion equation is:
TF = (9.0/5.0)Tc + 32
4) Write a program that sets up variables to hold the distance of a job
commute in miles, the cars fuel efficiency in mpg, and the price of
gasoline. Set the distance to 5.5 miles, the mpg to 20.0 miles/gallon and the
cost of gas to be $1.78 a gallon. Your program should then calculate and
output the total cost of the commute.
206
C Programming
5) Write a program that will calculate the final exam grade a student must
achieve in order to get a certain percentage of the total course points. You may
assume that the student has already taken three exams worth 100 points. The
final exam is worth 200 points. Your program should read in the scores on the
first three exams and the percentage the student is shooting for. Your program
should then calculate and print out the final exam score needed to achieve that
percentage.
6) Print a table of values for F where F = xy-1 and x has values 1, 2, ,9 and y
has values 0.5, 0.75, 1.0, ,2.5.
7) The numbers 1, 2, 3, 5, 8, 13, 21, 34, where each number after the second is
equal to the sum of the two numbers before it, are are called Fibonacci
numbers. Write a program that will print the first 50 Fibonacci numbers.
(Some Fibonacci numbers can be quite large )
8) Write a program that will calculate interest on an initial deposit. Your
program should read in the beginning balance and an annual interest rate and
print out how much money you would have each year for a run of twenty
years.
207
C Programming
9) Write a program that reads in three integers i, j, k. Determine if the integers
are in ascending order (i <= j <= k) or descending order (i >= j >= k) or in
neither order. Print an appropriate message.
10) Write a program to read in the coefficients A, B, C of a quadratic equation
Ax2 + Bx + C = 0
and solve it. If the roots are positive or zero, print the values. If the roots are
complex, compute the real and imaginary parts as two real numbers and print
these with appropriate formatting.
11) Write a program that calculates the approximate square root of a number x by
repeating the following formula:
Next Guess = 0.5 (Last Guess + x / Last Guess)
Use an initial guess of 1.0. You will know when your approximation is good
enough by comparing the Next Guess with the Last Guess. If the difference
between them is <0.000001, you stop your iteration: you have calculated the
approximate square root.
208
C Programming
12) Write a program that will determine the amount of change to return to a
customer.Your program should read in the price of the object and the amount
of money the customer gives. If the amount tendered equals the price, thank
the customer for the exact change. If not, let the customer know if he needs to
pay more or if he will get change back. In either case, your program should
break down the difference into dollars, half-dollars, quarters, dimes, nickels,
and pennies.
13) Write a program that will guess the number the user is thinking of between 1
and 10000. The program should print out a guess which is always the mid-
point of the range of numbers remaining. Hence, the first prompt the computer
will ask is if the number is equal to, above, or below 5000. The player should
press E for equal, A for above, or B for below. The program should read in
the response and repeat its prompt with the new guess. For example, if the
number was above 5000, the computer would repeat the question with a guess
of 7500. The process continues until the computer guesses the number. Once
the number is guessed, the computer should ask if the user wants to play again
and act appropriately.
209
C Programming
14) Write a program which will input a 2D array of integers and summarize the
frequency of occurrence of each of the ten digits. For example, the following
array:
8 0 0
7 5 0
1 2 3
9 0 0
would produce the following results:
Digit Occurrences Digit Occurrences
0 5 5 1
1 1 6 0
2 1 7 1
3 0 8 1
4 0 9 1
210
C Programming
15) Write a program to compute the transpose on a double 2D matrix.
16) Write a program that will input a 3X3 array of integers and determine if it is a
magic square. Magic squares have a special property: the values in each
row, in each column, and in each diagonal add up to the same number.
17) Write a program that normalizes the float values in a 3D array to values
between 0.0 and 1.0.
18) Write a program that inputs a piece of text and analyzes its characters. Your
program should:
Determine which character has the highest ASCII code
Determine which character has the lowest ASCII code
Determine which character(s) occurred most often in text and how many times
they appeared
Count the number of times certain special characters appeared:
Punctuation symbols
Upper-case letters
Lower-case letters
Vowels (either case)
Numerical digits 211
C Programming
19) Write a program in which an input string is checked to see if it is a palindrome
(reads the same backwards as forwards, i.e., MADAM).
20) Write a program that will input a character string and output the same
character string but without any blanks or punctuation symbols.
21) Write a program that will read in a value of x and compute the value of the
Gaussian function at that value
2
(1/2) e x /2
Check out your function in the main program.
22) Write a function total that will convert its three arguments representing hours,
minutes, and seconds to all seconds. Write a prototype for total and use it in a
main program.
23) Write a function range that receives an integer array with 50 elements and
calculates the maximum and minimum values (which should be represented as
global variables). Check out the function range with sample data in a main
program.
212
C Programming
24) Write a program in which the total, average, and standard deviation of a float
array X with 100 data values are calculated. The total, average, and standard
deviation should each be calculated in a separate function.
25) Write a program to print the following pattern on the screen:
*
***
*****
***
*
26) Write a program to read in the diameter of a circle. Compute the radius,
circumference and area of the circle. Print the calculated values in the
following format:
PROPERTIES OF A CIRCLE WITH DIAMETER XXXX.XXX
(1) RADIUS = XXXX.XXX
(2) CIRCUMFERENCE = XXXX.XXX
(3) AREA = XXXX.XXX 213
C Programming
27) Write a program that uses loops to produce the following formatted output:
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
28) Using pointers, write a function that will copy the first half of one string into
another.
29) Extend the deck of cards program shown in the handouts so that it deals out
eight poker hands and ranks them. (You will need to use a random-number
function to randomly generate cards from the deck.)
30) Using structures, write a program that will keep track of the electoral votes by
state won by a candidate in a presidential election. The structures should
contain the state name, number of electoral votes, and what party won the
state. The user should be able to find out the following from the program:
214
C Programming
How many total votes a certain party has
How that total breaks down by state
How many votes are still needed to win (270 needed to win)
Here are the number of electoral votes for each state: Alabama9, Alaska3,
Arizona8, Arkansas6, California54, Colorado8, Connecticut8,
Delaware3, District of Columbus3, Florida25, Georgia13, Hawaii
4, Idaho4, Illinois22, Indiana-12, Iowa7, Kansas6, Kentucky8,
Louisiana9, Maine4, Maryland10, Massachusetts12, Michigan18,
Minnesota10, Mississippi7, Missouri11, Montana3, Nebraska5,
Nevada4, New Hampshire4, New Jersey15, New Mexico5, New
York33, North Carolina14, North Dakota3, Ohio21, Oklahoma8,
Oregon7, Pennsylvania23, Rhode Island4, South Carolina8, South
Dakota3, Tennessee11, Texas32, Utah5, Vermont3, Virginia13,
Washington11, West Virginia5, Wisconsin11, Wyoming3
To simulate the election, have the user enter in a state name and what party won it,
and check the tallies. Keep providing input until we have a President.
215
C Programming
31) Assume that a data file called points.dat contains a set of coordinates. The
first line of the file contains the number of data coordinates in the file and each
of the remaining lines contain the x and y data values of one of the data points.
Write a program that will read in the data points and make a new file called
polar.dat that prints the coordinates in polar form instead of rectangular
form. The following are the conversion equations:
r = (x2 + y2)1/2
= atan(y/x)
32) Write an inventory program that uses the goods structure defined in the main
handout. Prompt the user to enter the number of items to be stored in the
warehouse and then dynamically allocate an array of goods structures that is
exactly that size. Initialize the goods array with your own choices.
33) Write a program to accept a number of integer arguments on the command line
and print out the max, min, sum, and average of the numbers passed.
216
C Programming