PROGRAMMING WITH C&C++
PROGRAMMING WITH C&C++UNIT-1
Posted by Madhuri Gongati
Programming With C
Introduction
to C
The C Language
is developed by Dennis Ritchie
for creating system applications that directly interact with the hardware devices such as drivers, kernels, etc.
C programming is considered as the base for other programming languages, that is why it is known as mother language.
Dennis Ritchie is known as the founder of the c language.
It can be defined
by the following ways:
1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured
programming language
5. Mid-level
programming language
History of C Language
C programming language was developed in 1972 by Dennis Ritchie
at bell laboratories of AT&T (American
Telephone & Telegraph), located in the U.S.A. It was developed to overcome the problems of
previous languages such as B, BCPL, etc. Initially, C language was developed to be used in UNIX operating system. It inherits many features of previous
languages such as B and BCPL.
Let's see the programming languages that were developed before C language.
1.
1960 “ALGOL”(language) is developed by “International Committee”. Remarks: General , Abstract(specific purpose).
2.
1963 “CPL”(Combined Programming Language) is developed at “Cambridge University”.
Remarks: It is hard to learn, it is difficult to implement.
3.
1967 “BCPL”(Basic Combined
Programming Language) is developed at “Cambridge University” by Martin Richards.
Remarks: It is used to solve some specific problems.
4.
1970 “B” is developed at “AT&T Bell laboratories” by “Ken Thompson”.
Remarks: It solve some specific
problems.
5.
1972 “C” is developed
at ”AT &T Bell Laboratories” by “Dennis Ritchie”. Remarks: Last generality
of “BCPL” and “B” restored.
Features of C Language:
C is the widely used language. It provides
many features that are given below.
1. Simple
2. Machine
Independent or Portable
3. Mid-level
programming language
4. structured
programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
1)
Simple: C is a simple language
in the sense that it provides a structured approach (to break the problem
into parts), the rich set of library
functions, data types, etc.
2)
Machine Independent or
Portable: Unlike
assembly language, c programs can be executed
on different machines with some machine specific
changes. Therefore, C is a machine independent language.
3)
Mid-level programming language: Although,
C is intended to do low-level
programming. It is used to develop
system applications such as driver,
etc. It also supports the features of a high-level language. That is why it is known as mid-level language.
4)
Structured programming
language:
C is a structured programming language
in the sense that we can break
the program into parts using functions.
So, it is easy to understand and modify.
Functions also provide code reusability.
5)
Rich Library: C provides a lot of inbuilt functions that make the development fast.
7)
Speed: The compilation and
execution time of C language is fast since there are lesser inbuilt functions
and hence the lesser overhead.
8)
Pointer: C provides the
feature of pointers. We can directly interact with the memory by using the pointers. We can use pointers for memory,
structures, functions, array, etc.
9)
Recursion: In C, we can call the function
within the function. It provides code reusability for every function. Recursion
enables us to use the approach of backtracking.
10)
Extensible: C language is extensible because
it can easily adopt new features.
C fundamentals:
Programming:
Programming is a process to solve a particular problem by using the
computer. When ever we need to
computerize a particular, we have to solve those problems and write these solutions
in the computer understandable code with the help of programming languages.
Program: A program is a group of instructions which is used to perform
particular task. The task’s like big number
out of two numbers, billing process of a hotels
or etc…
Instruction: It is command given to the computer to perform any operation. These instructions may be addition, subtraction, relation between two numbers etc…
Algorithm: A step by step procedure use to perform any task is called
algorithm. Step by step represent of a
program in general format is called algorithm.
Flow chart: A pictorial representation of an algorithm is called flow chart. It
can also show the flow of the
program. Here we can use several symbols for several works in a program.
These instructions and programs can be written in different
languages like C, C++, java etc… these languages are called program languages.
Example of an algorithm:
To find a number is an even or odd. Step1. Start.
Step2. Take a number ‘N’.
Step3. Divide
the number by 2 =>
N/2.
Step4. If the reminder is ‘0’ then goto Step5 other wise goto Step6. Step5.
Print the number is even. goto Step7.
Step6. Print the number is odd.
Step7. Stop.
PROGRAMMING LANGUAGES:
MACHINE, ASSEMBLY
AND HIGH-LEVEL LANGUAGE
It is a computer’s natural
language, which can be directly
understood by the system. This
language is machine dependent, i.e. it is not portable. A program written in 1s and 0s is called a machine language.
A binary code is used in a machine
language for a specific operation. A set of instructions in binary pattern
is associated with each computer. It is
difficult to communicate with a computer
in terms of 1s and 0s. Hence writing a program with a machine language is very
difficult.
ASSEMBLY LANGUAGE
Instead of using a string of binary bits in a machine language,
programmers started using
English like works as commands that can be easily interpreted by programmers. The designer
chooses easy symbols that are to be remembered by the programmer, so that the programmer can easily develop the program
in assembly language. The
alphanumeric symbols are called
mnemonics in the assembly language. The
ADD, SUB, MUL, DIV, RLC and RAL are
some symbols called mnemonics.
The programs written in other than the machine language need to be
converted to the machine language.
Translators are needed for conversion from one language to another. Assemblers are used to convert
assembly language program to machine language.
HIGH LEVEL LANGUAGE
Procedure-oriented languages are high-level language. These languages are employed for easy and speedy development of a
program. The disadvantages observed
with assembly languages are overcome
by high-level languages. The
programmer does not need to remember the
architecture and registers of CPU for developing a program. The compilers are used to translate high-level languages program to
machine language. Examples of HLL are
COBOL, FORTRAL, BASIC, C
and C++.
ASSEMBLER,COMPILER, INTERPRETER:
A program is a set of instructions for performing a particular task
.These instructions are just like
English words . the computer interprets the instructions as 1’s and 0’s. A
program can be written in assembly
language as well as in high level
language. This written program is called the source program. The source
program is to be converted to the machine language, which is called an object program.
A translator is required for such a translation.
A programming language translators are classified as follows. A list
of translators is given is given
below.
1.
Assembler
2.
Compiler
3.
Interpreter
ASSEMBLER:
An assembler translates the symbolic codes
of programs of an assembly
language into machine language instructions.
COMPLIER: Compliers are the translators, which
translate all the instructions of the program into machine which can be used
again and again. The compiler displays the list of errors and warnings
for the statements violating the syntax rules of the language.
INTERPRETER: Interpreters also come in the group of translators. It helps the
user to execute the source program.
STRUCTURE OF A ‘C’ PROGRAM:
Every c program
contains a number of building
blocks known as functions. Each functions of it performs
a specific task independently. The ‘C’ structure
is as follows:
Include header file section Global declaration section
/* comments*/ void main()
{
Declaration part; Executable
part;
}
User – defined functions
{
Body of the function
}
i)
Include Header file section:
C program
depends upon some header files for function definition that are used in the
program. Each header file has extension ‘.h’. The header files are included at the
beginning of the program. These files
should be included using #include. Eg: #include<stdio.h>
ii)
Global Declaration: This section declares some
variables that are used in more than one
function. These variables are known as global variables. This section must declare outside of all the functions.
iii)
Function main(): Every program written in C
must contain main() and its execution starts
at the beginning of this function. Void
main() means this function returns nothing and takes
no arguments.
iv)
Declaration part: The declaration part
declares the entire local variables that are
used in executable part. Local variables scope is limited to that
function where the local variables
are declared. The initialization of variable can also be done in this section.
v)
Executable part: This part contains the
statements following the declaration of the variables. This part contains
a set of statements or a single
statements.
vi)
User defined function: The function defined by
the user are called user- defined functions. These functions are defined outside
the main() function.
vii)
Body of the function:
the statements enclosed within the body of the function(between opening and closing braces) are called body of the function.
viii)
Comments: Comments are not necessary
in . However to understand the flow of program a programmer can insert comments
in the program.
Example program
for structure of C-program:
/* Example program */ /*
Documentation section */ #include<stdio.h> /* Linking section*/ #define a 10 /* Definition section */
int b; /* Global
variable declaration */ void main() /* Main function */
{
int c; b=10;
c=a+b;
printf(“Sum
: %d”,c); sub(b);
}
void sub(int y) /*
(Sub program or function) */
{
int z; / * Local variable
declaration for function
*/ z=a-y;
printf(“Subt : %d”,z);
}
Programming rules:
A programmer while writing program
should follow following rules.
i)
Every program should have main() function
ii)
C statements should be he terminated by a semi-colon.
iii)
All statements should
be written in lower case letters. Generally
uppercase letters are used only for symbolic
constants.
iv)
Blank spaces may be inserted between
the words.
v)
The opening and closing braces should be balanced, i.e. if opening
braces are four. Then closing braces should also be four.
Compiling program:
Compiling of c- program
is nothing, to generate
binary code file of our program to execute the program,
with the help of compiler.
The steps involved to create a program in C-language are entering program, compiling program
and running program. The program is typed in the
computer with the help of editor.
Editor: Editors provide space to write our program in computer. We can also open the existed programs in the computer. The text editors
are usually used to
write C-programs in to
file.
vi) Source program:
The program that is entered into the file is known as the source program.
We have to follow several
steps to write,
compile and a program in C-programming language. They are:
v Open the C-programming language editor.
v Write your program
or open an existing program
in the system.
v
When you create a new program, you have to save the program with a specific name. We have to follow the naming conventions (rules) to give name for C-program.
v
Give the file name with the extension ‘.C’. This extension
represents a file as a C-Program file.
v
After saving the program, compile the program.
The compilation process depends on the editor
or running machines operating system.
v
For example, if we want to run our program in dos operating system,
we have to follow several
steps to compile the program.
o
Go to compile menu in editor.
o
Then chose ‘compile
to obj’ command or press ALT+F9 key combination from the key board.
o
The compiler
will compile the program
v
The compiler will give
the syntax errors in our program. If we have any errors or warnings we have to
rectify the errors, then open our source program, correct the errors then do the compile process
again.
v
Whenever we have an error free program then the compiler can
create a .OBJ(object) file for machine.
It is also called binary code file.
v
After creating the .OBJ
file then run the program,
go to run menu and choose run command or press
CTRL+F9 key combination from the keyboard.
v
Whenever run a program the linker links the .OBJ file and
library files then create .EXE (executable) file, execute the program by using this .EXE file.
Linker: It also a software program. By using this compiler links the OBJ
file and library files the produce executable file this process is called building.
v
Whenever execute our program, the steps in the program is
executed sequentially this process is
called top down approach. If our program get any data from the user is called input,
then process the input and displays result on the output screen.
If the output is
correct then completed our task otherwise open the program
change the logic according to our requirement.
First C Program
To write the first c program,
open the C console and write the following
code:
1. #include
<stdio.h>
2. void main(){
3. printf("Hello C
Language"); 4. }
#include <stdio.h> includes the standard input output library functions. The printf() function is defined in stdio.h .
The main() function is the entry point of every program
in c language.
printf() The printf() function
is used to print data on
the console.
How to compile and run the
c program
There are 2
ways to compile and run the c program,
by menu and by shortcut.
By menu
Now click on the compile
menu then compile
sub menu to compile the c program.
Then click on the run menu then run sub menu to run the
c program.
By shortcut
Or,
press ctrl+f9 keys
compile and run the program
directly. You will see
the following output on user screen.
You
can view the user screen any time by pressing
the alt+f5 keys.
DATA TYPES:
C
language is rich in its data types. ‘C’ language supports the following data types.
DATA TYPES
Primary |
Derived |
User Defined |
char |
arrays |
enum |
Integer |
pointers |
structure |
Float Double |
functions |
typedef union |
1.
Scalar/ standard/ primary/
fundamental data types:
Basic data types is used for representing a single value only. It is only called simple or fundamental data type.
Size and range of basic data types:
Data type Size Range of value
char 1
byte -128 to 127
int 2
bytes -32,768 to 32,767
float 4
bytes 3.4e-38 to 3.4+38
double 8
bytes 1.7e-308 to 1.7e+308
Void:
Void or empty data type is used in programs. Void is a datatype which does not returns
any value.
2.
Derived data types:
Derived data types are derived from the scalar data type by adding
some additional relationship with the
various elements of the primary or scalar data types. Note that derived data type may be used for representing a
single value or multiple values. These are further sub divided into three categories.
1.
Array and strings 2. functions 3. pointers
(a). Arrays: An Array is nothing but a collection of sequence of
homogeneous(similar) data type
elements.
Declaration of an array:
Data type variable-name [size];
Where datatype can be any primary or secondary . Size is any integer.
Example: int a[50];
b) Pointer data type:
Pointer data type is used to handle the data at their memory
address.
3.
User defined type:
This is also used for definition, i.e. it allows the users to define a variable or an identifier, which is
used for representation of existing
data types.
a) enum: Another user defined data type is enumerated data type provided
by ANSI standard. Syntax: enum identified {value1, value2…..} variable;
The identifier is a user- defined enumerated data type, which can be
used to declare variables
that can have one of the values enclosed within the braces known as enumeration constant.
Example: enum day{Monday, Tuesday, Wednesday,..}
d;
b).
typedef: Supports a feature know
“type definition” that allows user to define an identifier that would represent an existing data
type. The user-defined data type identifier can later to declare variable.
Syntax: typedef
data_type identifier;
Where type represents the data type of the identifier refers to the
‘new’ name giving to the date type.
Ex: typedef int marks;
Here marks symbolize
int. they can be later used to declare variable
as follows. marks m1,m2;
m1,m2 are declared as int variable. The main advantage of typedef is
that we can create meaningful data type
names for increasing the readability of the
program.
c).
Structure: A Structure is nothing but
a collection of heterogeneous (different) of elements. Declaration of structure:
Struct tage_name
{
datatype field1; datatype field2;
……………… datatype field n;
};
Where tag name is the name of the structure / datatype can be any primary or secondary datatype.
Example: struct student
{
int
sno;
char name[10]; float m1,m2,m3;
};
Once the structure
data type is defined, the variable of that datatype
can be declared of follows.
Syntax: struct tagname
variablelist; Example: struct student s;
DECLARING VARIABLES:
The declaration of variables should
be done in declaration part of the program. The variables
must be declare before they are used in the program. Declaration ensures two things
i)
Compiler obtains
the variable name
ii)
It tells to the compiler
data type of the variable
being declared and helps in the
allocating the main.
Syntax : data type variable name;
Float m;
INITIALIZING VARIABLES:
Variables declared can be assigned
or initialized using assignment operator
‘=’ the declaration and initialization can also be done
in the same line.
int y=4;
Types of Operators:
1. Arithmetic 2. Relational 3. Logical 4. Assignment
5. Increment and decrement 6. Conditional 7.
Bitewise 8. Special
1.
Arithmetic Operators: Arithmetic operators are used for arithmetic operations like Addition,
Subtraction, Multiplication, Division
etc.
·
If all operands are integers, the result is an integer.
|
If an operand is a floating point or double precision value, the result is a double
2. Relational Operators: We often compare two quantities, and depending on their relation,
take
Operator |
Meaning |
< |
Is less
than |
<= |
Is less than or equal to |
> |
Is greater than |
>= |
Is
greater than or equal to |
= = |
Is
equal to |
!= |
Is not equal to |
1. LogicalOperators: An expression,
which combine
two or more
relational expression, is termed as a logical
expression.
Operator Meaning
&& AND
|| OR
! NOT
Logical Table:
A |
B |
A AND B |
A OR B |
NOT A |
T |
T |
T |
T |
F |
T |
F |
F |
T |
F |
F |
T |
F |
T |
T |
F |
F |
F |
F |
T |
Operator | Description | Example |
---|---|---|
= | Simple assignment operator. Assigns values from right side operands to left side operand | C = A + B will assign the value of A + B to C |
+= | Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. | C += A is equivalent to C = C + A |
-= | Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. | C -= A is equivalent to C = C - A |
*= | Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand. | C *= A is equivalent to C = C * A |
/= | Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. | C /= A is equivalent to C = C / A |
%= | Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. | C %= A is equivalent to C = C % A |
Conditional Operator in C
The conditional operator is also known as a ternary operator. The conditional statements are the decision-making statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?' and ':'.
As conditional operator works on three operands, so it is also known as the ternary operator.
The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement is also a decision-making statement.
Syntax of a conditional operator
BITWISE OPERATORS
- The & (bitwise AND) in C or C++ takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
- The | (bitwise OR) in C or C++ takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 if any of the two bits is 1.
- The ^ (bitwise XOR) in C or C++ takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.
- The << (left shift) in C or C++ takes two numbers, the left shifts the bits of the first operand, and the second operand decides the number of places to shift.
- The >> (right shift) in C or C++ takes two numbers, right shifts the bits of the first operand, and the second operand decides the number of places to shift.
- The ~ (bitwise NOT) in C or C++ takes one number and inverts all bits of it.
Size of ()operator:
The sizeof() is a compile time operator and, when used with an
operand, it returns the number of
byte the operand occupies. The operand may be a variable, a constant or a data
type qualifier.
Syntax: Variable=sizeof(v or e)
Example: int a;
K=sizeof(a) the value of k is 2 (because
a occupies two bytes of memory)
CONTROL STSTEMENTS
Normally C-compiler executes all the statements in the program
sequentially (one after other ) or
conditionally or Iteratively (more than one time) to handle such type of
statements ‘flow controls ‘ are
required. They can be also said as
control statements. Control
statements are used to control the
cursor in a program according to the condition or according to the required
loop. There are mainly three types of control
statements they are.
1.
Branching
2.
Looping statements.
3. Jumping statements
IF conditional statement:
‘ If ’ is one of the
keyword in the C-language, by using this we make some controls on the execution of program. The general syntax
of the ‘if’ is:
if(condition)
{
Executable Statements;
}
In the above syntax ‘if ‘ is a key word. The condition is following
by the keyword if. Whenever the
condition comes to execution, if the given condition true, it will return 1 to
if statement. If the given condition
is false, it will return 0 to if
statement. We have several form of if statements in C-language. They are:
1.
Simple if.
2.
if else.
3.
else if or else if ladder.
4. Nested if
C if Statement
The
syntax of the if statement in C programming is:
if (test
expression)
{
// code
}
How if statement works?
The if statement evaluates the
test expression inside the parenthesis ().
·
If the
test expression is evaluated to true, statements inside the body of if are executed.
·
If the
test expression is evaluated to false, statements inside the body of if are not executed.
C if...else Statement
The if
statement may
have an optional else
block. The
syntax of the if..else
statement is:
if (test expression) {
// run code if
test expression is true
}
else {
// run code if
test expression is false
}
C if...else Ladder
The if...else statement executes two different codes
depending upon whether the test expression is true or false. Sometimes, a
choice has to be made from more than 2 possibilities.
The if...else ladder allows you to check between multiple
test expressions and execute different statements.
Syntax
if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
}
.
.
else {
// statement(s)
}
Nested if
t is
possible to include an if...else statement inside the body of another if...else statement.
SYNTAX:
if(condition)
{
if(condition)
{
//ststement
}
}
LOOPING STATEMENTS
for Loop
Syntax
for (initializationStatement; Condition; inc/dec)
{
// statements
inside the body of loop
}
Example :
// Print numbers from 1 to 10
#include <stdio.h>
int main() {
int i;
for (i = 1; i <
11; ++i)
{
printf("%d
", i);
}
return 0;
}
while loop
The syntax of the while loop is:
while (condition)
{
// the body of the
loop
}
// Print numbers from 1 to 5
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
++i;
}
return 0;
}
do...while loop
The do..while loop is similar to the while loop with one
important difference. The body of do...while loop is executed at least once.
Only then, the test expression is evaluated.
Syntax
do {
// the body of the
loop
}
while (Condition);
// Program to add numbers until the user enters zero
#include <stdio.h>
int main() {
double number, sum =
0;
// the body of the loop is executed at least once
do {
printf("Enter
a number: ");
scanf("%lf", &number);
sum += number;
}
while(number !=
0.0);
}
JUMPING STATEMENTS
break
The break statement ends the loop immediately when it is encountered.
syntax
The break statement is almost always used with if...else
statement inside the loop.
Continue
The continue statement skips the current iteration of the
loop and continues with the next iteration. Its syntax is:
continue;
The continue statement is almost always used with the
if...else statement.
C goto Statement
The goto statement allows us to transfer control of the
program to the specified label.
Syntax
goto label;
... .. ...
... .. ...
label:
statement;
The label is an identifier. When the goto statement is
encountered, the control of the program jumps to label: and starts executing
the code.
C switch Statement
The switch statement allows us to execute one code block
among many alternatives.
You can do the same thing with the if...else..if ladder.
However, the syntax of the switch statement is much easier to read and write.
Syntax of switch...case
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default
statements
}
Comments
Post a Comment