unit-2 programming language 'c' · 2018. 7. 29. · c, c++, basic, cobol, pascal fortran....
TRANSCRIPT
UNIT-2Programming language 'C'
Contents
Types of Programming Languages : 1. Machine-level,2. Assembly,3. High level languages.
Features of C : basic concepts, structure of a C program, declarations,
Data types : Variables, expressions, conditional expressions.
Operators : Assignment, Arithmetic, Relational, Logical, Increment and Decrement, Precedence of operators, Type conversions,
I/O Function : scanf and printf functions.
Programming Language
A programming lang. is the lang. used tocommunicate instructions to the machine i.e.Computer.
Ex. C, C++, Basic, Cobol, Pascal Fortran.JAVA, JAVA Script.VB, VB .NETPHPC#PythonSQL
Types of Programming Languages
1. Machine-level Languages2. Assembly Languages3. High level Languages
Machine-level or Low Level Languages
series of sequence of 1 & 0 as instructions.This is the only lang. understand by computer.
These are machine dependent lang.Machine language instructions has two parts
1. Opcode ( Operation Code):Tells the computer which operation to perform.2. Operand : It tells where to find or store the
data to be manipulated.
M
a
c
h
i
n
e
C
o
d
e
s
Advantages Of Machine Languages
Only languages understand by computerSimply understandable for computerIt does not require any translator to translate
code.Limitation Of Machine Languages
Difficult for userAll opcode and addresses must rememberError finding is difficult as it is written in 0&1Writing program it takes huge time.
Assembly Language
Low Level programming developed to overcomeinconveniences of machine lang.
In assembly lang. operation codes and operands aregiven in the form of alphanumeric symbols insteadof binary nos. 1&0. These symbols are also called asmnemonic codes.
This is also machine dependent.Assembly language programming Are translated into
executable machine code by using assembler.
Assembly language program
AssemblerMachine Code (Object Code)
Assembly Language Program
High Level Lang
Designed to enable people to write program Easily& in their own native lang. i.e. English.
Uses English/ mathematical symbol.
Deals with arrays, variables, objects, arithmetic etc.HLL Progam must to translated into machine
language by using compiler or interpreter.
The first HLL designed in 1950sEx. C, C++, Basic, Cobol, Pascal Fortran.JAVA, JAVA Script.VB, VB .NET
Scripting Language
These lang. can be executed without explicit compilation and linking.
Scripting lang. are interpreted rather than complied.These are used in Web Development for
validation control etc.E.g. Java Script, VB Script, ASP, JSP, PHP, Perl, Ruby, Shell, Phyton.
Advantages
It is easier to write code.Editing & running scripting code is fast.
Limitation :
SlowerHarder to debug as no development environment is available by default.All scripting lang. are not supported by all the systems.
Natural Languages
Natural lang. is the lang. which acquired naturally.
This is typically used for human communication
No training is required for these lang.
E.g English, French, Chinese etc.
Characteristics of Good Programming
Language
Simple & readable
Portable : Language should be machine independent
General: Programming language should allow writing
wide variety of programs so that the programmer can
become expert in many languages.
Widely Available
Efficient
Abstract
Selecting Programming Language
The targeted platform where the programming Will
run
The elasticity of a lang. in which new features can be
added to the existing programming
The performance
Community support.
Environment: Platform, Web, Network Scientific,
General etc.
Subprogram (function)
Suppose we want to add two nos. then we have to write
programming For it., Again suppose we want to
perform the subtraction then again we need to write the
same code. So it will increase the programming Size.
To avoid this we can write subroutine(subprogram)
which is a part of main program.
These are nothing but the set of instructions to do the
specific task send result back to main program.
Some HLL language
FORTRAN : FORmula TRANslation. Developed by IBM
in 1957. It is a SCIENTIC LANGUAGE. The versions are
FORTRAN 66,77.
COBOL : Common Business Oriented Language. It is
developed by a group of computer professionals called
Conference on Data Systems Language ( CODASYL) in
1959. Its primary domain is business, finance and admin.
BASIC: Beginners All Purpose Symbolic Instruction Code.
It is a first HLL which used on the personal computers.
SNOBOL: StriNg Oriented and SymBOlic Language
Developed in 1962 in Bell Labs
C++, Java, C# : Object Oriented Languages
Lisp
Lisp: Means List Processing Language
This is second oldest HLL than ForTran
Lisp was originally created as a
Practical mathematical notation for computer
programs
In 1956 John McCarthy first developed the basics
behind lisp.
In 1965 the primary dialect of LISP was created.
In 1980 OOPS concepts are added.
List of Interpreter are : Emacs, Omega, LispWorks
MatLab
It stands for Mathematics Laboratory.
This is not Open Source.
This is developed by MathWork
Company.
This lang. is basically used for Research
Purpose.
It has different tool box like Image
Processing, Wireless Network, Neural
Network.
Octave (Gnu Octave)
This open source.
This is equivalent to MATLAB.
All commands which work in MatLab can work in Octave.
GNU Octave is a high-level interpreted language, primarily
intended for numerical computations. It provides capabilities for
the numerical solution of linear and nonlinear problems, and for
performing other numerical experiments. It also provides
extensive graphics capabilities for data visualization and
manipulation. Octave is normally used through its interactive
command line interface, but it can also be used to write non-
interactive programs. The Octave language is quite similar to
Matlab so that most programs are easily portable.
What is ‘C’ ?
C is programming language developed at
AT&T’s Bell Laboratory of USA in
1972.
It was written by Dennis Ritchie.
C is popular because it is reliable, simple
and easy to use. In Industry so many new
languages coming and out in years but is
till popular since 4-5 decades.
Features of C
Currently, the most commonly-used language
for embedded systems
“High-level assembly”
Very portable: compilers exist for virtually
every processor
Easy-to-understand compilation
Produces efficient code
Features of C
C is the most popular programming language, C has many
advantages:
Modularity:
modularity is one of the important characteristics of C. We
can split the C program into no. of modules instead of
repeating the same logic statements (sequentially). It
allows reusability of modules.
Middle level language:
as a middle level language C combines both the
advantages of low level and high level languages. (arrays,
pointers etc).
General purpose programming language:
C can be used to implement any kind of applications
such as math’s oriented, graphics, business oriented
applications.
Portability: we can compile or execute C program
in any operating
system(unix, dos, windows).
Powerful programming language: C is very
efficient and powerful
programming language, it is best used for data
structures and designing system software.
Basic Concepts of C Programming
Language
There are 3 types of Computer wares.
1. Human ware:
The person, who can use the system, is called 'Human
Ware ". He is also called as "User".
2. Hardware :
The physical components (devices) of a system are
called "Hardware".
Eg. Monitor, CPU, Keyboard, Mouse etc.
3. Software :
Def: Set of related programs is called “Software".
Translators
Assembler:
It is translating software. It translates assembly code to binary and vice versa.
Compiler / Interpreter:
Both are translating soft wares. Those can translate high level language to binary language and vice versa.
Compiler can process a whole file at a time and it provides .exe files. But, Interpreter can process a file line-by-line only. It does not provide .exe files. This is the main difference between them.
Learning Steps in 'C' :
1. Character Set
2. Word
3. Instruction
4. Program
5. Software
Character Set :
Def: All allowable symbols in this language are
called "Character set". The following characters
are used in this language.
Lower case letters : a b c … z
Upper case letters : A B C….Z
Digits : 0 1 2 3…9
Other characters : + - * ( ) & % $ # { } [ ]’ “ : ; etc.
White space characters : blank, new line, tab space
etc.
Word:
Def: Group of characters is called a 'Word'.
There are 3 types of words in C.
1. Keyword 2. Variables and / or Identifiers 3. Constants
Instructions:
Def: Collection of words has returns a complete meaning and ends with a semicolon (;) is called an Instruction.
Types of Instructions
1. Type declaration Instructions:
Any variable is used in a program that must be declaring
its data type before using it.
syn:
datatype var1, var2 , ...;
Eg.
int a;
float data;
Char grade;
Types of Instructions
2. I/O Instructions:
To read data from key board (std. input device) using a
statement. That is called "Input instruction".
To display the information on the monitor (std. output
device) using a statement. That is called "Output
Instruction".
Syn:
scanf ( ) ; : This is the standard input instruction in C.
printf ( ) ; : This is the standard output Instruction in C.
3. Arithmetic instructions:
Def: These instructions can perform Arithmetic
calculations.
Eg.
c = a+b;
gross = basic + hra +da; etc.
4. Control instructions:
Def: To control the flow of execution of the
program using certain statements are called
"Control Instructions ".
Eg.
if statement, looping statements etc.
#include <stdio.h> void main(){
printf("Hello, World! \n");
}
Preprocessor directive
Main function of program
Function used for
printing out data on
screen
Escape Sequences Character
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\‘ Single quotation mark
\“ Double quotation mark
\? Question mark
\0 Null character
Keywords in C
Identifiers
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,
Digits (0 to 9)
C does not allow punctuation characters such
as @, $, and % within identifiers.
C is a case-sensitive programming language.
mohd
a23b9
Here are some examples of acceptable identifiers −
mohd
zara
abc
move_name
a_123
myname50 _temp
j
a23b9
retVal
mohd
a23b9
C - Data Types
Data types in c refer to an extensive system
used for declaring variables or functions ofdifferent types.
C Data Types
C - Data Types
Type Format Spacifier Storage size Value range
char %c 1 byte -128 to 127 or 0 to 255
int %d 2 bytes -32,768 to 32,767
unsigned int %d 2 bytes 0 to 65,535
short %d 2 bytes -32,768 to 32,767
unsigned
short%d 2 bytes 0 to 65,535
long %ld 4 bytes -2,147,483,648 to 2,147,483,647
float %f 4 byte 1.2E-38 to 3.4E+38
double %lf 8 byte 2.3E-308 to 1.7E+308
long double %Lf 10 byte 3.4E-4932 to 1.1E+4932
C program for addition of two numbers
#include <stdio.h>
void main()
{
int a,b,c;
C=a+b;
printf(“Addition is : %d \n", c);
}
Get the size of int type on any machine
#include <stdio.h>
int main()
{
printf("Storage size for int : %d \n", sizeof(int));
return 0;
}
C - Variables
A variable is nothing but a name given to a storage area that
our programs can manipulate. the following basic variable
types
Type Description
charTypically a single octet(one byte). This is an integer
type.
int The most natural size of integer for the machine.
float A single-precision floating point value.
double A double-precision floating point value.
void Represents the absence of type.
Syntax:
type variable_list;int i, j, k;
char c, ch;
float f, salary;
double d;
C - Variables
In C programming, variables or memory
locations should be declared before it can be
used.
Similarly, a function also needs to be declared
before use.
Data types simply refers to the type and size
of data associated with variables and
functions.
Defining Constants
There are two simple ways in C to define
constants −
Using #define pre-processor
Syntax:
#define Identifier = Value;
Using const keyword
const Data type Identifier = Value;
Defining Constants
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
Defining Constants
#include <stdio.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
Variables
Local variables:
•Existence is only to the main program or
functions are called local variables.
•Local variables are declared with in the main
program or a function.
Global variables:
•Existence is to the both main() as well as other
functions are called global variables.
•Global variables are declared outside the
main() and other functions.
OperatorsAn operator is a symbol that tells the compiler to perform
specific mathematical or logical operation.
Operators are classified into 3 categories.
1. Unary Operators: Single operand with an operator is
called “Unary Operators”.
Unary Operation
Increment and Decrement operators.
Casting Operating.
Address of Operator
Value of Operator
Scope Resolution Operator.
Size of Operator
Operators2. Binary Operators: Two operands with an operator are
called “Binary Operators”.
Arithmetic Operator.
Logical Operator.
Bitwise Operator.
Relational Operator.
Arithmetic Operators
Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from the
first.
A − B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B / A = 2
% Modulus Operator and remainder of
after an integer division.
B % A = 0
++ Increment operator increases the
integer value by one.
A++ = 11
-- Decrement operator decreases the
integer value by one.
A-- = 9
Bitwise Operators : are used to perform binary
arithmetic.
~ Not
& AND
| OR
^ Xor
<< Shift left
>> Shift Right
~= Not Assignment
&= And Assignment
^= Xor assignment
|= Or assignment
<<= Shift left assignment
>>= Shift Right assignment
Logical Operators :
Operator Description Example
&&Called Logical AND operator. If both the
operands are non-zero, then thecondition becomes true.
(A && B) is false.
||Called Logical OR Operator. If any of
the two operands is non-zero, then thecondition becomes true.
(A || B) is true.
!
Called Logical NOT Operator. It is used
to reverse the logical state of its
operand. If a condition is true, thenLogical NOT operator will make it false.
!(A && B) is true.
Relational : Used to perform comparison. Relational
operators always results in Boolean value either 1 TRUE or 0 FALSE. Following is the list
Operator Description Example
== Checks if the values of two operands are
equal or not.
(A == B) is not true.
!= Checks if the values of two operands are
equal or not.
(A != B) is true.
> Checks if the value of left operand is greater
than the value of right operand.
(A > B) is not true.
< Checks if the value of left operand is less
than the value of right operand
(A < B) is true.
>= Checks if the value of left operand is greater
than or equal to the value of right operand.
(A >= B) is not true.
<= Checks if the value of left operand is less
than or equal to the value of right operand.
If yes, then the condition becomes true.
(A <= B) is true.
Bitwise Operator
Bitwise operator works on bits and perform bit-by-bit operation.
p q p & q p | q p ^ q
AND OR Ex- OR
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Operators
3. Ternary Operators: Three expressions with an operator
are called “Ternary operators”. Ex. Ternary operators.
Syntax:
Condition ? True Value : False Value
Ex.
g = (x < y)? x:y
Assignment Operators
Operator Description Example
= Simple assignment operator C = A + B will assign
the value of A + B to C
+= Add AND assignment operator. C += A is equivalent to
C = C + A
-= Subtract AND assignment operator. C -= A is equivalent to
C = C - A
*= Multiply AND assignment operator. C *= A is equivalent to
C = C * A
/= Divide AND assignment operator. C /= A is equivalent to
C = C / A
%= Modulus AND assignment operator. C %= A is equivalent
to C = C % A
Precedence of operators
Operator precedence determines the sequence of
operation priority in which an expression is evaluated.
Certain operators have higher precedence than
others.
for example, the multiplication operator has a higher
precedence than the addition operator.
For example,
x = 7 + 3 * 2; here, x is assigned 13, not 20 because
operator * has a higher precedence than +, so it first gets
multiplied with 3*2 and then adds into 7.
Hierarchy of Operation
Priority Operators Description
First * / %
Second + -
Third =
The Operations in Paranthesis has the highest
priority. Then Above same rules are applied
Associativity
Operator Category Associatively
Unary (++,--) R->L
Arithmetic(*,/,%) L->R
Arithmetic(+,-) L->R
Relational L->R
Equality L->R
Logical R->L
Assignment R->L
Precedence of operators
Type Conversion / Type Casting Type casting is a way to convert a variable from one data type to another data type. There are two types of type casting in c language.
Implicit conversionImplicit conversions do not required any operator forconverted. They are automatically performed when a value iscopied to a compatible type in program.Explicit conversionIn c language , Many conversions, specially those that imply adifferent interpretation of the value, require an explicitconversion.
Syntax: (Data_type) Identifier.Example: y = (int) x
Implicit Conversion#include <stdio.h>
void main()
{
int i = 17;
int sum;
char c = 'c'; /* ASCII value of c is 99 */
sum = i + c;
printf("Value of sum : %d\n", sum );
}
Output :-
Value of sum : 116
Explicit Conversion#include <stdio.h>
void main()
{
int i = 17;
float j = 38.34;
int sum;
sum = i + (int) j ;
printf("Value of sum : %d\n", sum );
}
Output :-
Value of sum : 50