LESSON 3 -C

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

Example of Decision tree

Advantages

 Are simple to understand and interpret. People are able to understand decision tree models after
a brief explanation.
 Have value even with little hard data. Important insights can be generated based on experts
describing a situation (its alternatives, probabilities, and costs) and their preferences for
outcomes.
 Help determine worst, best and expected values for different scenarios.
 Use a white box model. If a given result is provided by a model.
 Can be combined with other decision techniques.
Disadvantages of decision trees:

 They are unstable, meaning that a small change in the data can lead to a large change in the
structure of the optimal decision tree.
 They are often relatively inaccurate. Many other predictors perform better with similar data.
This can be remedied by replacing a single decision tree with a random forest of decision trees,
but a random forest is not as easy to interpret as a single decision tree.
 For data including categorical variables with different number of levels, information gain in
decision trees is biased in favor of those attributes with more levels.
 Calculations can get very complex, particularly if many values are uncertain and/or if many
outcomes are linked.

5.0 Introduction to structured programming using c language

5.1 C concepts

C is a general purpose programming language, unlike other languages such as C and FORTRAN
developed for some specific uses. C is designed to work with both software and hardware. C has in
fact been used to develop a variety of software such as:
 Operating systems: Unix and Windows.
 Application packages: WordPerfect and Dbase.
It was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs.
C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978, Brian Kernighan
and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX applications programs
have been written in C. The C has now become a widely used professional language for various
reasons.

Easy to learn
Structured language
It produces efficient programs.

Page 24
It can handle low-level activities.
It can be compiled on a variety of computer platforms.

Facts about C
 C was invented to write an operating system called UNIX.
 C is a successor of B language, which was introduced around 1970.
 The language was formalized in 1988 by the American National Standard Institute. (ANSI).
 The UNIX OS was totally written in C by 1973.
 Today, C is the most widely used and popular System Programming Language.
 Most of the state-of-the-art softwares have been implemented using C.
 Today's most popular Linux OS and RBDMS MySQL have been written in C.

Why to use C?

C was initially used for system development work, in particular the programs that make up the
operating system. C was adopted as a system development language because it produces code that runs
nearly as fast as code written in assembly language. Some examples of the use of C might be:
Operating Systems Modern Programs
Databases Text Editors
Language Interpreters Language Compilers
Utilities

MERITS OF C LANGUAGE

 C Supports structured programming design features.


It allows programmers to break down their programs into functions. Further it supports the use
of comments, making programs readable and easily maintainable.
 Efficiency
 C is a concise language that allows you to say what you mean in a few words.
 The final code tends to be more compact and runs quickly.
 Portability
C programs written for one system can be run with little or no modification on other systems.
 Power and flexibility
 C has been used to write operating systems such as Unix, Windows.
 It has (and still is) been used to solve problems in areas such as physics and engineering.
 Programmer orientation
 C is oriented towards the programmer’s needs.
 It gives access to the hardware. It lets you manipulate individual bits of memory.
 It also has a rich selection of operators that allow you to expand programming capability.

5.2 C programming environment

Local Environment Setup


If you want to set up your environment for C programming language, you need the following two
software tools available on your computer, (a) Text Editor and (b) The C Compiler.
Text Editor

Page 25
This will be used to type your program. Examples of few a editors include Windows Notepad, OS Edit
command, Brief, Epsilon, EMACS, and vim or vi.
The name and version of text editors can vary on different operating systems. For example, Notepad
will be used on Windows, and vim or vi can be used on windows as well as on Linux or UNIX.
The files you create with your editor are called the source files and they contain the program source
codes. The source files for C programs are typically named with the extension ".c".
Before starting your programming, make sure you have one text editor in place and you have enough
experience to write a computer program, save it in a file, compile it and finally execute it.
The C Compiler
The source code written in source file is the human readable source for your program. It needs to be
"compiled", into machine language so that your CPU can actually execute the program as per the
instructions given.
The compiler compiles the source codes into final executable programs. The most frequently used and
free available compiler is the GNU C/C++ compiler; otherwise you can have compilers either from HP
or Solaris if you have the respective operating systems.

