C Language
May 11, 2017 | Author: wasim ahmed | Category: N/A
Short Description
C Language...
Description
Page 1 of 86
C-language Computer: Computer is an electronic machine which accepts raw data as the input, process the data and gives information as the output. Language: It is the media of communication between any two or more. It may be oral or signs. What is meant by computer language? It is nothing but communicating with the system by the user or programmer to perform his task or fulfill his job. Computers basics: There is only 3 basic concepts about computer, that is noting input -> process->output.
What output to be desired? What are the inputs? How to be processed?
Input: The inputs are given to the system by using input devices such as keyboard, mouse. Output: The output is viewed on the output devices such as VDU (video display unit) or printer. Process:
Page 2 of 86 This task is performed by the CPU(Central Process Unit). It is divided into 3 parts. 1. A.L.U – ARTHMETIC AND LOGICAL UNIT 2. C.U- CONTROL UNIT 3. M.U- MEMORY UNIT ALU performs the actual number crunching and logical operations. CU controls the total process how to input and how to store and how to operate. MU is used to store the data.
Computer memory origination:
Parts of Computers: Mainly 2 parts are exit in computers one is HARDWARE(H/W) and SOFTWARE(S/W). What o What o
you touch physically is hardware? H/W is the collection of electronic and mechanical devices . you can’t touch physically is software? S/W is the collection of programs.
Hardware:
All the physical components or units connected to the computer circuit is known as hardware
Operating system:
Page 3 of 86 It is an interface between user and computer in other words Operating system is a complex set of programs which manages the resources of a computer resources include input, output, processor etc
Language: A programming language consists a set of executable instructions. Package: It is designed by any other language with limited resources Software : Software is said to be collection of programs. This can be categorized as 2 parts. 1. System S/W 2. Application S/w System S/W: o Those S/w are used as the interface between system and user are called as System S/W. Eg: Operating systems, Drivers, Utilities . Application S/w o Those S/w are used for the special purpose of the user. Eg: Packages(like accounting packages and ms-office).
Languages: But to implement or develop the S/W’s is done by the programming languages. Syntax: The structure of the program code. Eg: Add(10,20) or 10+20; it is different for every languages. Semantic: the actual meaning of the syntax. Eg: Add(10,20) – add 10 and 20 integers. Programming Languages are of 3 types. They are Machine Language Middle level language or Assembly Language High level Languages Machine Languages are completely based on the binary Language(mean 0’s and 1’s). this language is easily understood by computers but very hard for developer. Error checking is very tough job.
Page 4 of 86 Middle languages are use some small keywords, those reduce the programmers code to develop. These are little bit easy for developers and also systems but not completely. High level languages are completely in natural English words. So very easy for the developer but very hard to the system. Language translators: High and middle languages are to be translated to machine language code by Language translators, Because system only understood machine languages only. There are 3 types of translators are present. Assembler: This translator translates assembly level code to machine level code. Compiler: Compiler translates entire high level program code to machine level code at a time. Interpreter : interpreter translates high level program code to machine level code line by line. Note: If compiler is used, first complier checks for Syntactical errors and display’s the errors. If no errors are occurred then translates the program. If Interpreter is used, for execution of one statement it checks the next statement if it is syntactically correct or not. ASCII character American Standard code for information and Interchange There are 256 distinct characters used by the micro computers their values range from 0 to 255. These can be grouped as under Character type
No.of character
A to Z
26
a to z
26
digits
0-9
special Symbols
32
control characters
34
graphics characters
128 -------------------
Page 5 of 86 256 Out of the 256 characters, the first 128 are ASCII characters and the next are called extended ASXII characters. Each ASCII Character as a unique appearance. A to Z
65 to 90
a to z
97 to 122
o to 9
48 to 57
Enter
13
Space Bar
32
Tab
9
Backspace
8
Debugging: The process of correcting errors in a program is called as debugging. Various Steps in Application/Program development: 1. Problem definition 2. Analysis and design 3. Algorithm 4. Flow chart 5. Coding and Implementation 6. Debugging and testing 7. Documentation Problem Definition: Problem Definition phase is a clear understanding of exactly what is needed for creating to a workful solution. We must know exactly what we want to do before we begin to do it. Define the problem means Understanding the problem. It involves the 3 specifications regarding a problem solution o
Input Specifications
o
Output Specifications
o
Processing
Analysis and Design Phase
Page 6 of 86 Before going to make the final solutions for the problem, the problem must be analyzed outlines solutions prepared for simple problems but in case of complex problems the main problem is divided into sub problems called modulus. These sub problems can be handled can be solve independently when the task is too large, it always better to analysis. The tasks such that it can be divided into no.of module and solutions for each moduleue. Algorithm: Once the problem is divided into no.of modulus. The Logic for solving each module can be developed. The logic is expressed step by step. A step by step processor to solve the given problems know as ALGORITHM. An algorithm is defined as a final set of steps which accomplish a particular task. An algorithm can be described in a natural language such as English. Flow Chart: After the completion of algorithm the program flow can be visualized by drawing the FLOW CHART. A flow chart is nothing but a graphical of symbolic representation o how instructions will be executed one after the another. Coding and implementation: Coding is a process of converting the algorithm solution or flows chart in to a computer program. In this process each and every step of algorithm will be converted in to instructions of selected computer programming language. Before selecting a programming language. Before selected computer programming language we must follow the 3 following considerations o
Nature of the problem
o
Programming language available on the computer system.
o
Limitations of computer
Debugging and Testing: Before loading the program in to the computer, we must locate and correct all the errors. The process of correcting errors in a program is called as debugging. There are 3 types of errors that generally occur in a program namely o
Syntax errors
o
Logical errors
o
Runtime errors
It is very important to test the program written to achieve a specific task data of which the result are known as the results are known the results produced by the compute r can be verified. Documentation:
Page 7 of 86 It is the most important aspect of the programming. it is a continues process to keep the copy of all the phases invoked in problem definition ,analysis, design ,algorithm, flowchart, coding and implementation, debugging & testing are the parts of the Documentation. This phase involves to producing a written document for the users.
Language paradigms:
Programming style
Abstraction Employed
Procedure oriented
algorithms
Object Oriented
Classes and objects
Logic Oriented
Goals often expressed in predicate calculus
Rule Oriented
If then and else rules
Constraint Oriented
Invariant relationship
There are 3 types of paradigms are preset. They are
Monolithic Programming Procedure Programming Structured Programming Object Oriented Programming
Monolithic Programming : The programs written in these languages exhibit relatively flat physical structure. They consists only global data and sequential code.
Page 8 of 86 Only Global Data 1…….. 2……………. Goto 100 ……… ……. Goto 55 …….. Goto 3 ……. Goto 45 ………………………….. 100………… Eg: Assembly Language, BASIC Procedure Programming:
Programs are organized in the form of subroutines and all data items are global Program controls are through jumps and calls to subroutines Subroutines are abstracted to avoid repetitions Suitable for medium sized software applications Difficult to maintain and enhance the program code
Eg: FORTRAN AND COBOL
Page 9 of 86
Glob al Data
Sub Progr ams Structured Programming:
Emphasis on algorithm rather than data. Programs are divided into individual procedures that perform discrete tasks. Procedures are independent of each other as far as possible and have their own local data and processing logic. Controlled scope of data Introduction of the concepts of user defined data types Support for modular programming, Large projects are bfoken up into modules and programmed independently.
Eg: Pascal and C
Page 10 of 86
Global Data
Modul e1
Modul e2 Sub Programs
Modul e3
Object Oriented Programming:
Emphasis on data rather than algorithm Data abstraction is introduced in addition to procedural abstraction Data and associated operations are unified into a single unit, thus the objects are grouped with common attributes, operations and semantics Programs are designed around the data being operated, rather than operations themselves. Relation ships can be created between similar, yet distinct data types.
Page 11 of 86
Object A
Object B
Object B
History of the Programming Languages: Era 1960s
Applications
Major languages
Other languages
Business
COBOL
Assembler
Scientific
FORTRAN
ALGOL, BASIC
System
Assembler
JOVIAL,FORTH
AI
LISP
SNOBOL
Business
COBOL, C++, Java, Spreadsheet
C, PL/I, 4GLs
Scientific
FORTRAN, C, C++, Java
BASIC
Today
Page 12 of 86 System
C, C++, Java
Ada, BASIC, Modula AI
LISP, Prolog
Publishing
TeX, Postscript, word processing
Process
UNIX shell, TCL, Perl, JavaScript
AWK, Marvel, SED
New paradigms
ML, Smalltalk
Eiffel
History of C- Language: C is a programming language it is designed by DENNIS RITCHIE in 1972 at AT & T (American Telephone and Telegraphs) Bell labs ,USA. C is a most popular general purpose programming language. We can use the c language designed any type of applications. Mainly we are using the c language to implement system software those are COMPILERS, TEXT EDITORS, NETWORK DRIVERS, DATABASES and finally the OPERATING SYSTEMS. Brief history of c language: In 1960’s COBOL was being used for commercial applications and FORTRAN for scientific and Engineering applications are this stage people started to develop a language which is suitable for all possible applications. There fore an International committee was setup to develop such a language ALGOL60 was released it was not popular because it seemed too general to reduce the generality a new language called CPL (Combined Programming Language) was developed at CAMBRIDGE UNIVERSITY. It has very less features than some other features were
C – Language
Page 13 of 86
Features of ‘C’ language 1. c is a structure programming language with fundamental flow control construction. 2. C is high portable programming language. And c programs are run on another with or without any modifications. 3. C is simple and versatile programming language. 4. Programs written in c are efficient and fast. 5. C improves by itself it has several predefined functions. 6. C has a rich set of operators 7. C has only 32 key words 8. C permits all data conversions and mixed more operations. 9. C easily manipulates bits bytes and addresses 10.Dynamic memory allocation is possible with C. 11.Recursive functions called for algorithmic approach is possible with c. 12.Mainly we are using the c to implement system softwares those are compilers, Text readers, Network drivers, data bases and finally the operating systems. 13.C compiler combines the capabilities of an assembly level language with the features of high level language. So it is called as middle level language. Impotent points: 1. C was basically designed for the UNIX operating systems 93% of which is written in c. 2. c is a case sensitive programming language. C statements are entered in small case letters only 3. Every c statements must be terminated by a ‘ ; ’ except preprocessor statements and functions definition. 4. c is a function oriented programming language. Any c program contains one or more functions minimum one functions necessary by the name called “ main “ with out main with out main we can’t execute c program. 5. A function is represented by a function name with a pair of parenthesis. C program Execution
Page 14 of 86
Object File(.obj) C source program Compiler (.c file)
Execute File (.exe)
Linker
‘C’ Library Files Processor Start program Execution
O/P
Loading Primary Memory (RAM)
Once the coding is completed, the program is feed into the computer using a compiler to produce equivalent machine language code. In ‘c ‘program compilation two parts are there namely Compiler and Linker. The ‘C’ compiler receives source program (file) as input and converts into object file. Then the linker receives this object file and linking with the c libraries after linking it produces a Executable files. After the creation of executable file that starts the program execution and loading the information in to the primary memory through loading process. After loading the information the processor process the information and gives the output.
Basic structure of ‘C’ Language program: [Document Section] Pre-Processor Section or Link Section [Global declaration Section] Main() { [Local Declaration Section]
Page 15 of 86 Statements } [Sub – Programming section] (user defined functions)
Document Section:
This section consists a set of comment lines giving the name of the program author name and some other details about the program.
Link Section (or) Preprocessor Section:
It provides instructions to the compiler to link the functions from the System Library.
Global Declaration Section:
The variables that are used in more than one function are called global variables and these variables are called in the Global Declaration Section.
Main Function Section:
Every ‘C’ program must have one main function. This section consists 2 parts namely 1. Local declaration section. 2. Statements. The local declaration section declares all the variables used in statements. The Statements part consists A sequence of executable instructions. These two
Page 16 of 86 parts must appear between the opening and closing curly brasses “{ }”. The program execution begins at opening bras and ends at the closing bras.
Sub Programming Section: It consist all the user defined function. This section may be placed before or after the main function.
Comments: Un executable lines in a programmer called comments. These lines are skipped by the compiler. C- comments: /*----------------------------------------------------------------- */ (for both multi line and single line comments.)
Note: If c++ editor use single line comments ( // ). // ---------------------
#include: This is a preprocessor file inclusion directive and is used to include header files. It provides instructions to the compiler to link the functions from the system library.
#include “file name” #include When the file name is included with in double quotation marks(“ ” ). The search for the file is made first the current directory and then standard directory, otherwise when the filename included with in “< >” brasses the file is searched only in the standard directory.
Page 17 of 86
Stdio.h ---- standard input output header file. Conio.h ---- Console input output header file. Console units keyboard , monitor. Note: These 2 headers are used commonly in c program
C-Tokens
Tokens: The smallest unit part of a program language, that is not to be divided is called as Token. Every language has it’s own tokens.
General languages tokens:
Alphabets
C-Tokens:
Words
Sentences
Paragraphs
Page 18 of 86
Key Words: Key word is the predefined word, whose definition is already given to the compilers.
There are 32 reserved key words are present in c- language. In “ANSI C” there are some more keywords are present. Ex: Auto, double, long, struct, union, void.
These keywords reduce the stress on the programmer to generate the code.
Identifier:
Identifier is nothing but naming. i.e. The name given to the memory block present in memory( generally main). Identification of every thing such as variables, constants, functions etc are identified by using the identifier only. Syntax:
Page 19 of 86 Type name; Ex: int a; void add();
Rules to write variable names or Identifiers:
A variable name contains maximum of 30 characters. A variable name includes alphabets and numbers, but it must start with an alphabet. It cannot accept any special characters, blank spaces except under score( _ ). It should not be a reserved word(keyword). Variables:Variables are those whose value varies(changes) at the time of program execution. i.e. value in the memory block doesn’t changes.
Syntax: Data_type var_name; Data_type iden-1,iden-2,……..iden-n. Ex: int a; char ch;
Page 20 of 86 Constants:Constant in c refer to fixed value that don’t change during the execution of a program . C supports the following constants. Integer constantans Real Constants Character constants String constants Constants are those whose value does not varies (not changes) at the time of program execution. i.e. value in the memory block doesn’t changes. o o o o
Syntax: const Data_type var_name; Ex: const int a; const char ch; Note: ‘const’ is the keyword to create constants in c-languages. Constants are of 2 types. Namely “Numeric constants” and “Character constants”.
Strings:-
Strings means nothing collection of the Characters. In ‘C’ there is no direct definition for string type. But an array of characters is known as String.
Page 21 of 86 Syntax: char string_name[ size ]; ex: char st[25];
Operators:
It is a symbol and it performs a particular operation. Operant is an entity on which an operator acts. C has a rich set of operators. 1. 2. 3. 4.
Arithmetic operators Logical operators Relational operators Bitwise Operators….etc
Special Characters:
All Characters other than Alphabets and digits are treated as special characters.
Data types:-
The kind of data that variables may hold in programming language is called as data types.
Page 22 of 86
Data types are of 3 data types. 1. 2. 3.
Primary Data Types Derived Data Types User Defined Data Types
Primary Data Types:
All C compliers supports ‘int’,’char’,’float’,’double’.
four
fundamental
data
types
namely
Integer: (int) It is a positive, negative and whole values but not a decimal numbers. Eg: -75, 0 , 25 etc Float: The numbers which are stored in the form of floating point representation is called as float data type. Eg: 10.25, 125.56,0.123,-0.567 Double: The numbers which are stored in the form of double precision floating point representation is called as double data type. Eg: 2367.1234, -12345.687957 etc
Derived Data Types:
Page 23 of 86 These are created from the basic integers, characters and floating data types. The examples of derived data types are Arrays, Pointers, Structures, Unions etc.
User Defined Data Types: The user define data types enable a program to invent his own data types and defined what values it can taken. Thus this data types can help reducing the programming errors. In ‘C’ language 2 types of user define data types are available namely.
Typedef(Type definition) ENUM (Enumerated data type)
Type modifiers or type qualifiers (signed, unsigned, short and long) :
A type modifier alters the meaning of the base data type to yield a new type. Each of these type modifiers can be applied to the base type int. The Modifiers signed and unsigned can also be applied to the base type char. In addition long can be applied to double.
Data Type
Format Specifier
Memory Size (in bytes)
Accessibility Range
unsigned char
%c
1
0 to 255
char
%c
1
-128…..0….127
int
%d
2
-32768 to -32767
unsigned int
%u
2
0 to 65535
long (or) long int
%ld
4
-214783548 to 214783647
unsigned long (or) unsigned long int
%lu
4
0 to 4294967295
float
%f
4
3.4 *(10**-38) to 3.4*(10**38)
double
%lf
8
1.7*(10**-388) to 1.7*(10**388)
long double
%Lf
10
3.4*(10**-4932) to 1.1*(10**4932
char[] -string
%s
Page 24 of 86
Initialization: AT the time of declaring a variable we can store some data into that variable is called as Initialization. Eg: int n=100; float ft=24.67; char ch=’c’; int a=10,b=20; int x=100,y,z;
Sample C Program #include #include void main() { clrscr(); printf(“welcome to c programming”); }
Printf():
It is a function and is used to print data on the standard output device. Declaration: int printf(“Control string”[,arg1,arg2,arg3……]); eg:
Page 25 of 86 printf(“welcome to c programming”);
This printf statements are used to print messages and the value contained in variable on screen. Clrscr(); It clears the text mode window. Declaration: void clrscr(); Note: In c language all the declarations will be done before the executable statement.
Steps to Entering into c editor 1. Double click on desktop turboc++ icon or startmenu-> run>c:\tc\bin\tc.exe and enter. 2. check path options menu->directories -> 1)c:\tc\include 2)c:\tc\lib 3)----4)----Note: It is for if you install the turboc++ software. If not so plz check path c:\tc. 3. 4. 5. 6. 7. 8. 9.
open file menu(alt+f) select new-> type c program save file ‘f2’ or alt+f+c compile {compile menu – select compile option} run {run menu – select run option} output {window menu – select users screen} quit {file menu – select quit option}
Shortcut keys for c editor:
Option
Key
Save
F2
Page 26 of 86
Open
F3
Compile
Alt+ F9
Run
Ctrl+ F9
Output
Alt + F5
Close File
Alt + F3
Full Screen
F5
Switch bet’n 2 windows
F6
Quit
Alt + x
Getch(): It is a function and is used to get a character from keyboard but it does not echo the screen. This is used to reduce the key press of Alt + F5 key to see the output.
Escape Sequence Characters:
Declaration of Constants:
\n
New line
\t
Horizontal tab(8 spaces)
\v
Vertical Tab
\b
Back Space
\r
Carriage written
\a
Alert(Beep Sound)
Page 27 of 86 Constants refers to fixed values that donot change during the execution of a program. Const: It is a key word and is used to define constants Declaration: const datatype identifier=value; or const datatype ide_1=val_1,iden_2=val_2………; eg: const int n=100; const int x=10,y=25,z=50;
Symbolic Constants:
#define: It is a preprocessor statement and is used to define symbolic constants. Syntax: # define identifier value Eg: #define pi 3.14 #define g 9.8 Eg pro: #include #include #define pi 3.14 #define g 9.8
Void main() { clrscr();
Page 28 of 86 printf(“pi = %.2f “,pi); printf(“g = %.1f”,g); getch(); }
Data reading from key board: Scanf: It is a function and is used to read data from standard input device. Syntax: int scanf(“format(s)”,address-1,adress-2…….); Eg: int n; scanf(“%d”,&n);
Note: &n refers the address of variable n, where the value of n to be stored in memory.
fflush: It is a function and it flushes the specified stream Syntax: int fflush( stream_name); eg: fflush(stdin);
flushall: it flushes all open streams. Syntax: int flushall();
Page 29 of 86 Operators in ‘C’
Operator: It is a symbol and it reforms a particular operation. Operand: It is a entity on which an operator acts. Unary Operator: It requires only a single operator. Binary Operator: It requires 2 operators.
C operators can be classified into a no.of categories. They are
1. Arithmetic Operators 2. Relational Operators 3. Logical Operators 4. Assignment Operators 5. Increment and Decrement Operators 6. Ternary Operators( Conditional Operator) 7. Bitwise Operators 8. Special Operators
Arithmetic Operators: These are the basic operators in c language. These operators are used for Arithmetic Operators. “ + ” Addition
Calculates sum
“-”
Subtraction
Calculates Difference
“*”
Multiplication
“/”
Division
Calculates Product Calculates Quotient
Page 30 of 86 “ % ” Modulus
Calculates Reminder
C-Operators Operators are of 8 types. They are as follows.
1) 2) 3) 4) 5) 6) 7) 8)
Arithmetic Operators Relational Operators Logical Operators Assignment Operators Unary Operators Ternary Operators Bitwise Operators Special Operators
Arithmetic Operators: These are the operators used to perform the arithmetic operations. Such that addition, subtraction, Multiplication, division, and modulus(reminder) operators are called as arithmetic Operators. Operator
Symbol
meaning
+
Plus
Addition
-
Minus
Subtraction
*
Asterisk
Multiplication
/
Slash
Division
%
Percentage
Modulus
Relational Operators: These are the operators derives the relation between the operands.
Operator
Meaning
<
Less than
Greater than
>=
Greater than or equal to
Page 31 of 86
==
Equal to
!=
Not equal to
Logical Operators: Logical operators are used to perform nested conditions by combining the statements or conditions. && || true
- Logical AND – true only all conditions are true -
!
Logical OR – true if any one or both of the conditions are
- Logical NOT – Inverse of the statements
P
Q
P&&Q
P||Q
T
T
T
T
T
F
F
T
F
T
F
T
F
F
F
F
Assignment Operators: Assignment operators are used to assign an expression result to a variable. “ = “ symbol is used for assignment Operation. Note: Must assign a known value to a unknown. Ex: a=10. In case of assignment operators we use short hand expressions. a=a+10;
a+=10
a=a-10;
a-=10
a=a*10;
a*=10
a=a/10;
a/=10
a=a%10;
a%=10
Page 32 of 86
Unary Operators: Unary operators are also called as increment/decrement operators. There are 4 unary operators are present.
1) 2) 3) 4)
++var Var++ --var var--
post incrimination pre Incrimination post decrimentation pre Decrimentation
Ternary Operators: Ternary operators are used selection of one expression based on the condition. Syntax: exp1?exp2:exp3; if exp1 is true then exp2 will be executed else exp3 is true.
Bitwise Operators: Bitwise operators are used at registry level operations those are directly connected to the registries. &
Bitwise AND
|
Bitwise OR
>>
shift right
View more...
Comments