Sei sulla pagina 1di 14

MODULE 1

OVERVIEW OF C PROGRAMMING LANGUAGE


INTRODUCTION
C is a general-purpose programming language, developed by Dennis Ritchie
of Bell Laboratories, and is used for writing programs in many different
domains, such as operating systems, numerical computing, graphical
applications, etc. Although it was originally intended to run under UNIX,
there was a great interest in running it on the IBM PC and other systems.
FIRST C PROGRAM
#include <stdio.h>
#include <conio.h>
main()
{
/* My first C program */
printf("Hello World! \n");
getch();
}
C is case sensitive. All commands in C must be lowercase.
C has a free-form line structure. End of each statement must be
marked with a semicolon. Multiple statements can be on the same line.
White space is ignored. Statements can continue over many lines.
The C program starting point is identified by the word main(). This
informs the computer as to where the program actually starts. The
parentheses that follow the keyword main indicate that there are no
arguments supplied to this program.
The two braces, { and }, signify the begin and end segments of the
program. In general, braces are used throughout C to enclose a block
of statements to be treated as a unit. COMMON ERROR: unbalanced
number of open and close curly brackets!!!
The purpose of the statement #include <stdio.h> is to allow the use
of the printf() statement to provide program output. For each
function built into the language, an associated header file must be
included.
The purpose of the statement #include <conio.h> is to allow the use
of getch() to hold the screen.
printf() is actually a function in C that is used for printing
variables and text. Where text appears in double quotes "", it is
printed without modification. There are some exceptions however. This
has to do with the \ and % characters. These characters are
1
modifiers, and for the present the \ followed by the n character
represents a newline character. Thus the program prints
Hello World!
And the cursor is set to the beginning of the next line.
/* My first C program */
Comments can be inserted into C programs by bracketing text with the
/* and */ delimiters. Comments are useful for a variety of reasons.
Primarily, they serve as internal documentation for program structure
and functionality.
getch() is a function in C that holds the screen during execution and
it is terminated by pressing any key.