Preprocessor directives
Preprocessor directives are lines included in a program that begin with the character #, which make
them different from a typical source code text. They are invoked by the compiler to process some
programs before compilation.

 #define- the #define directive allows the definition of macros within your source code.
 #include- Inserts a particular header from another file.
 #undef- Undefines a preprocessor macro.
 #ifdef- Returns true if this macro is defined.
 #ifndef- Returns true if this macro is not defined.
 #if- Tests if a compile time condition is true.
 #else- The alternative for #if.
 #elif- #else and #if in one statement.
 #endif- Ends preprocessor conditional.
 #error-Prints error message on stderr.
 #pragma- Issues special commands to the compiler, using a standardized method.

5.3 C program format

A C program basically consists of the following parts −

 Preprocessor Commands
 Functions
 Variables
 Statements & Expressions
 Comments

 Preprocessor Commands: These commands tells the compiler to do preprocessing before doing
actual compilation. Like #include <stdio.h> is a preprocessor command which tells a C compiler to
include stdio.h file before going to actual compilation.

Page 26
 Functions: are main building blocks of any C Program. Every C Program will have one or more
functions and there is one mandatory function which is called main() function. This function is
prefixed with keyword int which means this function returns an integer value when it exits. This
integer value is retured using return statement.
 The C Programming language provides a set of built-in functions. In the above example printf() is a
C built-in function which is used to print anything on the screen. Check Builtin functionsection for
more detail.
 You will learn how to write your own functions and use them in Using Function session.
 Variables: are used to hold numbers, strings and complex data for manipulation. You will learn in
detail about variables in C Variable Types.
 Statements & Expressions : Expressions combine variables and constants to create new values.
Statements are expressions, assignments, function calls, or control flow statements which make up
C programs.
 Comments: are used to give additional useful information inside a C Program. All the comments
will be put inside /*...*/ as given in the example above. A comment can span through multiple lines.

Note the followings

 C is a case sensitive programming language. It means in


C printf and Printf will have different meanings.
 C has a free-form line structure. End of each C statement must be marked
with a semicolon.
 Multiple statements can be one the same line.
 White Spaces (ie tab space and space bar ) are ignored.
 Statements can continue over multiple lines.

#include <stdio.h>
int main() {
/* my first program in C */
printf("Hello, World! \n");
return 0;
}

Explanation:
 The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler to
include stdio.h file before going to actual compilation.
 The next line int main() is the main function where the program execution begins.
 The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in
the program. So such lines are called comments in the program.
 The next line printf(...) is another function available in C which causes the message "Hello, World!" to
be displayed on the screen.
 The next line return 0; terminates the main() function and returns the value 0.

Page 27
6.0 Fundamentals of c programming

6.1 C fundamentals

Operators and Operands

An operator is a component of any expression that joins individual constants, variables, array elements
and function references.

An operand is a data item that is acted upon by an operator. Some operators act upon two operands
(binary operators) while others act upon only one operand (unary operators).

An operand can be a constant value, a variable name or a symbolic constant.

Note: An expression is a combination of operators and operands.

Examples
x + y ; x, y are operands, + is an addition operator.
3 * 5; 3, 5 are constant operands, * is a multiplication operator.
x % 2.5; x, 5 are operands, % is a modulus (remainder) operator.
sizeof (int); sizeof is an operator (unary), int is an operand.

Arithmetic Operators

There are five arithmetic operators in C.


Operator Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder after integer division

Note:
There exists no exponential operators in C.
The operands acted upon by arithmetic operators must represent numeric values, that is operands may
be integers, floating point quantities or characters (since character constants represent integer values).
The % (remainder operator) requires that both operands be integers.
Thus;
5%3
int x = 8;
int y = 6 ; x % y are valid while;
8.5 % 2.0 and
float p = 6.3, int w = 7 ; 5 %p , p % w are invalid.
Division of one integer quantity by another is known as an integer division. If the quotient (result of
division) has a decimal part, it is truncated.
Dividing a floating point number with another floating point number, or a floating point number with
an integer results to a floating point quotient .

