Lecture 1: Introduction of Electrical Principle

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 12

Computer Methods Vol1

Computer programming (often shortened to programming or coding) is the process of


designing, writing, testing, debugging / troubleshooting, and maintaining the source code of
computer programs. This source code is written in a programming language. The purpose of
programming is to create a program that exhibits a certain desired behavior. The process of
writing source code often requires expertise in many different subjects, including knowledge of
the application domain, specialized algorithms and formal logic.

A computer program (also a software program) is a sequence of instructions written to


perform a specified task for a computer. A computer requires programs to function, typically
executing the program's instructions in a central processor. The program has an executable form
that the computer can use directly to execute the instructions. The same program in its human-
readable source code form, from which executable programs are derived (e.g., compiled),
enables a programmer to study and develop its algorithms.

A programming language is an artificial language designed to express computations that can be


performed by a machine, particularly a computer. Programming languages can be used to create
programs that control the behavior of a machine, to express algorithms precisely, or as a mode of
human communication.

Categories of Programming Languages

The term programming language usually refers to high-level languages, such as BASIC, C, C++,
COBOL, FORTRAN, Java, and Pascal. Each language has a unique set of keywords (words that
it understands) and a special syntax for organizing program instructions.

High-level programming languages, while simple compared to human languages, are more
complex than the languages the computer actually understands, called machine languages. Each
different type of CPU has its own unique machine language.

Lying between machine languages and high-level languages are languages called assembly
languages. Assembly languages are similar to machine languages, but they are much easier to
program in because they allow a programmer to substitute names for numbers. Machine
languages consist of numbers only.

Lying above high-level languages are languages called fourth-generation languages (usually
abbreviated 4GL). 4GLs are far removed from machine languages and represent the class of
computer languages closest to human languages.

Regardless of what language you use, you eventually need to convert your program into machine
language so that the computer can understand it. There are two ways to do this:

 compile the program

 interpret the program


The definition of a particular language consists of both syntax (how the various symbols of the
language may be combined) and semantics (the meaning of the language constructs).

Programming Using C/C++


We begin by outlining the basic processes you need to go through in order to compile your C (or C++)
programs

Creating, Compiling and Running Your Program

The stages of developing your C program are as follows:

Creating the program


For example;

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

Create a file containing the complete C/C++program, such as the above example. You can use
any ordinary editor with which you are familiar to create the file.

The contents must obey C /C++syntax.

Compilation

There are many C compilers around, e.g the Borland bcc compiler.

