Professional Documents
Culture Documents
0.1. DEFINITION
We use programming languages to write computer programs. Although there are many different
programming languages, the mist commonly used today are called high-level languages because
it is close to the human languages.
This is the native tongue of a computer. Each machine instruction is a binary string of 0s and 1s
that specifies an operation and identifies the memory cells involved in that operation. For
example, if we wanted to represent the algebraic formula:
Area = width*length
In a machine language program, we might need a sequence of instructions such as the following:
0001 0000 1110 0100
1010 1101 0011 0010
0101 0001 1101 0000
Although the computer would have no difficulty understanding the three machine languages
instructions above, they are unintelligible to most people.
Writing larger programs in assembly language is quite difficult and hence, high-level languages
were developed (like BASIC).For example, in C, you would use the instruction
2
C PROGRAMMING 2013-2014 UR
area = width * length
which closely resembles the original formula. This statement means “ multiply the value of width
by the value of length and store the result as area”.
The development of Ada was driven largely by the US Department of Defense, wich
sought a single high-level language to be used in the specialized program applications
area known as real-time, distributed systems.
BASIC (Beginners All-purpose Symbolic Instruction Code) was designed to be easily
learned and used by students.
COBOL (Common Business-Oriented Language) is primarily for business data-
processing operations.
FORTRAN (FORmula TRANslator) is primarily used by engineers and scientists.
Lisp ( LISt Processing) is a language used primarily in artificial intelligence applications.
Pascal was developed primarily for teaching introductory programming by following a
particular approach often referred to as structured programming. This language was
named after the famous mathematician and philosopher Blaise Pascal. It was very popular
during the 80's and 90's.
The C language, developed in 1972 by Dennis Ritchie of Bell Laboratories, is highly
versatile language that has been used in a wide variety of applications, from operating
systems implementation (such as UNIX) to database and large-scale, numeric-processing
applications. C++ is based on C; it is also a versatile programming language that is
rapidly gaining wide acceptance in the computing field. It is becoming increasingly
popular for teaching programming concepts, partly because it provides powerful features
useful for practicing modern approaches to software development.
MATLAB (matrix laboratory) is a tool for doing numerical computations with matrices
and vectors. It can also display information graphically.
PHP is a newer programming language with focus on web design.
JAVA is an object oriented interpreted programming language. It has gained popularity in
the past few years for its ability to be run on many platforms, including Microsoft
Windows, Linux, Mac OS, and other systems. It was developed by Sun Microsystems.
3
C PROGRAMMING 2013-2014 UR
The following steps can be followed to prepare a program for execution:
1. Use the editor program to enter each line of the source program into memory and to save
it on disk as a source file.
2. Use a compiler program to translate the source program into machine language. If there is
any syntax errors (errors in grammar), the compiler displays these errors on the monitor.
Compile the program into machine-language. The machine language program produced is
called the object code. At this stage the compiler may find Syntax errors in the program.
3. Use the editor program to correct the errors by editing and resaving the source program.
When the source program is error free, the compiler saves its machine language as an
object file.
Use the Linker/loader program to combine the object file with additional object files that may be
needed for the program to execute ( for example , programs for input and output). The
linker/loader can also save the final machine language program as an executable file on disk.
CHAPTER I: OVERVIEW OF C
1.1. DEFINITIONS
1.1.1. Compiler
The compiler will read each and every character that has been typed in the program code. After
reading the entire code, the compiler will convert the code into machine level format (i.e. 0s and
1s). Technically speaking, the microprocessor in a computer can understand only binary numbers
(only 0s and 1s). It is not possible for us to write programs in binary numbers. Compilers will
convert the coding for a program into machine understandable form (i.e. it will convert the
instructions we type into machine understandable form). Compilation is the process of
converting the source code into machine language.
1.1.2. Keywords
Keyword is a word that the compiler already knows, i.e. when the compiler sees a keyword
somewhere in the program it knows what to do automatically.
4
C PROGRAMMING 2013-2014 UR
There are 32 words defined as keywords in C. These have predefined uses and cannot be used for
any other purpose in a C program. They are used by the compiler as an aid to compiling the
program. They are always written in lower case. A complete list follows;
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
1.1.3. Debugging
Debugging is the process of identifying bugs in the code. A bug is a programming term for an
„error‟.
1.1.4 Preprocessor
• 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
1.3.1. Comments
Comments are parts of the source code disregarded by the compiler. They simply do nothing.
Their purpose is only to allow the programmer to insert notes or descriptions embedded within
the source code. They serve as internal documentation for program structure and functionality.
C supports two ways to insert comments:
// line comment
/* block comment */
6
C PROGRAMMING 2013-2014 UR
The first of them, known as line comment, discards everything from where the pair of slash signs
(//) is found up to the end of that same line. The second one, known as block comment, discards
everything between the /* characters and the first appearance of the */ characters, with the
possibility of including more than one line.
Why use comments?
7
C PROGRAMMING 2013-2014 UR
found in the file stdio.h.
All header files have the extension .h and generally reside
in the /usr/include subdirectory.
#include <string.h>
#include <math.h>
#include "mylib.h"
#include<filename>
Example: #include<stdio.h>
#include<math.h>// allows to read mathematical functions: trigonometric functions(
tan(x),sin(x),cos(x);logarithmic functions (log(x)= ln(x),log10(x)), exp(x), pow(x,y)=xy,
Note: The line #include <stdio.h> must start in column one. It causes the compiler to
include the text of the named file (in this case stdio.h) in the program at this point. The
file stdio.h allows the compiler to read input/output streams. All your programs will
include this file.
<assert.h> : Diagnostics
<ctype.h> : Character Class Tests
<errno.h> : Error Codes Reported by (Some) Library Functions
<float.h> : Implementation-defined Floating-Point Limits
<limits.h> : Implementation-defined Limits
<locale.h> : Locale-specific Information
<math.h> : Mathematical Functions
<setjmp.h> : Non-local Jumps
<signal.h> : Signals
<stdarg.h> : Variable Argument Lists
<stddef.h> : Definitions of General Use
8
C PROGRAMMING 2013-2014 UR
<stdio.h> : Input and Output
<stdlib.h> : Utility functions
<string.h> : String functions
<time.h> : Time and Date functions
9
C PROGRAMMING 2013-2014 UR
10
C PROGRAMMING 2013-2014 UR
1.4. Data types
1.4.1. Definition
A data type provides a method of modeling or representing a particular set of values and
determines what operations can be performed on those values. For the moment only four variable
types are considered, namely, int, float, double and char. These types hold values as follows:
int: variables can represent negative and positive integer values (whole numbers). There is a limit
on the size of value that can be represented, which depends on the number of bytes of
storage allocated to an int variable by the computer system and compiler being used. On a
PC most compilers allocate two bytes for each int which gives a range of -32768 to
+32767. On workstations, four bytes are usually allocated, giving a range of -2147483648
to 2147483647. It is important to note that integers are represented exactly in computer
memory.
float :variables can represent any real numeric value, that is both whole numbers and numbers
that require digits after the decimal point.Usually four bytes are allocated for float
variables, this gives an accuracy of about six significant figures and a range of about -1038
to +1038. It is important to note that float values are only represented approximately.
char variables represent a single character -- a letter, a digit or a punctuation character. They
usually occupy one byte, giving 256 different possible characters. The bit patterns for characters
usually conform to the American Standard Code for Information Interchange (ASCII).
Examples of values for such variables are:
int 123 -56 0 5645
float 16.315 -0.67 31.567
char '+' 'A' 'a' '*' '7'
Built in Types -
11
C PROGRAMMING 2013-2014 UR
Int Integers (2 or 4 byte).
Single precision real (floating point) numbers. Usually 4 bytes and not typically
Float
used.
Double Double precision real (floating point) numbers. Usually 8 bytes and typically used.
Type Modifiers -
unsigned Doesn‟t use sign bit (assumes int if base type is omitted).
Long May have twice as many bytes as base type (assumes int if base type is omitted).
Short May have half as many bytes as base type (assumes int if base type is omitted).
Const Constant (values can‟t be changed during execution).
Note that short int and long int are also available, and may be represented by fewer or
more bits than int. unsigned int, short unsigned int and long unsigned int can be
used to hold zero-or-positive whole numbers.
Scanf();
example: scanf(“%d”,&age);
A statement to print the value of a variable or a string of characters (set of characters enclosed
by double quotes) to the screen begins with printf, followed by the (. The data to be printed are
between “ ”:
Printf(”string of characters”);
12
C PROGRAMMING 2013-2014 UR
1.6. LOCAL AND GLOBAL VARIABLES
A global variable exists only once in a program, and is visible in every function. Modifications
to it in one function are permanent and visible to all functions.
A local variable, however, has a limited scope: it exists only within the block that it is declared
in. Once that block ends, the variable is destroyed and its values lost.
Any variable declared within a block are strictly local to that block (and any enclosed block),
and they are created each time the block is executed and destroyed when the block is exited
(unless declared static).
e 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
13
C PROGRAMMING 2013-2014 UR
• For floating-point values, in addition to specifying the field width, the number of decimal places
can also be controlled. A sample format specifier would look like this
%7.3f
%6.4 s
Formatted input
• Modifications can be made to the control string of the scanf function which enable 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.
14
C PROGRAMMING 2013-2014 UR
Example:
#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);
As we have seen, a computer has its own language known as the machine language. Therefore,
after writing a program in C, we need to translate it in a language the computer can understand. A
program was created to that effect and supplied to you with C. This is what we call a compiler.
15
C PROGRAMMING 2013-2014 UR
The words (or verbs) "execute" and "run" will be used interchangeably to mean the same
thing. Running the program consists of obeying the statements in the body of the function
main.
In the past, a program used to be created from various parts all over the computer; some of the
techniques are still used to "debug" a program to isolate problems or "bugs". Since this is a small
program, we will just ask the computer to "execute" it and see the result.
The C language doesn't define how to create a project. When you buy or acquire a c compiler, its
documentation should tell you how to create and execute a project. We describe here how to
create a project in most familiar environments.
The programs we will be creating on this course are called console applications. They can also
be called Bash programs (especially on Unix/Linux).
Dev-C++ is a free programming environment. To get it, you can download it from
http://www.bloodshed.net. If you decide to use it, you should help the developers with a
financial contribution.
1. Start Dev-C++ 4
2.
16
C PROGRAMMING 2013-2014 UR
3. On the main menu, click File -> New Project...
4. On the New Project dialog box, click the Project property sheet if necessary.
Click Console Application
17
C PROGRAMMING 2013-2014 UR
5. On the subsequent New Project dialog box, type Exercise to change the name of the
project:
6. Click OK. You will be asked to create a location for the project.
#include <stdlib.h>
printf("hello world!");
system("PAUSE");
return 0;
13. To execute the program, on the main menu, click Execute -> Compile
15. After viewing the program, press Enter to close the DOS window to return to Dev-C++
19
C PROGRAMMING 2013-2014 UR
CHAPETER TWO: VARIABLES, OPERATORS AND EXPRESSIONS
2.1. VARIABLES
2.1.1 Definition
A variable is a named memory location in which data of a certain type can be stored. The
contents of a variable can change, thus the name. User defined variables must be declared
before they can be used in a program. It is during the declaration phase that the actual memory
for the variable is reserved. All variables in C must be declared before use.
• Get into the habit of declaring variables using lowercase characters.
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.
sum Sum
data_type var;
example: int sum; // declares a variable named sum having int as data type
Integer (int) variables are used to store integer values like 34, 68704 etc. To declare a variable of
type integer, type keyword int followed by the name of the variable. You can give any name to a
variable but there are certain constraints, they are specified in Identifiers section. For example,
the statement
int sum;
20
declares that sum is a variable of type int. You can assign a value to it now or later. In order to
assign values along with declaration use the assignment operator (=).
There are three types of integer variables in C, short, int and long int. All of them store values of
type integer but the size of values they can store increases from short to long int. This is because
of the size occupied by them in memory of the computer. The size which they can take is
dependent on type of computer and varies. More is the size, more the value they can hold. For
example, int variable has 2 or 4 bytes reserved in memory so it can hold 2 32= 65536 values.
Variables can be signed or unsigned depending they store only positive values or both positive
and negative values. And short, variable has 2 bytes. Long int variable has 4 bytes.
To store decimal values, you use float data type. Floating point data types comes in three sizes,
namely float, double and long double. The difference is in the length of value and amount of
precision which they can take and it increases from float to long double. For example, statement
declares a variable average which is of type float and has the initial value 2.34
A variable of type char stores one character. It size of a variable of type char is typically 1 byte.
The statement
declares a variable of type char (can hold characters) and has the initial values as character c.
Note that value has to be under single quotes.
21
2.1. 4.Constant
A constant is a variable whose value cannot be changed in the program.
Often in programming numerical constants are used, e.g. the value of . It is well worthwhile to
associate meaningful names with constants.
General form
Example:
#include <stdio.h>
#include <stdlib.h>
#define TAXRATE 0.10
22
balance = 72.10;
tax = balance * TAXRATE;
printf("The tax on %.2f is %.2f\n",balance, tax);
system("PAUSE");
return 0;
}
Output of the above program
Can include letters, underscore, or digits. Examples are: keyboard, Master, Junction,
Player1, total_grade, _Score_Side1 ;
23
is case sensitive and can be of any length but typically only the first 31 characters are
significant. Objects names are generally all lowercase. Class names generally start with
an upper case letter.
Note:
Represent storage units in a program
Used to store/retrieve data over life of program
Type of variable determines what can be placed in the storage unit
Assignment – process of placing a particular value in a variable
Variables must be declared before they are assigned
The value of a variable can change; A constant always has the same value
Name must begin with a letter; otherwise, can contain digits or any other characters. C is
CASE SENSITIVE! Use 31 or fewer characters to aid in portability
All variables must be declared in a C program before the first executable statement!
Examples:
main(){
int a, b, c;
float d;
/* Do something here */
}
2.2 EXPRESSION
An expression in C is some combination of constants, variables, operators and function calls.
Sample expressions are:
a + b;
3.0*x - 9.66553;
A statement in C is just an expression terminated with a semicolon.
24
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
This notation can be used with the arithmetic operators that are the same as the ones available in
most programming languages: addition (+), subtraction (-), division (/), multiplication (*) and
modulus (%, this produces the remainder from integer division). Integer division truncates the
result (it doesn't round). The modulus operator cannot be used with floating-point numbers.
Example: x= y+z+2.0;
Interpretation:
i) variable or object specifed by result is assigned the value of expression.
ii) The previous value of result is destroyed.
iii) The expression may be a single variable or abject or variables and constants using arithmetic
operations.
example: sum += x;
The expression is shown in brackets to indicate that the expression is evaluated first before
applying the operator op. The following examples illustrate the use of compound assignment
operators:
total += value; or total = total + value;
x /= y + 1; or x = x/(y + 1);
n %= 2; or n = n % 2;
Except for the case of the compound modulus operator %= the two operands may be any
arithmetic type. The compound modulus operator requires that both operands are integer types.
#include <stdio.h>
int main()
{
int length, width; // declaration of input variables
int perimeter, area; // declaration of output variables
printf( "Length = "); // prompt user
scanf(“ %d”,&length); // enter length
printf( "Width = "); // prompt user
scanf(“ %d”,&width); // input width
perimeter = 2*(length+width); // compute perimeter
26
area = length*width; // compute area
//output results
printf(“\nPerimeter is %d meters\n", perimeter);//output perimeter
printf(“\nArea is %d square meters\n,area");// output area
printf(”Thank you for your program ! \n”);
printf(”Enjoy this program! \n”);
return 0;
} // end of main program
The logical operators can be defined by truth tables as follows. Note that F is used for false and
T is used for true in these tables.
These tables show that NOT reverses the truth value of the operand, that the AND of two
operands is only true if both operands are true and that the OR of two operands is true if either or
both of its operands are true. Using these logical operators more complex conditions can now be
written.
There are some operations that occur so frequently in writing assignment statements that C has
shorthand methods for writing them.
One common situation is that of incrementing or decrementing an integer variable. For example:
n = n + 1;
n = n - 1;
The ++ and -- operators here have been written after the variable they apply to, in which case
they are called the postincrement and postdecrement operators. There are also identical
preincrement and predecrement operators which are written before the variable to which they
apply. Thus
28
++n; can be used instead of n = n + 1;
--n; can be used instead of n = n - 1;
Both the pre- and post- versions of these operators appear to be the same from the above, and in
fact it does not matter whether n++ or ++n is used if all that is required is to increment the
variable n. However both versions of the increment and decrement operators have a side effect
which means that they are not equivalent in all cases. These operators as well as incrementing or
decrementing the variable also return a value. Thus it is possible to write
i = n++;
What value does i take? Should it take the old value of n before it is incremented or the new
value after it is incremented? The rule is that a postincrement or postdecrement operator delivers
the old value of the variable before incrementing or decrementing the variable. A preincrement or
predecrement operator carries out the incrementation first and then delivers the new value. For
example if n has the value 5 then
i = n++;
would set i to the original value of n i.e. 5 and would then increment n to 6. Whereas
i = ++n;
would increment n to 6 and then set i to 6.
For the moment this notation will only be used as a shorthand method of incrementing or
decrementing a variable.
Note:
The unary increment and decrement operators are applied to integer variables to increase
or decrease the value by 1.
If the increment (or decrement) operator is placed after the variable, the operation takes
place after the value has been returned.
If the increment (or decrement) operator is placed before the variable, the operation takes
place before the value is returned.
29
2.10. PRECEDENCE & ASSOCIATIVITY OF OPERATORS
• The precedence of operators determines the order in which operations are
performed in an expression. Operators with higher precedence are employed
first. If two operators in an expression have the same precedence, associativity
determines the direction in which the expression will be evaluated.
• C has a built-in operator hierarchy to determine the precedence of operators.
Operators higher up in the following diagram have higher precedence. The
associativity is also shown.
- ++ -- R to L
* / % L to R
+ - L to R
= R to L
This is how the following expression is evaluated
1+2*3-4
1+6-4
7-4
3
NB:
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.
2.11TYPE CASTING
• Programmers can override automatic type conversion and explicitly cast
variables to be of a certain type when used in an expression. For example,
(double) i
• will force i to be of type double. The general syntax is (type) expression
• Some examples,
(char) 3 + 'A'
x = (float) 77;
(double) k * 57
30
Exercises
#include <stdio.h>
using namespace std;
int main ( )
{
int i,j,k;
i = 10;
k = i++;
j = i+k;
i= ++j;
printf(“%d,%d,%d\n”, i, j , k);
return 0;
} The output is:
a. 10,21,10
b. 11,20,10
c. 21,21,10
d. 20,21,11
5. Given the following int a,b,c,d,e;
a=8,b=3,c=4,d=9;
e=a % b * c + a / b – c or abc*%83/+9-
The value of e is
1. -3
2. 1
3. -4
4. None
31
CHAPTER THREE: CONTROL STATEMENTS
Control statements determine the order in which nested statements are executed. They consist of
selection statements and repetition statements. Where more than one statement is required in a
control structure, a block should be used.
3.1.1. IF statement
The if-else statement can exist in two forms: with or without the else. The two forms are:
The "expression" evaluates to true or false. The "statement" means either a simple statement
terminated by a semicolon or compound statement, which is a group of simple statements
enclosed in braces { }. Note this statement can also be another if, so they can
be strung together.
Note:Pascal programmers should notice that the "then" is implied in C and C++, which are terse
languages. "Then" isn't essential, so it was left out.
Example 1.
#include <stdio.h>
int main() {
int i;
32
printf( "type a positive integer less than 10\n") ;
scanf(“%d”,& i);
if(i > 5)
printf( "the number was greater than 5 \n") ;
else if(i < 5)
printf("the number was less than 5\n ");
else
printf("the number must be equal to 5 \n");
return 0;
}
Example 2. Write a program that will tell you if a number was odd or even. You could use
modulus to quickly tell you by asking for the remainder of the number when divided by two.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int num;
printf(" Enter a number \n");
scanf("%d",& num);
// num % 2 computes the remainder when num is divided by 2
if ( num % 2 == 0 )
{
printf("%d is even",num);
}
else
{
printf("%d is odd",num);
}
system("PAUSE");
return 0;
}
33
3.1.2. SWITCH statement
The switch statement is a very clean way to implement multi-way selection (i.e., selecting
from among a number of different execution paths), but it requires a selector that evaluates to
an integral value at compile-time. If you want to use, for example, a string as a selector, it
will not work in a switch statement. For a string selector, you must use instead a series of if
statements and compare the string inside the conditional.
Its general form is as follows:
Note:
A selector is an expression that produces an integral value (choice). The switch compares the result
of selector to each choice. Switch statement selects the next statement to be executed from many
possible statements. If it finds a match, the corresponding statement (simple or compound executes. If
no match occurs, the default statement executes.
The selection is made depending on the value of a selector variable which can only be an integer or a
character.
34
The default label is optional but if it is not included then a selector which does not match any of
the case labels causes the whole switch statement to be ignored.
You will notice in the above definition that each case ends with a break, which causes
execution to jump to the end of the switch body. This is the conventional way to build a
switch statement, but the break is optional. If it is missing, the code for the following case
statements execute until a break is encountered. Although you don't usually want this kind of
behavior, it can be useful to an experienced C programmer.
35
quit = 1; /*Notice that selecting 'q' sets the quit flag to 1. The next time the selector is
evaluated, quit == 0 returns false so the body of the while does not execute.*/
break;
default :
printf( "Please use a,b,c or q!\n");
}// end of switch
}//end of while
return 0;
}// end main
Note:
• The switch statement works as follows
1) Integer control expression is evaluated.
2) A match is looked for between this expression value and the case constants. If a match is
found, execute the statements for that case. If a match is not found, execute the default statement.
3) Terminate switch when a break statement is encountered or by “falling out
the end”.
• 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
36
3.2.1. WHILE statement
The while statement examines or evaluates a condition. The syntax of the while statement
is:
while(Condition)
Statements;
Increment or decrement;
#include <stdio.h>
void main()
{
int i; // declaration of variable
i = 1;// initialization of the first integer=1
while (i <= 10)// testing the condition
{
printf(”%d”, i);
printf(” ”);
i++; // update
}
}
Its functionality is exactly the same as the while loop, except that condition in the do-while loop
37
is evaluated after the execution of statement instead of before, granting at least one execution of
statement even if condition is never fulfilled.
Example 1
#include <stdio.h>
int main()
{
int Number = 0;//initializing the number
do
{
Printf("Number %d\n",Number);
Number++;
}while( Number <= 12 ); //end of do-while
return 0;
}
Example 2
1. Sum of Arithmetic Progression
The following program produces the sum 1+2+3+ ...+n, where a value for n is entered by the
user:
// Example program
// When user enter n (>0) the sum of the first n natural numbers is output.
#include <stdio.h>
void main()
{
int i,n;// i: conter, n number entered by the user
int sum;
printf( "Enter a value for n: ");
scanf(“%d”,& n);
sum = 0;//initializing the sum
i = 1;//initializing the counter
do
{
sum += i;
i++;// stepping
}
38
while (i <= n);//end of do-while
printf("The sum of the first %d natural numbers is %d\n",n,sum);
}
3.2.3. FOR
for(initializing expressions)
{
statements; // what the loop will do
}
39
3.3. Jump statements.
#include <stdio.h>
int main ()
{
int n;
for (n=10; n>0; n--)
{
printf(“%d”, n); 10, 9, 8, 7, 6, 5, 4, 3, countdown
if (n==3) aborted!
{
printf( "countdown
aborted!");
break;
}
}
return 0;
}
int main ()
40
{
for (int n=10; n>0; n--) {
if (n==5) continue;
printf(“%d,”, n);
}
Printf( "FIRE!\n");
return 0;}
Example:
#include <stdio.h>
int main()
{
for(int Count = 0; Count <= 12; ++Count)
{
Printf( "Count %d\n ", Count);
if( Count == 5 )
goto Copine;
}
Copine:
Printf( “This is a student of BacI\n");
return 0;}
41
EXERCISES
42
CHAPTER FOUR: FUNCTIONS
4.1. Definition
A function in C is a small “sub-program” that performs a particular task, and supports the
concept of modular programming design techniques. In modular programming the various
tasks that your overall program must accomplish are assigned to individual functions and the
main program basically calls these functions in a certain order.
The functions are used for the following reasons:
– Don‟t have to repeat the same block of code many times in your code. Make that code block a
function and call 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 well then move on to the others.
– Easy to modify and expand. Just add more functions to extend program capability
– For a large programming project, you will code only a small fraction of the program.
– Make program self-documenting and readable.
You need to have the #include <math.h> directive at the top of your program to use these. All
parameters and return values are of type double. math.h also defines some constants which may
be used. For example M_PI can be used for and M_E can be used for .
Function Description
acos(x) inverse cosine, -1 <= x <= +1, returns value in radians in range 0 to PI
asin(x) inverse sine, -1 <= x <= +1, returns value in radians in range –PI/2 to PI/2
43
cos(x) trigonometric cosine of x ( x in radians)
44
4.3.1. Function prototype
The general format for a prototype is simple:
Return-type function_name(arg_type arg1,………..arg_type argN);
arg_type just means the type for each argument -- for instance, an int, a float, or a char. It's
exactly the same thing as what you would put if you were declaring a variable.
There can be more than one argument passed to a function or none at all (where the parentheses
are empty), and it does not have to return a value. Functions that do not return values have a
return type of void. Lets look at a function prototype:
int mult ( int x, int y );
This prototype specifies that the function mult will accept two arguments, both integers, and that
it will return an integer. Do not forget the trailing semi-colon. Without it, the compiler will
probably think that you are trying to write the actual definition of the function.
Type main()
{
Declarations;
Function call;
}
45
If the function returns a value then the type of that value must be specified in function-type. For
the moment this could be int, float or char. If the function does not return a value then the
function-type must be void.
46
4.3.4. return statement
Unless the function type is void , a function must return a single result of the indicated type. This
is accomplished through the use of C return statement.
General form:
return (expression);
e.g. return (k*k); return (x+y);
Note: When a return statement executes, the expression following return is evaluated and its
value is communicates back to the calling function as the function result.
4.3.5. Examples
#include<stdio.h>
//Function prototype
int square_int(int); // type of function and type of the integer to be squared
//Main program: use of the function square_int to compute area of a square
int main()
{
//local data
int side;//input: side length of a square
int area;// output: area of square
area=square_int(side);//function call to compute area of square
return 0;
}// end of main function
//Function definition
int square_int( int k)
{
return (k*k);//function return
}// end of function definition
47
3.Functions with no parameters
Functions with no parameters are of limited use. Usually they will not return a value but carry out
some operation. For example consider the following function which skips three lines on output.
4.3.6. Recursion
Recursion is a programming technique that allows the programmer to express operations in terms
of themselves. In C, this takes the form of a function that calls itself. A useful way to think of
recursive functions is to imagine them as a process being performed where one of the instructions
is to "repeat the process". This makes it sound very similar to a loop because it repeats the same
code, and in some ways it is similar to looping. On the other hand, recursion makes it easier to
express ideas in which the result of the recursive call is necessary to complete the task.
1. A simple base case which we have a solution for and a return value. Sometimes there are
more than one base cases.
2. A way of getting our problem closer to the base case. I.e. a way to chop out part of the
problem to get a somewhat simpler problem.
3. A recursive call which passes the simpler problem back into the function.
48
{
return (integer * (myFactorial(integer-1)));
}
}
EXERCISES
1. Consider the following code
#include <stdio.h>
float average(int list[], int length)
{
float total = 0;
int count;
for (count = 0 ; count < length ; count++)
total += float(list[count]);
return (total / length);
}
int main (){
int numbers[] ={2,4,6,8,10};
int size = 5;
printf(”The percentage is :%f\n “,average(numbers,size)*10);
return 0;}
The output is:
i. The percentage is 6
ii. The percentage is 66
iii. The percentage is 60
iv. None
2. write a c program to compute log(x) where x is entered from the keyboard
3. Using for/while/do ..while, write a c function that prompts the user to type two integers
and displays the following
Enter a:4
Enter b:3
Result:64
4. Using recursion, write a c function to sum all positive integers less than n
49
CHAPTER FIVE: ARRAYS FUNDAMENTALS
5.1. DEFINITION
An array is a series of elements of the same type placed in contiguous memory locations that can
be individually referenced by adding an index to a unique identifier.
Arrays come in two flavors: one dimensional and multi-dimensional arrays.
Note: The index must be an integer and indicates the position of the element in the array. Thus
the elements of an array are ordered by the index.
Here are examples of declaring arrays:
i. int Age[12]; //declares a group or array of 12 values, each one being an integer.
ii. float Grade[100]; // declares an array of 100 floating-point values.
iii. double Angle[360]; /*declares an array of double-precision numbers. There are 360 of these
items in the group.*/
iv. int A[4][6];/* declares an array of integer numbers. 4 rows and 6 columns. Each row has 6
elements. Therefore, the array is comprised of 24 elements. */
Just like any variable can be initialized, an array also can be initialized. you can start with the
data type to specify the kind of array you are declaring. This is followed by the array name, and
the square brackets. After specifying the dimension or not, and after the closing square bracket,
type the assignment operator (=). The elements, also called items, that compose the array are
50
included between an opening curly bracket '{' and a closing curly bracket '}'. Each item is
separate from the next by a comma operator. As a normal C/C++ initialization, you end it with
a semi-colon.
Examples:
double distance[5] = {44.14, 720.52, 96.08, 468.78, 6.28};
int number[12]= {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12};
int primes[10] = {1, 2, 3, 5, 7}; /*would reserve space for a ten element array but would only
initialise the first five elements.*/
int primes[] = {1, 2, 3, 5, 7, 11, 13};/* initialising an array to hold the first few prime numbers*/
double distance[2][4] = { 44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12 }; /*
A 2-dimensional array having 2*4=8 elements */
C/C++ also allows you to include each row in its own pair of curly brackets. You must separate
each row from the next with a comma. Once again, this makes code easier to read. For example,
double distance[2][4] = { { 44.14, 720.52, 96.08, 468.78 },{ 6.28, 68.04, 364.55, 6234.12 }};
Note: After initializing an array, its elements are counted from left to right. Each element of the
array, also called a member of the array, has a specific and constant position. The position
of an item is also called its index. The first member of the array, the most left, has an index
of 0. The second member of the array has an index of 1. Since each array has a number of
items which can be specified as n, the last member of the array has an index of n-1.
Based on this system of indexing, to locate a member of an array, use its index in the group.
Imagine you declare and initialize an array as follows:
To locate the value of the 3rd member of the array, you would type distance[2]. In the
same way, the 1st member of the array can be located with distance[0].
51
Once you can locate a member of the array, you can display its value using cout. Here is
an example:
#include <stdio.h>
int main()
{
double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};
return 0;
}
52
// displaying results
Printf("\nThe matrix is :\n\n ");
i=0;
while(i<4)// loop for rows
{
for(int j=0;j<4;j++) // loop for columns
{
Printf(“%d”,A[i][j]); // sets width of 8 characters before and after each column
}// end loop for columns
i++ ;
printf("\n\n"); // skip 2 lines to begin the next row
}//end loop for rows
return 0;//succesful of program
}//end main program
12 13 14 14
15 12 16 17
18 19 10 20
30 34 35 26
Examples:
i. char name[12]; //The variable name should have at most 12 characters
ii. char studentname[20][30]; // 20 student names, each name having at most 30 characters.
Here is an example:
54
i). To initialize an array of characters, you use the curly brackets. Each character must be
enclosed in single-quotes. If you know the characters you will be using to initialize the array, you
should omit specifying the dimension. Here is an example:
#include <stdio.h>
int main()
{
char L1 = 'J', L2 = 'a', L3 = 'm', L4 = 'e', L5 = 's';
printf( "The name is %c%c%c%c%c ", L1, L2, L3, L4, L5);
return 0;
As done with other arrays, each member of this array of characters can be accessed using its
index. Here is an example:
#include <stdio.h>
int main()
{
char Name[6] = { 'J', 'a', 'm', 'e', 's' };// initializing characters
printf("The name is %c%c%c%c%c ", Name[0] , Name[1], Name[2], Name[3], Name[4]);
return 0;
}
55
ii). Another technique used to initialize an array of characters is to type the group of
characters between double-quotes. Since you know the array, let the compiler figure out
its dimension. Here is an example:
char arrayname[]=”string”;
Any of these two techniques would allow you to display the string using the cout operator.
Instead of initializing an array, sometimes you will have to wait until the program is running,
to assign a value to the array. First, you must declare the array, specifying an approximate
dimension. To request the value of an array of characters, use the cin operator, specifying
only the name of the array. Here is an example:
#include <stdio.h>
#include <stdlib.h>
char FirstName[20];
char LastName[20];
printf( "The following pieces of information are needed to complete your application\n");
scanf("%s",&FirstName);
56
scanf("%s",&LastName);
system("PAUSE");
return 0;
Member Information
Full Name: Michael Callhoun
Each member of an array is a pseudo-variable and can be processed as such. This means that you
can add the values of two members of the array(Number[2]+Number[0]), you can subtract the
value of one of the members from another member(member[1]-Number[4]). In the same way,
you can perform multiplication, division, or remainder operations on members of an array.
Example1: One of the regular operations performed on an array consists of adding the values of
the members to produce a sum. Here is an example:
#include <stdio.h>
int main()
{
// We know that we need a constant number of elements
const int max = 10;
58
int number[max];
return 0;
}
Example2: Another type of operation regularly performed on an array consists of looking for
a value held by one of its members. For example, you can try to know if one of the members
holds a particular value you are looking for. Here is an example:
#include <stdio.h>
59
int main()
{
// Declare the members of the array
int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int find; // find is the number to search
int i, m = 8;
//executable statements
Printf( "Enter a number to search: ");
Scanf(“d”,& find);
for (i = 0; (i < m) && (Numbers[i] != Find); ++i)
continue;
Example3: One of the most regular operations performed consists of comparing the values
of different members to get the lowest value of the members. Here is an example:
60
minimum = numbers[i];
}
return 0;
}
5.7. STRINGS
P a c i f i q u e \0
The last character \0 is called the null-terminating character. For this reason, a string is
said to be null-terminated. The string library ships with a lot of functions used to perform
almost any type of operation on almost any kind of string. Used under different
circumstances, the string functions also have different syntaxes.
The strings that you can use in your program may be defined in various libraries depending
on your compiler but most of the time, they are available once you include the string library
that is defined in the std namespace.
#include<string.h>
When requesting its value from the user, by default, the string identifier is used to get only a
one-word variable. Here is an example program that requests a first and last names:
61
#include <stdio.h>
#include <string.h> //to open the string library
int main()
{
string FirstName, LastName; // declaration of strings
printf( "Enter first name: ");
scanf(“%s”,&FirstName);
printf("Enter last name: ");
scanf(“%s”,& LastName);
// Printing the results
Printf("\n\nFull Name: %s %s\n\n ", FirstName, LastName);
return 0;
}
• Included in the string.h 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
63
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
Example:
#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);
}
Output
65
66
CHAPTER SIX: POINTERS AND STRUCTURES
67
*p = ‟X‟; // ch now holds ‟X‟
printf(“%s”,ch); // outputs the character ‟X‟
It is useful to have a pointer value that points to nothing, that is, a null pointer.
By convention, such a pointer is assigned the value zero.
Example
int x = 1, y = 2, z[10];
int *ip; /* ip is a pointer to int */
ip = &x; /* ip now points to x */
y = *ip; /* y is now 1 */
*ip = 0; /* x is now 0 */
ip = &z[0]; /* ip now points to z[0] */
70
And then we could print out our array either using the array notation or by dereferencing
our pointer. The following code illustrates this:
Compile and run the above program and carefully note lines A and B and that the
program prints out the same values in either case. Also observe how we dereferenced our
pointer in line B, i.e. we first added i to it and then dereferenced the new pointer. Change
line B to read:
printf("ptr + %d = %d\n",i, *ptr++);
and run it again... then change it to:
printf("ptr + %d = %d\n",i, *(++ptr));
and try once more. Each time try and predict the outcome and carefully look at the actual
outcome.
In C, the standard states that wherever we might use &var_name[0] we can replace that
with var_name, thus in our code where we wrote:
ptr = &my_array[0];
to achieve the same result.
This leads many texts to state that the name of an array is a pointer.
For example, while we can write
ptr = my_array;
we cannot write
my_array = ptr;
The reason is that while ptr is a variable, my_array is a constant. That is, the location at
which the first element of my_array will be stored cannot be changed once my_array[]
has been declared.
Example:
Declare an array b[ 5 ] and a pointer bPtr
To set them equal to one another use:
bPtr = b;
The array name (b) is actually the address of first element of the array b[ 5 ]
bPtr = &b[ 0 ]
71
Explicitly assigns bPtr to address of first element of b
– Element b[ 3 ]
• Can be accessed by *( bPtr + 3 )
– Where n is the offset. Called pointer/offset notation
• Can be accessed by bptr[ 3 ]
– Called pointer/subscript notation
– bPtr[ 3 ] same as b[ 3 ]
• Can be accessed by performing pointer arithmetic on the array itself
*( b + 3 )
6.8. Structures
A structure is a variable in which different types of data can be stored together in one variable
name. Consider the data a teacher might need for a high school student: Name, Class, GPA, test
scores, final score, ad final course grade. A structure data type called student can hold all this
information:
struct student {
char name[45];
char class;
float gpa;
int test[3];
int final;
char grade;
};
The above is a declaration of a data type called student. It is not a variable declaration, but a
type declaration.
To actually declare a structure variable, the standard syntax is used:
struct student Lisa, Bart, Homer;
You can declare a structure type and variables simultaneously. Consider the
following structure representing playing cards.
struct playing_card {
int pips;
char *suit;
} card1,card2,card3;
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.pips=2;
card1.suit="Hearts";
• Once you know how to create the name of a member variable, it can be treated
72
the same as any other variable of that type. For example the following code:
card2.pips=card1.pips+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 pips 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.
// example about structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct movies_t {
string title;
int year;
} mine, yours;
void printmovie (movies_t movie);
int main ()
{
string mystr;
mine.title = "2001 A Space Odyssey";
mine.year = 1968;
cout << "Enter title: ";
getline (cin,yours.title);
cout << "Enter year: ";
getline (cin,mystr);
stringstream(mystr) >> yours.year;
cout << "My favorite movie is:\n ";
printmovie (mine);
cout << "And yours is:\n ";
printmovie (yours);
return 0;
}
void printmovie (movies_t movie)
{
cout << movie.title;
cout << " (" << movie.year << ")\n";
}
73
6.9. Pointers and Structures
As you may know, we can declare the form of a block of data containing different data
types by means of a structure declaration. For example, a personnel file might contain
structures which look something like:
struct tag {
char lname[20]; /* last name */
char fname[20]; /* first name */
int age; /* age */
float rate; /* e.g. 12.75 per hour */
};
Example:
#include <stdio.h>
#include <string.h>
struct tag{ /* the structure type */
char lname[20]; /* last name */
char fname[20]; /* first name */
int age; /* age */
float rate; /* e.g. 12.75 per hour */
};
struct tag my_struct; /* define the structure */
void show_name(struct tag *p); /* function prototype */
int main(void)
{
struct tag *st_ptr; /* a pointer to a structure */
st_ptr = &my_struct; /* point the pointer to my_struct */
strcpy(my_struct.lname,"Jensen");
strcpy(my_struct.fname,"Ted");
printf("\n%s ",my_struct.fname);
printf("%s\n",my_struct.lname);
my_struct.age = 63;
show_name(st_ptr); /* pass the pointer */
return 0;
}
void show_name(struct tag *p)
{
printf("\n%s ", p->fname); /* p points to a structure */
printf("%s ", p->lname);
printf("%d\n", p->age);
}
74
CHAPTER VII. FILE INPUT AND OUTPUT
7.1.INTRODUCTION
So far, all the output (formatted or not) in this course has been written out to
what is called standard output (which is usually the monitor). Similarly all
input has come from standard input (usually associated with the keyboard).
The C programmer can also read data directly from files and write directly to
files. To work with files, the following steps must be taken:
1 Declare variables to be of type FILE.
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.
4 Break the connection between the internal FILE variable and actual disk
file. This disassociation is done with the fclose() function.
75
• will input -- from the file myfile.dat -- real and integer values into the variables x and m
respectively.
• 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.
• The syntax for file closing is simply fclose(in_file);
• 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
• 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:
if (feof(in_file))
printf ("No more data \n");
Example
#include <stdio.h>
#include <ctype.h>
#include <string.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();
}
76
void processfile(void) {
struct goods record;
while (!feof(input_file)) {
getrecord(&record);
if (record.quantity <= record.reorder)
printrecord(record);
}
}
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;
}
void printrecord (struct goods record) {
printf("\nProduct name \t%s\n",record.name);
printf("Product price \t%f\n",record.price);
printf("Product quantity
\t%d\n",record.quantity);
printf("Product reorder level
\t%d\n",record.reorder);
}
77
REFERENCES
1. http://www.cplusplus.com/doc/tutorial
2. FRANK L.F et al. (2000). Problem solving, Abstraction, and Design Using C++, Addison
Wesley Longman, Inc, USA.
3. IAN A. and PETER K.(1997). Introduction to C++ Programming I, [online]
http://www.cee.hw.ac.uk/~pjbk/pathways/cpp1/cpp1.html, October, 2006
7. http://www.fredosaurus.com/notes-cpp/
8. http://www.coronadoenterprises.com/tutorials/c/chap02.htm
78