Page 28
Exercise
Suppose a = 10, b = 3, v1 = 12.5, v2 = 2.0, c1 =’P’, c2 = ‘T’. Compute the result of the following
expressions.
a+b v1 * v2
a-b v1 / v2
a*b c1
a/b c1 + c2 +5
a%b c1 + c2 +’9’

Note:
c1 and c2 are character constants
ASCII codes for 9 is 57, P = 80,T = 84.

If one or both operands represent negative values, then the addition, subtraction, multiplication, and
division operators will result in values whose signs are determined by their usual rules of algebra. Thus
if a b, and c are 11, -3 and –11 respectively, then

a+b =8
a – b = 14
a * b = -33
a / b = -3
a % b = -2
c % b = -2
c/b=3

Examples of floating point arithmetic operators


r1 = -0.66, r2 = 4.50 (operands with different signs)
r1 + r2 = 3.84
r1 - r2 = -5.16
r1 * r2 = -2.97
r1 / r2 = -0.1466667

Note:
If both operands are floating point types whose precision differ (e.g. a float and a double) the lower
precision operand will be converted to the precision of the other operand, and the result will be
expressed in this higher precision. (Thus if an expression has a float and a double operand, the result
will be a double).
If one operand is a floating-point type (e.g. float, double or long double) and the other is a character or
integer (including short or long integer), the character or integer will be converted to the floating point
type and the result will be expressed as such.
If neither operand is a floating-point type but one is long integer, the other will be converted to long
integer and the result is expressed as such. (Thus between an int and a long int, the long int will be
taken).
If neither operand is a floating type or long int, then both operands will be converted to int (if
necessary) and the result will be int (compare short int and long int)

From the above, evaluate the following expressions given:


i =7, f = 5.5, c = ’w’. State the type of the result.

Page 29
i+f
i+c
i + c-‘w’
( i + c) - ( 2 * f / 5)

(‘w” has ASCII decimal value of 119)

Note: Whichever type of result an expression evaluates to, a programmer can convert the result to a
different data type if desired. The general syntax of doing this is:

(data type) expression.


The data type must be enclosed in parenthesis (). For example the expression (i + f) above evaluates to
12.5. To convert this to an integer, it will be necessary to write
(int) (i + f).

Operator Precedence

The order of executing the various operations makes a significant difference in the result. C assigns
each operator a precedence level. The rules are;

Multiplication and division have a higher precedence than addition and subtraction, so they are
performed first.

If operators of equal precedence; (*, /), (+, -) share an operand, they are executed in the order in which
they occur in the statement. For most operators, the order (associativity) is from left to right with the
exception of the assignment ( = ) operator.

Consider the statement;


butter = 25.0 + 60.0 * n / SCALE;
Where n = 6.0 and SCALE = 2.0.

The order of operations is as follows;


First: 60.0 * n = 360.0
(Since * and / are first before + but * and / share the operand n with * first)

Second: 360.0 / SCALE = 180


(Division follows)

Third: 25.0 + 180 = 205.0 (Result)


(+ comes last)

Note that it is possible for the programmer to set his or her own order of evaluation by putting, say,
parenthesis. Whatever is enclosed in parenthesis is evaluated first.

What is the result of the above expression written as:


+ 60.0 * n) / SCALE.

Page 30
Example: Use of operators and their precedence
/* Program to demonstrate use of operators and their precedence */
include<stdio.h >
main()
{
int score,top;
score = 30;
top = score - (2*5) + 6 * (4+3) + (2+3);
printf (“top = %d \ n” , top);
system(“pause”);
return 0;
}
Try changing the order of evaluation by shifting the parenthesis and note the change in the top score.

Example: Converting seconds to minutes and seconds using the % operator


#include<stdio.h >
#define SEC_PER_MIN 60
main()
{
int sec, min, sec_left;
printf(“ Converting seconds to minute and seconds \n “) ;
printf( “Enter number of seconds you wish to convert \n “) ;
scanf(“% d” , &sec ) ; /* Read in number of seconds */
min = sec / SEC_PER_MIN ; / * Truncate number of seconds */
sec_left = sec % SEC_PER_MIN ;
printf(“% d seconds is % d minutes,% seconds\n “ ,sec,min,sec_left);
system(“pause”);
return 0;
}

