UNIT- 1
Introduction to Programming
The main components of the computer system are:
Motherboard
Processor
Internal Memory
Video card
Sound card
Internal Hard Disk Drive.
Motherboard:
The motherboard is central to any computer system.
All components plug into the motherboard either directly or indirectly
Once connected to the motherboard the components can work together to form the computer system.
Components communicate and send signals to each other via the BUS network.
Processor (CPU / Central Processing Unit)
|
|
|
Internal Memory (RAM and ROM)
There are two types of internal memory – RAM and ROM.
RAM and ROM are used to store computer data which can be accessed by the CPU.
RAM and ROM are referred as “Primary Storage”
RAM (Random Access Memory)
- RAM is used to temporarily store information that is currently in use by the computer. This can include anything from word documents to videos.
- RAM can be read from and written to and so the information stored in RAM can change all the time.
- RAM is a fast memory. Data can be written to and read from RAM very quickly. RAM is generally measured in GB (Gigabytes).
- RAM is Volatile Memory. This means that information stored in RAM is deleted as soon as the computer is turned off.
ROM (Read Only Memory)
- ROM is used to permanently store instructions that tell the computer how to boot (start- up). It also loads the operating system (e.g. Windows).
These instructions are known as the BIOS (Basic input/output system) or the boot program. - Information stored in ROM is known as READ ONLY. This means that the contents of ROM cannot be altered or added to by the user.
- ROM is fast memory. Data stored in ROM can be accessed and read very quickly.
- ROM is Non-Volatile memory. This means that stored information is not lost when the computer loses power.
- Other examples of ROM include:
- DVD/CD ROMS bought in stores containing pre-recorded music and movie files. These are played back at home but cannot be altered.
- ROM in printers which is used to store different font types.
Video Card:
Graphic cards are hardware devices that plug into the motherboard and enables the computer to display images on the monitor.
Graphics cards usually require installation of software alongside the hardware. The software instructs the computer how to use the graphics card and alter settings to change image quality and size.
Sound Card:
Sound cards are internal hardware devices that plug into the motherboard.
A sound card's main function is to allow the computer system to produce sound, but they also allow users to connect microphones to input sounds into the computer.
Sound cards are also useful in the conversion of analogue data into digital and vice versa.
Storage Devices:
Secondary storage devices are used to store data that is not instantly needed by the computer.
Secondary storage devices permanently store data and programs for as long as we need. These devices are also used to back-up data in case original copies are lost or damaged.
1.1.1 Memory, processor, I/O Devices, storage, operating system, Concept of assembler, compiler, interpreter, loader and linker.
Memory:
A memory is used to store data and instructions. Computer memory is the storage space in the computer, where data is to be processed and instructions required for processing are stored. The memory is divided into large number of small parts called cells. Each location or cell has a unique address, which varies from zero to memory size minus one.
For example, if the computer has 64k words, then this memory unit has 64 * 1024 = 65536 memory locations. The address of these locations varies from 0 to 65535.
Memory is primarily of three types −
- Cache Memory
- Primary Memory/Main Memory
- Secondary Memory
Cache Memory
Cache memory is a high -speed semiconductor memory which can speed up the CPU. It acts as a buffer between the CPU and the main memory. It is used to hold those parts of data and program which are most frequently used by the CPU. The parts of data and programs are transferred from the disk to cache memory by the operating system, from where the CPU can access them.
Advantages
The advantages of cache memory are as follows −
- Cache memory is faster than main memory.
- It consumes less access time as compared to main memory.
- It stores the program that can be executed within a short period of time.
- It stores data for temporary use.
Disadvantages
The disadvantages of cache memory are as follows −
- Cache memory has limited capacity.
- It is too expensive.
Primary Memory (Main Memory)
Primary memory holds only those data and instructions on which the computer is currently working. It has a limited capacity and data is lost when power is switched off. It is generally made up of semiconductor device. These memories are not as fast as registers. The data and instruction required to be processed resides in the main memory. It is divided into two subcategories RAM and ROM.
Characteristics of Main Memory
- These are semiconductor memories.
- It is known as the main memory.
- Usually volatile memory.
- Data is lost in case power is switched off.
- It is the working memory of the computer.
- Faster than secondary memories.
- A computer cannot run without the primary memory.
Secondary Memory
This type of memory is also known as external memory or non-volatile. It is slower than the main memory. These are used for storing data/information permanently. CPU directly does not access these memories, instead they are accessed via input-output routines. The contents of secondary memories are first transferred to the main memory, and then the CPU can access it. For example, disk, CD-ROM, DVD, etc.
Characteristics of Secondary Memory
- These are magnetic and optical memories.
- It is known as the backup memory.
- It is a non-volatile memory.
- Data is permanently stored even if power is switched off.
- It is used for storage of data in a computer.
- Computer may run without the secondary memory.
- Slower than primary memories.
Processor:
A processor (CPU) is the logic circuitry that responds to and processes the basic instructions that drive a computer. The CPU is the main integrated circuitry (IC) chip in a computer, as it is responsible for interpreting most of computers commands. CPUs will perform most basic arithmetic, logic, and I/O operations, as well as allocate commands for other chips and components running in a computer.
The basic elements of a processor include:
- The arithmetic logic unit (ALU), which carries out arithmetic and logic operations on the operands in instructions.
- The floating -point unit (FPU), also known as a math coprocessor or numeric coprocessor, a specialized co-processor that manipulates numbers more quickly than the basic microprocessor circuitry can.
- Registers, which hold instructions and other data. Registers supply operands to the ALU and store the results of operations.
- L1 and L2 cache memory. Their inclusion in the CPU saves time compared to having to get data from random access memory (RAM).
CPU Operations
The four primary functions of a processor are fetch, decode, execute and write back.
Fetch- is the operation which receives instructions from program memory from a systems RAM.
Decode- is where the instruction is converted to understand which other parts of the CPU are needed to continue the operation. This is performed by the instruction decoder
Execute- is where the operation is performed. Each part of the CPU that is needed is activated to carry out the instructions.
Program stored and executed operating system:
Whenever you save your program(anything) into a file (any kind of file, say ‘add.c’), it automatically gets stored in the secondary storage that is the hard disk. The Operating System’s kernel (kernel’s File management system) does it for you.
When you run program, it is loaded into the main/primary memory of the computer called RAM (the entire program is transferred to the RAM, by a small program called the loader (which often comes with the compiler i.e. is a part of the compiler).
The program instructions are executed in the ALU (Arithmetic-Logic Unit) of the CPU (in its registers like the Accumulator). In order to execute the instructions , the CPU fetches the values of the variables (say, int a =10; int b =20;) in the program from the RAM, and stores the results also in the RAM (int sum =30;), which is then sent to the output buffer stream (stdout) , which prints the results (30) on the computer console/terminal, the Windows kernel (kernel’s I/O management system) does the printing .
Compilers:
Compiler is a program that translates source code into object code. The compiler derives its name from the way it works, looking at the entire piece of source code and collecting and reorganizing the instructions. Thus, a compiler differs from an interpreter, which analyses and executes each line of source code in succession, without looking at the entire program. The advantage of interpreters is that they can execute a program immediately. Compilers require some time before an executable program emerges. However, programs produced by compilers run much faster than the same programs executed by an interpreter.
Every high- level programming language comes with a compiler. In effect, the compiler is the because it defines which instructions are acceptable.
Because compilers translate source code into object code, which is unique for each type of computer many compilers are available for the same language.
An algorithm is the finite set of English statements which are designed to accomplish the specific task. Study of any algorithm is based on the following four criteria
1. Design of algorithm : This is the first step in the creation of an algorithm. Design of algorithm includes the problem statement which tell user about the area for which algorithm is required. After problem statement next important thing required is the information about available and required resources. The last thing required in design of algorithm phase is information about the expected output.
2. Validation of algorithm : Once an algorithm is designed , it is necessary to validate it for several possible input and make sure that algorithm is providing correct output for every input. This process is known as algorithm validation. The purpose of the validation is to assure us that this algorithm will work correctly independently of the issues concerning the programming language it will eventually be written in.
3. Analysis of algorithm : Analysis of algorithms is also called as performance analysis. This phase refers to the task of determining how much computing time and storage an algorithm requires. The efficiency is measured in best case, worst case and average case analysis.
4. Testing of algorithm : This phase is about to testing of a program which coded as per the algorithm. Testing of such program consists of two phases:
Debugging : It is the process of executing programs on sample data sets to determine whether faulty results occur or not and if occur, to correct them.
Profiling : Profiling or performance measurement is the process of executing a correct program on data sets and measuring the time and space it takes to compute the result
Characteristics of an algorithm
Input: Algorithm must accept zero or more inputs.
Output: Algorithm must provide at least one quantity.
Definiteness: Algorithm must consist of clear and unambiguous instruction.
Finiteness: Algorithm must contain finite set of instruction and algorithm will terminates after a finite number of steps.
Effectiveness: Every instruction in algorithm must be very basic and effective.
Uses of algorithm
Algorithm provide independent layout of the program.
It is easy to develop the program in any desired language with help of layout.
Algorithm representation is very easy to understand.
To design algorithm there is no need of expertise in programming language.
1.2.1 Representation of Algorithm, Flowchart, Pseudo code with examples
There are three ways to represent an algorithm. Consider the following algorithm of addition of two numbers
Step 1 : Start
Step 2 : Read a number, say x and y
Step 3 : Add x and y
Step 4 : Display Addition
Step 5 : Stop
1. Flowcharts: A flow chart is a diagrammatic / pictorial representation of an algorithm. It is the simplest way of representation of algorithm. Initially an algorithm is represented in the form of flowchart and then flowchart is given to programmer to express it in some programming language. Logical error detection is very easy in flowchart as it shows the flow of operations in diagrammatic form. Once flowchart is ready it is very easy to write a program in terms of statements of a programming language. Following are the symbols used in designing the flowcharts.
2. Pseudo code : Pseudo code is the combination of English statements with programming methodology. In pseudo code, there is no restriction of following the syntax of the programming language. Pseudo codes cannot be compiled. It is just a previous step of developing a code for given algorithm.
3. Program : In this way of representation, complete algorithm is represented using some programming language by following the complete syntax of programming language.
Sr. No. | Name of Symbol | Symbol | Meaning / Purpose |
1. | Terminal |
| To indicate START / STOP. Usually it is the first symbol and last symbol used in program logic. |
2. | Input / Output Statement | To indicate input / output of Data | |
3. | Processing Statement | To indicate the processing of instructions. | |
4. |
Decision Box |
| To indicate decision making and a branch to one or more alternatives. |
5. | Flow Lines | To indicate the direction of flow of information. | |
6. | Connector |
| It is used when flowchart becomes long and need to be continued. Shows the continuity of the algorithm on the next page. |
1.2.2 From algorithms to programs
An algorithm is a step-by-step procedure for solving a certain class of problems.
This can be executed mechanically.
Program = algorithm formulated in programming language.
To be valid, the algorithm must be correct in the results it provides and it must also terminate. Meaning that an analyst has to prove these two characteristics to establish the validity of the algorithm.
To be valid, a program simply compiles (or be interpreted) and herein lies the key difference. A program is a sequence of steps written to run on a machine.
Programs usually implement algorithms, and others, like an operating system implement many algorithms. To go from an algorithm to a program is to go from an idea to a concrete thing.
In a nutshell, an algorithm is a sequence of steps that describes an idea for solving a problem meeting the criteria of correctness and terminability. A program is a sequence of steps that is specified at enough detail to be able to run on a machine.
1.2.3 Source code
Source code is the list of human-readable instructions that a programmer writes—often in a word processing program—when he is developing a program. The source code is run through to turn it in compiler to machine code called as object code.
Computer Programming is defined as the step by step process of designing and developing various sets of computer programs to accomplish a specific computing outcome. The process comprises several tasks like analysis, coding, algorithm generation, checking accuracy and resource consumption of algorithms, etc.
The purpose of computer programming is to find a sequence of instructions that solve a specific problem on a computer.
These basic elements include −
- Programming Environment
- Basic Syntax
- Data Types
- Variables
- Keywords
- Basic Operators
- Decision Making
- Loops
- Numbers
- Characters
- Arrays
- Strings
- Functions
- File I/O
1.3.1 Structure of C program
C program basically consists of the following parts −
- Preprocessor Commands
- Functions
- Variables
- Statements & Expressions
- Comments
Let us look at a simple code that would print the words "Hello World" –
#include <stdio.h>
int main() { /* my first program in C */ printf("Hello, World! \n");
return 0; } The various parts of the above program −
|
1.3.2 Writing and executing the first C program
A C program source code can be written in any text editor; however, the file should be saved with .c extension. First C Program
#include<stdio.h> int main() { int num; printf("Enter your age: "); scanf("%d", &num); if (num <18) { printf("you are not eligible for voting"); } else { printf("You can vote!!"); } return 0; } Output:
Enter your age:25
Lets understand this Program: Comment: Comment start with’ /*’ and end with ‘*/’. Comments are not mandatory but still it’s a good practice if you use them, it improves the readability of the code. A program can have any number of comments.
Include section: While writing program we use several keywords & statements and functions such as printf(), scanf() etc. The file that has definitions of these functions needs to be included in the program. In the above program we have used stdio.h.There are several libraries and “stdio.h” is one of them, which is used for reading the data from terminal and to display the data on terminal. |
1.3.3 Syntax and logical errors in compilation
A syntax error is an error in the source code of a program. Since computer programs must follow strict syntax to compile correctly, any aspects of the code that do not conform to the syntax of the programming language will produce a syntax error.
• Spelling mistakes
• Missing out quotes
• Missing out brackets
• Using upper case characters in key words e.g. IF instead of if
• Missing out a colon or semicolon at end of a statement
• Using tokens in the wrong order A logic error (or logical error) is a ‘bug’ or mistake in a program’s source code that results in incorrect or unexpected behaviour. It is a type of runtime error that may simply produce the wrong output or may cause a program to crash while running.
1.3.4 Object and executable code
|
Source code is the C program that you write in your editor and save with a ‘ .C ‘ extension which is un-compiled when written for the first time or whenever a change is made in it and saved.
Object code is the output of a compiler after it processes the source code. The object code is usually a machine code, also called a machine language, which can be understood directly by a specific type of CPU. However, some compilers are designed to convert source code into an assembly language or some other another programming language.
An assembly language is a human-readable notation using the mnemonics in the ISA of that particular CPU.
Executable (also called the Binary) is the output of a linker after it processes the object code. A machine code file can be immediately executable, runnable as a program , or it might require linking with other object code files for example libraries to produce a complete executable program.
1.3.5 Components of C language
Tokens in C
A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following C statement consists of five tokens − printf("Hello, World! \n"); The individual tokens are − printf ( "Hello, World! \n" ) ; Semicolons In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity. Given below are two different statements − printf("Hello, World! \n"); return 0;
Comments Comments are like helping text in your C program and they are ignored by the compiler. They start with /* and terminate with the characters */ as shown below − /* my first program in C */ You cannot have comments within comments and they do not occur within a string or character literals. Identifiers A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z, a to z, or an underscore ‘_’ followed by zero or more letters, underscores, and digits (0 to 9). C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-sensitive programming language. Here are some examples of acceptable identifiers − mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal |
Keywords
The following list shows the reserved words in C. These reserved words may not be used as constants or variables or any other identifier names.
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 |
|
|
|
Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement −
int age;
there must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement −
fruit = apples + oranges; // get the total fruit
1.3.6 Standard I/O in C
#include<stdio.h> void main() { int a,b,c; printf("Please enter any two numbers: \n"); scanf("%d %d", &a, &b); c = a + b; printf("The addition of two number is: %d", c); } Please enter any two numbers: 12 3 The addition of two number is:15 Managing Input/Output I/O operations are useful for program to interact with users . stdlib is the standard library for input-output operations. In C two important streams play their role: These are:
Standard input or stdin is used for taking input from devices such as keyboard as a data stream. Standard output or stdout is used for giving output to a device such as a monitor. For using I/O functionality programmers must include stdio header-file within the program. Reading Character in C The easiest and simplest I/O operations are taking character as input by reading that character from standard input . getchar() function can be used to read a single character. This function is alternate to scanf() function. Syntax: var_name = getchar(); Example: #include<stdio.h> void main() { char title; title= getchar(); } Writing Character in C Syntax: Putchar(var_name);
Example: #include<stdio.h> void main() { char result = ‘P’ putchar(result); putchar(‘\n’); } |
1.3.7 Fundamental data types
Data Declarations
Declarations serve two purposes:
They tell the compiler to set aside an appropriate amount of space in memory for the program’s data (variables).
They enable the compiler to correctly operate on the variables. The compiler needs to know the data type to correctly operate on a variable. The compiler needs to know how many bytes are used by variables and the format of the bits. The meaning of the binary bits of a variable are different for different data types.
- char is 8 bit (1 byte) ASCII, but can also store numeric data.
- int is 4 byte 2’s complement.
- short is 2 byte 2’s complement.
- long is 8 byte 2’s complement.
- unsigned (int, short, and long) are straight binary
- float is 4 byte IEEE Floating Point Single Precision Standard.
- double is 8 byte IEEE Floating Point Double Precision Standard.
Character - integer relation The ASCII code is a set of integer numbers used to represent characters. char c = 'a'; /* 'a' has ASCII value 97 */ int i = 65; /* 65 is ASCII for 'A' */ printf( "%c", c + 1 ); /* b */ printf( "%d", c + 2 ); /* 99 */ printf( "%c", i + 3 ); /* D */
Integers A variations of int (unsigned, long, ...) are stored binary data which is directly translated to it’s base-10 value.
Floating point data Variables of type float and double are stored in three parts: the sign, the mantissa (normalized value), and an exponent.
sizeof Because some variables take different amount of memory of different systems, C provides an operator which returns the number of bytes needed to store a given type of data. i = sizeof(char); j = sizeof(long); k = sizeof(double); The sizeof operator is very useful when manually allocating memory and dealing with complex data structures. Conversions and Casts Two mechanisms exist to convert data from one data type to another, implicit conversion and explicit conversion, which is also called casting. implicit conversion If an arithmetic operation on two variables of differing types is performed, one of the variables is converted or promoted to the same data as the other before the operation is performed. In general, smaller data types are always promoted to the larger data type.
explicit conversion or casts The programmer can tell the compiler what types of conversions should be performed by using a cast. A cast is formed by putting a data type keyword in parenthesis in front of a variable name or expression. x = (float)(m * j); i = (int)x + k; |
1.3.8 Variables and memory locations
Variables are the names you give to computer memory locations which are used to store values in a computer program.
Here are the following three simple steps −
- Create variables with appropriate names.
- Store your values in those two variables.
- Retrieve and use the stored values from the variables.
When creating a variable, we need to declare the data type it contains.
Programming languages define data types differently.
For example, almost all languages differentiate between ‘integers’ (or whole numbers, eg 12), ‘non-integers’ (numbers with decimals, eg 0.24), and ‘characters’ (letters of the alphabet or words).
- char – a single 16-bit Unicode character, such as a letter, decimal or punctuation symbol.
- boolean – can have only two possible values: true (1) or false (0). This data type is useful in conditional statements.
- byte - has a minimum value of -128 and a maximum value of 127 (inclusive).
- short– has a minimum value of -32,768 and a maximum value of 32,767
- int: – has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).
- long – has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).
- float – a floating point number with 32-bits of precision
- double – this is a double precision floating point number.
1.3.9 Storage classes
A storage class is used to describe the following things:
- The variable scope.
- The location where the variable will be stored.
- The initialized value of a variable.
- A lifetime of a variable.
References:
The C Programming Language. 2nd Edition Book by Brian Kernighan and Dennis Ritchie
C Programming: A Modern Approach Book by Kim N. King
C Programming Absolute Beginner’s Guide book by S.D Perry