There are also equivalent C++ compilers which are usually denoted by CC (note upper case CC.
For example Sun provides CC and GNU GCC. The GNU compiler is also denoted by g++

For the sake of compactness in the basic discussions of compiler operation we will simply refer
to the cc compiler -- other compilers can simply be substituted in place of cc unless otherwise
stated.

To Compile your program simply invoke the command cc. The command must be followed by
the name of the (C) program you wish to compile. Thus, the basic compilation command is:
cc program.c

where program.c is the name of the file.

If there are obvious errors in your program (such as mistypings, misspelling one of the key
words or omitting a semi-colon), the compiler will detect and report them.

There may, of course, still be logical errors that the compiler cannot detect. You may be telling
the computer to do the wrong operations.

When the compiler has successfully digested your program, the compiled version, or executable,
is left in a file called a.out

Running the program

The next stage is to actually run your executable program. This executes your program, printing
any results to the screen. At this stage there may be run-time errors, such as division by zero, or
it may become evident that the program has produced incorrect output.

If so, you must return to edit your program source, and recompile it, and run it again.

The C Compilation Model


We will briefly highlight key features of the C Compilation model in the Fig. bellow.

The C Compilation Model


The Preprocessor

The Preprocessor accepts source code as input and is responsible for

 removing comments
 interpreting special preprocessor directives denoted by #.

For example

 #include -- includes contents of a named file. Files usually called header files. e.g
o #include <math.h> -- standard library maths file.

o #include <stdio.h> -- standard library I/O file

 #define -- defines a symbolic name or constant. Macro substitution.

o #define MAX_ARRAY_SIZE 100

C Compiler

The C compiler translates source to assembly code. The source code is received from the
preprocessor.

Assembler

The assembler creates object code.

Link Editor

If a source file references library functions or functions defined in other source files the link
editor combines these functions (with main()) to create an executable file. External Variable
references are resolved here also.

C - Program Structure

A C program basically has the following form:

 Preprocessor Commands
 Functions

 Variables

 Statements & Expressions

 Comments

E.g Consider the simple C program below.


#include <stdio.h>

int main()
{
/* My first program */
printf("Hello, World! \n");

return 0;}

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.

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.

Variables: are used to hold numbers, strings and complex data for manipulation.

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 following:

 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 on the same line.

 White Spaces (ie tab space and space bar ) are ignored.

 Statements can continue over multiple lines.

C – Reserved(Key)words
The following names are reserved by the
C language. Their meaning is already
defined, and they cannot be re-defined to
mean anything else.
Auto Else Long Switch
Break Enum register Typedef
Case Extern Return Union
Char Float Short Unsigned
Const For signed Void
continue Goto Sizeof Volatile
Default If Static While
Do Int Struct _Packed
Double
 While naming your functions and variables, other than these names, you can choose any
names of reasonable length for variables,

C - Basic Datatypes

C has a concept of 'data types' which are used to define a variable before its use. The definition
of a variable will assign storage for the variable and define the type of data that will be held in
the location.

The value of a variable can be changed any time.

C has the following basic built-in datatypes.

 int
 float

 double

 char

Please note that there is not a boolean data type. C does not have the traditional view about
logical comparison, but that’s another story.
int - data type

int is used to define integer numbers.

{
int Count;
Count = 5;
}

float - data type

float is used to define floating point numbers.

{
float Miles;
Miles = 5.6;
}

double - data type

double is used to define BIG floating point numbers. It reserves twice the storage for the
number. On PCs this is likely to be 8 bytes.

{
double Atoms;
Atoms = 2500000;
}

char - data type

char defines characters.

{
char Letter;
Letter = 'x';
}

Modifiers

The data types explained above have the following modifiers.

 short
 long

 signed

 unsigned
The modifiers define the amount of storage allocated to the variable. The amount of storage
allocated is not cast in stone. ANSI has the following rules:

short int <= int <= long int


float <= double <= long double

What this means is that a 'short int' should assign less than or the same amount of storage as an
'int' and the 'int' should be less or the same bytes than a 'long int'. What this means in the real
world is:

Type Bytes Range


---------------------------------------------------------------------
short int 2 -32,768 -> +32,767 (32kb)
unsigned short int 2 0 -> +65,535 (64Kb)
unsigned int 4 0 -> +4,294,967,295 ( 4Gb)
int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb)
long int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb)
signed char 1 -128 -> +127
unsigned char 1 0 -> +255
float 4
double 8
long double 12

These figures only apply to todays generation of PCs. Mainframes and midrange machines could
use different figures, but would still comply with the rule above.

You can find out how much storage is allocated to a data type by using the sizeof operator
discussed in Operator Types Session.

Here is an example to check size of memory taken by various datatypes.

#include<stdio.h>
intmain()
{
printf("sizeof(char) == %d\n", sizeof(char));
printf("sizeof(short) == %d\n", sizeof(short));
printf("sizeof(int) == %d\n", sizeof(int));
printf("sizeof(long) == %d\n", sizeof(long));
printf("sizeof(float) == %d\n", sizeof(float));
printf("sizeof(double) == %d\n", sizeof(double));
printf("sizeof(long double) == %d\n", sizeof(long double));
printf("sizeof(long long) == %d\n", sizeof(long long));

return 0;
}

Qualifiers
A type qualifier is used to refine the declaration of a variable, a function, and parameters, by
specifying whether:

 The value of a variable can be changed.


 The value of a variable must always be read from memory rather than from a register

Standard C language recognizes the following two qualifiers:

 const
 volatile

The const qualifier is used to tell C that the variable value can not change after initialisation.

const float pi=3.14159;

Now pi cannot be changed at a later time within the program.

Another way to define constants is w ith the #define preprocessor which has the advantage that it
does not use any storage

The volatile qualifier declares a data type that can have its value changed in ways outside the
control or detection of the compiler (such as a variable updated by the system clock or by
another program). This prevents the compiler from optimizing code referring to the object by
storing the object's value in a register and re-reading it from there, rather than from memory,
where it may have changed. You will use this qualifier once you will become expert in "C". So
for now just proceed.