The sizeof operator

sizeof returns the size in bytes, of its operand. The operand can be a data type e.g. sizeof (int), or a
specific data object e.g. sizeof n.

If it is a name type such as int, float etc. The operand should be enclosed in parenthesis.

Example : Demonstrating ‘sizeof’ operator


#include <stdio.h>
main()
{
int n;
printf(“n has % d bytes; all ints have % d bytes \n”, sizeof n, sizeof(int)) ;
system(“pause”);
return 0;
}
The Assignment Operator

Page 31
The Assignment operator ( = ) is a value assigning operator. There are several other assignment
operators in C. All of them assign the value of an expression to an identifier.

Assignment expressions that make use of the assignment operator (=) take the form;

identifier = expression;
where identifier generally represents a variable, constant or a larger expression.

Examples of assignment;
a=3;
x=y;
pi = 3.14;
sum = a + b ;
area_circle = pi * radius * radius;

Note
You cannot assign a variable to a constant such as 3 = a ;
The assignment operator = and equality operator (= =) are distinctively different. The = operator
assigns a value to an identifier. The equality operator (= =) tests whether two expressions have the
same value.
Multiple assignments are possible e.g. a =b = 5 ; assigns the integer value 5 to both a and b.
Assignment can be combined with +, -, /, *, and %

The Conditional Operator


Conditional tests can be carried out with the conditional operator (?). A conditional expression takes
the form:

expression1 ? expression2 : expression3 and implies;

evaluate expression1. If expression1 evaluates to true ( value is 1 or non zero) then evaluate
expression 2, otherwise (i.e. if expression 1 is false or zero ) , evaluate expression3.

Consider the statement (i < 0) ? 0 :100

Assuming i is an integer, the expression (i < 0) is evaluated and if it is true, then the result of the entire
conditional expression is zero (0), otherwise, the result will be 100.

Unary Operators

These are operators that act on a single operand to produce a value. The operators may precede the
operand or are after an operand.

Examples
Unary minus e.g. - 700 or –x
Incrementation operator e.g. c++
Decrementation operator e.g. f - -
sizeof operator e.g. sizeof( float)

Page 32
 Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
 Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
 Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;

Relational Operators

There are four relational operators in C.

< Less than


<= Less than or equal to
> Greater than
>= Greater than or equal to

Closely associated with the above are two equality operators;


== Equal to
!= Not equal to

The above six operators form logical expressions.

A logical expression represents conditions that are either true (represented by integer 1) or false
(represented by 0).

Example
Consider a, b, c to be integers with values 1, 2,3 respectively. Note their results with relational
operators below.

Expression Result

a<b 1 (true)
(a+ b) > = c 1 (true)
(b + c) > (a+5) 0 (false)
C != 3 0(false)
b==2 1 (true)

Logical operators

&& Logical AND


|| Logical OR
! NOT

The two operators act upon operands that are themselves logical expressions to produce more complex
conditions that are either true or false.

Page 33
Example
Suppose i is an integer whose value is 7, f is a floating point variable whose value is 5.5 and C is a
character that represents the character ‘w’, then;

(i > = = 6 ) && ( C = = ‘w’ ) is 1 (true)


( C’ > = 6 ) || (C = 119 ) is 1 (true)
(f < 11 ) && (i > 100) is 0 (false)
(C! = ‘ p’) || ((i + f) < = 10 ) is 1 (true)

Revision Exercises

Describe with examples, four relational operators.


What is ‘operator precedence’? Give the relative precedence of arithmetic operators.
Suppose a, b, c are integer variables that have been assigned the values a =8, b = 3 and c = - 5, x, y, z
are floating point variables with values x =8.8, y = 3.5, z = -5.2.

Further suppose that c1, c2, c3 are character-type variables assigned the values E, 5 and ? respectively.

Determine the value of each of the following expressions:


a/b (v) x % y
2 * b + 3 * (a – c) (vi) 2 * x / (3 * y)
(a * c) % b (vii) c1 / c3
(x / y) + z (viii) (c1 / c2) * c3