2
MODULE 2
FUNDAMENTAL DATA TYPES
THE NUMERIC TYPES
From the point of view of computer programmers, there are two main types
of numbers. The classification of numbers into these two categories is
based on whether they can have only integer values or also fractional part
in addition to the integer part. For example, the number 123 has only
integer portion. However, the number 12.35 has an integer portion (i.e.
12) and also fractional portion (i.e. 35) after decimal point.
Numbers that cannot have any fractional part are called an integer while
numbers that can have fractional part are called floating point numbers.
Integers are used for counting discrete values. For example, we say that,
there are 5 balls in a bag or 10 biscuits in a pack. But we never say
that, there are 2.8 balls or 5.9 biscuits.
On the other hand, floating point numbers are used approximately to
measure something. For example, we say that, the height of a person is 5.7
feet or the weight of some metal is 5.20 kilograms.
int is used in declaring an integer while float is used in declaring a
floating-point number.
THE CHARACTER TYPE
This type is used to represent single character and the keyword used in
declaring a character is char. For example:
char letter;
DECLARING VARIABLES
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
The declaration of variables is done after the opening brace of main().
main() {
int sum;
The basic format for declaring variables is
datatype var1, var2, , var n;

3
e.g. int i,j,k;
float length,height;
char letter;
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;
j=j+3;
letter=T;
Note that when assigning a character value the character should be
enclosed in single quotes.
Also, a variable can be declared and assigned a value at one time. This is
termed Variable Initialization. For example:
int x=12;
Example.
int x;
float y, z;
x=6;
y=10.3;
z=x*y;
printf("the value of our multiplication = %f\n,z);

`
4
MODULE 3
I/O STATEMENTS
BASIC OUTPUT
The basic output command for C is printf() function. The general form of
printf() is
printf(control string,argument lists);
N.B:- The number of arguments must match the number of identifiers
Lets take a look at our printf() statement in a previous example:
printf("the value of our multiplication = %f\n,z);
The first argument of the printf function is called the control string.
When the printf is executed, it starts printing the text in the control
string until it encounters a % character. The % sign is a special
character in C and marks the beginning of a format specifier. A format
specifier controls how the value of a variable will be displayed on the
screen. When a format specifier is found, printf looks up the next
argument (in this case z), displays its value and continues. The f
character that follows the % indicates that a floating-point number will
be displayed. At the end of the control statement, printf reads the
special character \n which indicates print the new line character.
FORMAT SPECIFIERS
The table below shows what format specifiers should be used with what data
types:
SPECIFIER DATATYPE
%d integer
%f floating-point
%c character
%s character string

COMMON SPECIAL CHARACTERS FOR CURSOR CONTROL


We will be looking at \n and \t. \n is called newline and it is used to
take the cursor to the next line while \t is called tab and is used to
give a long space between two arguments.
Lets take a look at the printf() example again and rewrite it:
printf("the multiplication of %d\t and \t%f = %f\n,x,y,z);
BASIC INPUT
scanf() is a function in C which allows the programmer to accept input
from a keyboard. The following program illustrates the use of this
function.

5
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 called the address operator.

6
MODULE 4
OPERATORS
ASSIGNMENT OPERATOR(=)
The assignment operator assigns a value to a variable.
a = 5;
This statement assigns the integer value 5 to the variable a.
ARITHMETIC OPERATORS (+, -, *, /,%)
The five arithmetical operations supported by the C language are:
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Operations of addition, subtraction, multiplication and division literally
correspond with their respective mathematical operators. The Modulus (%)
produces the remainder of division of two numbers. For example:
8 % 3= 2
COMPOUND ASSIGNMENT OPERATORS(+=, -=, *=, /=)
When we want to modify the value of a variable by performing an operation
on the value currently stored in that variable we can use compound
assignment operators.
Expression is equivalent to
value += increase value = value + increase;
a -= 5 a = a - 5
a /= b a = a / b
price *= units + 1 price = price * (units + 1);
INCREMENT AND DECREMENT OPERATORS(++, --)
Shortening even more some expressions, the increment operator (++) and the
decrement operator (--) increase or reduce the value stored in a variable
by one. They are equivalent to +=1 and to -=1, respectively. Thus:
c++;
c+=1;
c=c+1;
are all equivalent in its functionality: the three of them increase the
value of c by 1.
RELATIONAL AND EQUALITY OPERATORS (==, !=, >, <, >=, <= )
In order to evaluate a comparison between two expressions we can use the
relational and equality operators. The result of a relational operation is
a Boolean value that can only be true or false, according to its Boolean
result.
7
We may want to compare two expressions, for example, to know if they are
equal or if one is greater than the other. Here is a list of the
relational and equality operators that can be used in C:
==Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Here are some examples:
(7 == 5) /* evaluates to false. */
(5 > 4) /* evaluates to true. */
(3 != 2) /* evaluates to true. */
(6 >= 6) /* evaluates to true. */
(5 < 5) /* evaluates to false. */
Be careful! The operator = (one equal sign) is not the same as the
operator == (two equal signs), the first one is an assignment operator
(assigns the value at its right to the variable at its left) and the other
one (==) is the equality operator that compares whether both expressions
in the two sides of it are equal to each other.
LOGICAL OPERATORS (&&, ||)
The operator && corresponds with Boolean logical operation AND. This
operation results true if both of its two operands is true, thus being
false only when either operands are false themselves. Here are the
possible results of a && b:
a b a && b
true true True
true false False
false true False
false false False
The operator || corresponds with Boolean logical operation OR. This
operation results true if either one of its two operands is true, thus
being false only when both operands are false themselves. Here are the
possible results of a || b:
a b a || b
true true True
true false True
false true True
false false False

8
MODULE 5
SELECTION STATEMENT
In this module, we will be looking at if statement and if-else statement.
if STATEMENT
The if statement allows decision making depending upon a condition.
Program code is executed or skipped. The basic syntax is
if (control expression)
program statement;
If the control expression is TRUE, the body of the if is executed. If it
is FALSE, the body of the if is skipped.
N.B:- There is no termination (;) at the end of an if statement.
Example:
if (score>=40)
printf("\nYou passed CSC216 and Your score is %d",score);
if-else STATEMENT
It is used to decide between two or more 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.
Example
if (score>=40)
printf("\nYou passed CSC216 and Your score is %d",score);
else
printf("\nYou failed CSC216 and Your score is %d",score);

The if-else statement can be extended using the if-else-if ladder. Its
syntax is as follows:
if (expression)
statement1;
else if (expression)
statement2;
else if (expression)
statement3;
.
.
.
9
else
statement n;
If the expression is TRUE, it executes statement1, else, it moves to the
next else-if expression and execute statement2 if it is TRUE, and so on.
If all the statements FAIL, it executes the last statement that has only
else. Below is an example:
if (score>=70 && score<=100)
printf("\nYour grade is A and score is %d, score);
else if (score>=60 && score<=100)
printf("\nYour grade is B and score is %d, score);
else if (score>=50 && score<=100)
printf("\nYour grade is C and score is %d, score);
else if (score>=45 && score<=100)
printf("\nYour grade is D and score is %d, score);
else if (score>=40 && score<=100)
printf("\nYour grade is E and score is %d, score);
else if (score<=39 && score>=0)
printf("\nYour grade is F and score is %d, score);
else
printf("\n%d is an invalid score,score);
N.B:- 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.

10
MODULE 6
ITERATION (LOOPING)
Program looping is often desirable in coding in any language to have the
ability to repeat a block of statements a number of times. We will be
looking at for loop and its syntax is as follows:
for (initialization expr; control expr; count expr)
program statement;
Example 1:
for (int ctr=1; ctr<=10; ctr++)
printf("%d\n,ctr);
Example 2:
printf(Even numbers below 21\n);
for (int num=2; num<=20; num+=2)
printf(%d\t,num);

- Control expressions are separated by ; not ,


- If there are multiple C statements that make up the loop body,
enclose them in curly brackets {}
- The line of the for statement does not end with a ;

11
MODULE 7
ARRAYS AND STRINGS
ARRAYS
Arrays are a data structure which holds multiple values of the same data
type. Arrays are an example of a structured variable in which there are a
number of pieces of data contained in the variable name and 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. His first approach might be to create a
specific variable for each user. This might look like
int id1 = 175; int id2 = 232; int id3 = 601;
It becomes increasingly more difficult to keep track of the IDs as the
number of variables increase. Arrays offer a solution to this problem.
It uses an indexing system to find each variable stored within it. In C,
indexing starts at zero.
The replacement of the previous example using an array looks like this:
int id[3]; /* declaration of array id */
id[0] = 175;
id[1] = 232;
id[2] = 601;
OR
Static int id[3]={175,232,601};
To print a value from this array, we use
Printf(your ID= %d,id[0]);
STRINGS
A string is a collection of characters
Char username[10]=csc dept;
Char password[]=#computer1;
Printf(your username is %s and password is %s,username,password);
You can also collect strings using keyboard input.
Char username[10];
Char password[];
Printf(please enter your username);
Scanf(%s,username);
Printf(please enter your password);
Scanf(%s,password);
Printf(your username is %s and password is %s,username,password);
N.B:- Unlike numbers, the address operator & is not used when entering
strings

12
MODULE 8
CLASSES
MATH LIBRARY CLASS (math.h)
For one to use the math library class, the math.h header file must be
imported.
#include <math.h>
Below is an example:
#include <conio.h>
#include <stdio.h>
#include <math.h>
int main(){
int a=3,b=9,c;
float d;
c= pow(a,2);
d= sqrt(b);
printf(the square of %d is %f,a,c);
printf(the square root of %d is %f,b,d);
getch();}

USER DEFINED CLASS


In order to use functions, the programmer must do three things
Define the function
Declare the function
Use the function in the main code
Its syntax is as follows:
return_type function_name (data type variable name list)
{
local declarations ;
function statements ;
}
where the return_type in the function header tells the type of the value
returned by the function (default is int)
where the data type variable name list tells what arguments the
function needs when it is called (and what their types are)
where local declarations in the function body are local constants and
variables the function needs for its calculations.
Below is an example:

13
#include <conio.h>
#include <stdio.h>
float area(float a,float b)
{
return a*b;
}
int main()
{
float c= area(3.1,9.3);
printf("%f",c);
getch();
}

14

Potrebbero piacerti anche