C - Variable Types

A variable is just a named area of storage that can hold a single value (numeric or character). The
C language demands that you declare the name of each variable that you are going to use and its
type, or class, before you actually try to do anything with it.

The Programming language C has two main variable types

 Local Variables
 Global Variables

Local Variables

 Local variables scope is confined within the block or function where it is defined. Local
variables must always be defined at the top of a block.
 When a local variable is defined - it is not initalised by the system, you must initalise it
yourself.

 When execution of the block starts the variable is available, and when the block ends the
Global Variables

Global variable is defined at the top of the program file and it can be visible and modified by any
function that may reference it.

Global variables are initalised automatically by the system when you define them!

Data Type Initialser

int 0

char '\0'

float 0

pointer NULL

If same variable name is being used for global and local variable then local variable takes
preference in its scope. But it is not a good practice to use global variables and local variables
with the same name.

C- Using Constants

A C constant is usually just the written version of a number. For example 1, 0, 5.73, 12.5e9. We
can specify our constants in octal or hexadecimal, or force them to be treated as long integers.
 Octal constants are written with a leading zero - 015.
 Hexadecimal constants are written with a leading 0x - 0x1ae.
 Long constants are written with a trailing L - 890L.

Character constants are usually just the character enclosed in single quotes; 'a', 'b', 'c'. Some characters
can't be represented in this way, so we use a 2 character sequence as follows.
'\n' newline
'\t' tab
'\\' backslash
'\'' single quote
'\0' null ( Usedautomatically to terminate character string )

In addition, a required bit pattern can be specified using its octal equivalent.

'\044' produces bit pattern 00100100.

Character constants are rarely used, since string constants are more convenient. A string constant
is surrounded by double quotes eg "Brian and Dennis". The string is actually stored as an array
of characters. The null character '\0' is automatically placed at the end of such a string to act as a
string terminator.

A character is a different type to a single character string. This is important poing to note.

Defining Constants

ANSI C allows you to declare constants. When you declare a constant it is a bit like a variable
declaration except the value cannot be changed.

The const keyword is to declare a constant, as shown below:

int const a = 1;
const int a =2;

Note:

 You can declare the const before or after the type. Choose one and stick to it.
 It is usual to initialize a const with a value as it cannot get a value any other way.

The preprocessor #define is another more flexible (see Preprocessor Chapters) method to define
constants in a program.

#define TRUE 1
#define FALSE 0
#define NAME_SIZE 20

Here TRUE, FALSE and NAME_SIZE are constant

You frequently see const declaration in function parameters. This says simply that the function is
not going to change the value of the parameter.

The following function definition used concepts we have not met (see chapters on functions,
strings, pointers, and standard libraries) but for completeness of this section it is included here:

void strcpy(char *buffer, char const *string)

The enum Data type

enum is the abbreviation for ENUMERATE, and we can use this keyword to declare and initialize a
sequence of integer constants. Here's an example:

enum colors {RED, YELLOW, GREEN, BLUE};

I've made the constant names uppercase, but you can name them which ever way you want.
Here, colors is the name given to the set of constants - the name is optional. Now, if you don't
assign a value to a constant, the default value for the first one in the list - RED in our case, has
the value of 0. The rest of the undefined constants have a value 1 more than the one before, so in
our case, YELLOW is 1, GREEN is 2 and BLUE is 3.

But you can assign values if you wanted to:

enum colors {RED=1, YELLOW, GREEN=6, BLUE };

Now RED=1, YELLOW=2, GREEN=6 and BLUE=7.

The main advantage of enum is that if you don't initialize your constants, each one would have a
unique value. The first would be zero and the rest would then count upwards.

You can name your constants in a weird order if you really wanted...

#include <stdio.h>

int main() {
enum {RED=5, YELLOW, GREEN=4, BLUE};

printf("RED = %d\n", RED);


printf("YELLOW = %d\n", YELLOW);
printf("GREEN = %d\n", GREEN);
printf("BLUE = %d\n", BLUE);
return 0;
}

This will produce following results

RED = 5
YELLOW = 6
GREEN = 4
BLUE = 5

You might also like