Data Types
In computer programming, a data type or simply type is a classification of data which tells the compiler
or interpreter how the programmer intends to use the data. Most programming languages support
various types of data, for example: real, integer or Boolean. A Data type provides a set of values from
which an expression (i.e. variable, function ...) may take its values. The type defines the operations that
can be done on the data, the meaning of the data, and the way values of that type can be stored.

Simple Data types - primitive data type is either of the following:


a basic type is a data type provided by a programming language as a basic building block. Most
languages allow more complicated composite types to be recursively constructed starting from basic
types.
a built-in type is a data type for which the programming language provides built-in support.
They include
Type Meaning Keyword
Character Character data Char
Integer Signed whole number Int
Float floating-point numbers Float
Double double precision floating-point Double
numbers
Void Valueless Void

The ‘int’ specifier

Page 34
It is a type specifier used to declare integer variables. For example, to declare count as an integer you
would write:
int count;

Integer variables may hold signed whole numbers (numbers with no fractional part). Typically, an
integer variable may hold values in the range –32,768 to 32,767 and are 2 bytes long.

The ‘char’ specifier


A variable of type char is 1 byte long and is mostly used to hold a single character. For example to
declare ch to be a character type, you would write:
char ch;

The ‘float’ specifier


It is a type specifier used to declare floating-point variables. These are numbers that have a whole
number part and a fractional or decimal part for example 234.936. To declare f to be of type float, you
would write:
float f;
Floating point variables typically occupy 4 bytes.
The ‘double’ specifier
It is a type specifier used to declare double-precision floating point variables. These are variables that
store float point numbers with a precision twice the size of a normal float value. To declare d to be of
type double you would write:
double d;
Double-type variables typically occupy 8 bytes.

An identifier- is a string of alphanumeric characters that begins with an alphabetic character or an


underscore character that are used to represent various programming elements such as variables,
functions, arrays, structures, unions and so on. Actually, an identifier is a user-defined word.

An expression - in a programming language is a combination of one or more explicit values,


constants, variables, operators, and functions that the programming language interprets (according to its
particular rules of precedence and of association) and computes to produce ("to return", in a stateful
environment) another value. This process, as for mathematical expressions, is called evaluation.

I/O Instructions –

C programming has several in-built library functions to perform input and output tasks.

Two commonly used functions for I/O (Input/Output) are printf() and scanf().

The scanf() function reads formatted input from standard input (keyboard) whereas
the printf() function sends formatted output to the standard output (screen).

Page 35
Example 1: C Output
#include <stdio.h> // Including header file to run printf() function.
int main()
{
printf("C Programming"); // Displays the content inside quotation
return 0;
}

Output

C Programming

 All valid C program must contain the main() function. The code execution begins from the start
of main() function.
 The printf() is a library function to send formatted output to the screen.
The printf()function is declared in "stdio.h" header file.
 Here, stdio.h is a header file (standard input output header file) and #include is a
preprocessor directive to paste the code from the header file when necessary. When the
compiler encounters printf() function and doesn't find stdio.h header file, compiler shows
error.
 The return 0; statement is the "Exit status" of the program.

Example 2: C Integer Output


#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}

Output

Page 36
Number = 5

Inside the quotation of printf() function, there is a format string "%d" (for integer). If the
format string matches the argument ( testInteger in this case), it is displayed on the screen.

Example 3: C Integer Input/Output


#include <stdio.h>
int main()
{
int testInteger;
printf("Enter an integer: ");
scanf("%d",&testInteger);
printf("Number = %d",testInteger);
return 0;
}

Output

Enter an integer: 4

Number = 4

Keywords - These are reserved words that have special meaning in a language. The compiler
recognizes a keyword as part of the language’s built – in syntax and therefore it cannot be used for any
other purpose such as a variable or a function name. C keywords must be used in lowercase otherwise
they will not be recognized.

Examples of keywords
auto break case else int void
default do double if sizeof long
float for goto signed unsignedError! Bookmark not defined.
register return short union continue
struct switch typedef const extern

Page 37

You might also like