Paper DSC 203:PROGRAMMING WITH C & C++
UNIT-I: INTRODUCTION TO C LANGUAGE, VARIABLES, DATA TYPES AND OPERATORS INTRODUCTION: TYPES OF LANGUAGES- HISTORY OF C LANGUAGE – BASIC TRUCTURE –PROGRAMMING RULES – FLOW CHARTS-ALGORITHMS–COMMONLY USED LIBRARY FUNCTIONS - EXECUTING THE C PROGRAM - PRE-PROCESSORS IN “C”- KEYWORDS & IDENTIFIERS – CONSTANTS – VARIABLES: RULES FOR DEFINING VARIABLES - SCOPE AND LIFE OF A VARIABLE–- DATA TYPES - TYPE CONVERSION - FORMATTED INPUT AND OUTPUT OPERATIONS. OPERATORS: INTRODUCTION – ARITHMETIC – RELATIONAL – LOGICAL – ASSIGNMENT - CONDITIONAL - SPECIAL - BITWISE - INCREMENT / DECREMENT OPERATOR.
UNIT-II: WORKING WITH CONTROL STATEMENTS, LOOPS CONDITIONAL STATEMENTS: INTRODUCTION - IF STATEMENTS - IF-ELSE STATEMENTS – NESTED IF-ELSE – BREAKSTATEMENT-CONTINUE STATEMENT-GO TO STATEMENT-SWITCH STATEMENTS. LOOPING STATEMENTS: INTRODUCTION-WHILE STATEMENTS – DO-WHILE STATEMENTS - FOR STATEMENTS-NESTED LOOP STATEMENTS.
UNIT-IV: POINTERS, STRUCTURES AND UNIONS POINTERS: FEATURES OF POINTERS- DECLARATION OF POINTERS-ARITHMETIC OPERATIONS WITH POINTERS STRUCTURES: FEATURES OF STRUCTURES - DECLARING AND INITIALIZATION OF STRUCTURES –STRUCTURE WITHIN STRUCTURE- ARRAY OF STRUCTURES- ENUMERATED DATA TYPE-UNIONS-DEFINITION AND ADVANTAGES OF UNIONS COMPARISON BETWEEN STRUCTURE & UNIONS.
UNIT-V: OBJECT ORIENTED CONCEPTS USING C++ OBJECT ORIENTED PROGRAMMING: INTRODUCTION TO OBJECT ORIENTED PROGRAMMING - STRUCTURE OF C++ – SIMPLE PROGRAMOF C++– STORAGE CLASSES-SIMILARITIES AND DIFFERENCES BETWEEN C & C++ - DATA MEMBERS-MEMBER FUNCTIONS - OBJECT ORIENTED CONCEPTS-CLASS-OBJECT-INHERITANCE- OLYMORPHISM- ENCAPSULATION-ABSTRACTION.
UNIT-I
INTRODUCTION
TO C LANGUAGE, VARIABLES,
DATA TYPES AND OPERATIONS
History
of C language
1.Explain
History and Features of C language?
Ans:
C is
a programming language which born at “AT & T’s Bell Laboratories” of USA in
1972. It was written by Dennis Ritchie. This language was created for a
specific purpose: to design the UNIX operating system (which is used on many
computers). In the late 70’s C began to replace widespread well-known languages
of that time like PL/I, ALGOL etc. Programmers everywhere began using it
to write all sorts of programs. Soon, however, different organizations began
applying their own versions of C with a subtle difference. This posed a serious
problem for system developers. To solve this problem, the American National
Standards Institute (ANSI) formed a committee in 1983 to establish a standard
definition of C.
· UNIX
developed c. 1969 -- DEC PDP-7 Assembly Language
· BCPL
-- a user friendly OS providing powerful development tools developed from BCPL.
Assembler tedious long and error prone.
· A
new language ``B'' a second attempt. c. 1970.
· A
totally new language ``C'' a successor to ``B''. in 1972
· By
1973 UNIX OS almost totally written in ``C''.
Features
of C Language:
1.Generality C
language is general purpose language .It is used to write simple programs to
complex. It is used to develop many applications.
2.Middle
level language C language has capabilities like high
level language and high level language. C language can be used to write system
software as well as application software.
3.Extensive
library functions C
language has a huge set of built in library functions that makes it a robust
language. Any complex programs can be easily written using these library functions.
4.Poratabilty C
language is portable. It means that the programs written on one machine can be
executed on different machine with or without minor changes in the program.
5.Structured
Programming C programs can be collection of function modules and
blocks.
6.Efficiency and speed C language has rich set of data types and operators that makes the language more efficient and fast.
Basic Structure
2.Explain
Basic Structure of C Program?
C Program consists of various sections which can be as follows
·
· The
link section provides instructions to the compiler to link functions from
system library.
· C
program depends upon some header files for function definition .Each header
file by default is extended with .h
· The
definition section defines all symbolic constants.
· There
are some variables that are used in more than one function such variables are
called global variables. And are declared in the global declaration section
that is outside of all the functions.
· C program
must have one main ( ) function section.
This
section contains two parts:
- Declaration part
- Executable part
· The
declaration part declares all the variables used in executable part. There is
at least one statement in the executable part. These two parts must appear
between the opening and closing braces.
· Each
statement must end with semicolon (;).
· Sub
program section contains all the user defined functions, that are called in the
main() function.
Ex:
/*Program to addition of 2 numbers*/
#include<stdio.h>
void main( )
{
int a=15,b=20; /* Declaration part*/
int c=a+b;
printf("addition of a,b=%d",c);/* executable part*/
}
--O--
Flow
charts-algorithms
3.Define
Algorithm? Explain types of Algorithm?
Ans:
Algorithms
To
solve any problem a plan is needed. An algorithm is a part of the plan for the
computer program.
What
is an Algorithm?
An
algorithm is ‘an effective procedure for solving a problem in a finite number
of steps’.
“Effective”
means that an answer is found and it has a finite number of steps. A
well-designed algorithm should give an answer and also it must be terminated.
Different
Ways of Stating Algorithms:
Algorithms
can be represented in four ways:
1.
Step-form
2.
Pseudo-code
3.
Flowchart
4.
Nassi-Schneiderman
Step-form
representation:
· The
step-form uses normal language.
·It
states the algorithm with written statements.
· Every
statement is logically related to the preceding statement.
· Each
statement solves a part of the problem and all the statements together complete
the solution.
Example:
Write an algorithm for finding the sum of any two numbers.
Step 1. START
Step 2. PRINT “ENTER TWO NUMBERS”
Step 3. INPUT A, B
Step 4. C =A + B
Step 5. PRINT C
Step 6. STOP
Pseudo-code
- It is a written form representation of the algorithm.
- It is in the human language.
- It uses a limited vocabulary to define its actions.
Example:
If student's grade is greater than or equal to 60
Print "passed"
else
Print "failed"
Flowchart
A flowchart comprises a set of various standard
shaped boxes that are interconnected by flow lines.
Flow lines have arrows to indicate the direction of
the flow of control between the boxes.
The activity to be performed is written within the
boxes in English.
In addition, there are connector symbols that are
used to indicate that the flow of control continues elsewhere.
Advantages
of using flowcharts
Communication: Flowcharts are a better way of communicating
the logic of a system.
Flowchart to find largest of 3 numbers |
Proper
documentation: Program flowcharts
serve as a good program documentation needed for various purposes.
Efficient
coding: Flowcharts
act as a guide or blueprint during the systems analysis and program development
phase.
Proper
debugging: Flowcharts
help in the debugging process.
Efficient
program maintenance: The
maintenance of an operating program becomes easy with the help of a flowchart.
Flowchart to find largest of 3 numbers
Executing
the C Program
4.
Explain the Creation and compiling
,Executing a C Program?
Ans:
Creation
of a Program:
Compiling & Linking the program:
The structure program statements should
be translated into object programs which is suitable for execution by the
computer. The translation is done after correcting each statement. If there is
no error compilation proceeds and translated program are stored in another file
name with the same file name with extension ‘.obj’.
Compiling includes pre-processing,
compilation, assembly, and linking. For compiling the C program use the COMPILE
command (or ALT+F9) from the Turbo C++ IDE. If your program has any errors then the COMPILER will
list out the compile time errors.
Executing the program:
After successful compilation, use the
RUN command (or Ctrl+F9) from the Turbo C++ IDE to execute the program. If your
program has any errors then it will list out the runtime errors.
Otherwise it will display the result.
Compiler: Translates a program / set of programs
written in high level language into another computer language, i.e. source code
into object code.
Interpreter: An interpreter is a computer program
that executes instructions.
Loader: Loader is the part of operating system.
It is responsible for loading program From executable into memory preparing
them for execution and them executing.
The loader task is simple it has to put
the programs into some available space in memory.
--O--
Pre-processors
in “C”:
5.Explain
the Concept of Preprocessor in C?
Ans:
The C
preprocessor is exactly what its name implies. It is a program that processes
our source program before it is passed to the compiler.
Note that if the source code is stored in a file
PR1.C then the expanded source code gets stored in a file PR1.I. When this
expanded source code is compiled the object code gets stored in PR1.OBJ. When
this object code is linked with the object code of library functions the
resultant executable code gets stored in PR1.EXE.
The
preprocessor offers several features called preprocessor directives. Each
of these preprocessor directives begin with a # symbol. The directives can be placed anywhere in a
program but are most often placed at the beginning of a program, before the
first function definition.
The
preprocessor makes
·
program
development easier.
·
programs
easier to read.
·
modification
of programs easier.
· C
code more transportable between different machine architectures.
The
C Preprocessor Directives
The preprocessor directives can be classified into
two categories: unconditional and conditional.
#
define
The
general form for the define directive is #define macro_name replacement_string
The
#define directive causes the compiler to go through the program, replacing every
occurrence of macro_name with replacement_string. The replacement string stops
at the end of the line. No semicolon is used at the end of the directive.
#include <stdio.h>
#define FALSE 0
int main()
{
int done=0;
while(done=!TRUE)
{
printf(“\n Here done is FALSE”);
done++;
}
printf(“\n Now done is TRUE”);
return 0;
}
Output: Now done is TRUE
#include
This
directive causes one file to be included in another. The preprocessor command
for file inclusion looks like this: #include
"filename" and it simply
causes the entire contents of filename to be inserted into the program.
It
is common for the files that are to be included to have a .h extension. This
extension stands for ‘header file’.
The
prototypes of all the library functions are grouped into different categories
and then stored in different header files.
For
example prototypes of all mathematics related functions are stored in the
header file ‘math.h’, prototypes of console input/output functions are stored
in the header file ‘conio.h’, and so on.
Actually
there exist two ways to write #include statement. These are:
#include
"filename"
#include
<filename>
Example
#include "goto.c"
This command would look for the file goto.c in the current
directory as well as the specified list of directories as mentioned in the
include search path that might have been set up.
#include <goto.c>
This command would look for the file goto.c in the
specified list of directories only
C
Tokens
The
smallest individual units in a c program are called tokens or lexical
units. C tokens can be classified as follows:
1.
Keywords
2.
Identifiers
3.
Constants
4.
Separators
5.
Operators
Keywords
keywords
are the reserved words. Keywords
have a fixed meaning. These meanings cannot be changed. The keywords cannot be
used as variable names.
ANSI
C defines the following 32 keywords:
auto break case
char const
continue default do
double else enum extern float
for goto if
int long
register return short signed sizeof static
struct switch
typedef union
unsigned void
volatile while
Identifiers
Identifiers
are the names given to the variables, constants, data types, arrays, functions,
structs, unions and classes.
Identifiers
has the following rules:
I.
An identifier must start with an alphabet ( or underscore).
II.
It may contain a sequence of letters and digits
III.
Identifiers are case sensitive. “count” is different from “Count”.
IV.
Keywords cannot be used as identifiers
IV.
White spaces are not allowed.
V.
An identifier may contain any number of characters.
Some
of the valid identifiers: |
Some
of the invalid identifiers: |
total_marks |
1number |
number1 |
struct |
_count |
student
name |
C
Constants Constants
are the fixed values that do not change during the program execution. They are
also known as literals. In C, the keyword “const” can be used to declare
constants. It has the following syntax:
const datatype
identifier = value;
Example:
const int i = 30;
const
float pi = 3.14;
Constants
are of different types
1.
Integer Constants
2.
Real Constants
3.
Character Constants
4.
String Constants
1. Integer
Constants
Integer
constants are the whole numbers without any fractional part. There are three
types of integer constants:
1.1.
Decimal Integer Constants
The
integer constants that contains a set of digits, 0 through 9 are known as
Decimal integer constants
Example: 124, -121, 0, 5678
1.2.
Octal Integer Constants
Integer
constants that contains a set of digits from the set 0 through 7 are known as
Octal integer constants. An Octal integer starts with 0.
Example: 010, 0123, 0, 0560
1.3.
Hexadecimal Integer Constants
The
integer constants that contain a set of digits 0 to 9 and A to F are known as
hexadecimal integer constatns. A hexaemcal constant starts with 0x or 0X.
Example: 0xB, 0X9d, 0X123F
2. Real
Constants
The
constants that have fractional parts are called real or floating point
constants. These may be represented in fractional form or the exponent form.
Example: 0.08, -0.901, 132.03
3. Character
Constants
A
single character that is enclosed within single quotes is known as a character
constant.
Examples: ‘a’ , ‘S’, ‘4’
4.String
constants:
A
group of characters enclosed within double quotes is known as a String constant
Example:
“Dennis Ritchie”
“Ravi”
"Computer"
Variables:
Variables
are the names given to the memory locations. Variables can store data. A
variable can change its value during the program execution.
They variables can be declared as
below:
data
type variable_name_1, variable_name_2, ..., variable_name_n;
Example:
int a, b, c;
int
x = 10;
float
f =2.3;
Variables
will follow the rules of identifiers.
The rules for writing the variable
names are as follows:
·
Variable names must contain letters, digits and characters.
·
They must begin with alphabet or underscore.
·
They are case sensitive i.e, SUM and sum are not equal.
·
Keywords should not be used as variable name.
·
Blank spaces, commas and special symbols are not allowed
within them.
Scope and life of
variable
Explain Scope and
life of a variable
Ans:
Variables
can be declared at three basic places:
·
Variables
that are declared inside a function are called local variables.
·
The
variables that are declared in the definition of function parameters are called
formal parameters.
·
The
variables that are declared outside all functions are called global
variables.
Scope and life of a
variable is defined as vicinity or space of a variable within a program, where
value of given variable can be accessed. Hence, the effect of a variable can be
felt only within the block where the variable has been declared.
#include<stdio.h>
#include<conio.h>
main()
{
int m=1,n;
{
printf(“Iam from
block 1,the value of m is %d\n”,m);
int n=3;
{
m=4;
printf(“\n iam from
block 2 ,the value of m and n are%d\t%d”,m,n);
}
do
{
n=2;
printf(“\n iam from
block3,the value of n is %d\n”,n);
}while(n<2)
return 0;
}
Ans: A data type is a characteristic
that defines what type of data a variable can hold and the set of operations
that can be applied.
In C the data types are broadly
classified into the following types:
1.Primary Data types:
The standard and basic data types of
C are known as the primary data types. C has five basic data types:
It occupies 1 byte of memory. It
uses the keyword “char”. Character constants and literals can be represented
within single quotes.
2. Int: Integers are the numbers without
any decimal point (period/exponent). An int type can be classified into three
types:
a)short: A short type can represent
smallest integers. It occupies 2 bytes of memory.
b) int: An int data type occupies 2 bytes
/ 4 bytes of storage. Its range is -32,768 to 32767 or or -2,147,483,648 to 2,147,483,647.
c)long: A long type can represent long integers. It
occupies 4 bytes of storage.
3. Float: The numbers with
decimal point (exponent) are known as floating point numbers or real numbers.
They can use the keyword “float”. Float types are classified into three types:
a) float: A float type can represent 6
digits of precision. It occupies 4 bytes of storage. Its range is -3.4e38 to
+3.4e38.
b)double: A double type can represent double
precision floating point numbers. It occupies 8 bytes of storage. Its range is
-1.7e308 to +1.7e308.
c)long double: A double type can represent large
range of values. It occupies 10 bytes of storage.
4. Void type: A void type can
represent “valueless”. It specifies an empty set of values.
--O—
Type Conversion
7.Explain in detail type conversion?
Ans:
The process of converting one
predefined type into another type is called type conversion.
Type conversion is two types:
Implicit Type Conversion:
A type conversion that is
automatically performed by the compiler is known as implicit type conversion or type promotion.
It has the following rules:
- All short and char are automatically converted to int.
- If either of the operand is of type long double, then others will be converted to long double and result will be long double.
- If either of the operand is double, then others are converted to double.
- If either of the operand is float, then others are converted to float.
Explicit Type Conversion:
A type conversion that is performed
by the programmer is known as explicit type conversion.
The explicit type conversion is also
known as type casting.
It takes the following form:
(data_type)expression;
where, data_type is any valid c data
type, and expression may be constant, variable or expression. For example,
x=(int)a+b*d;
The following rules have to be
followed while converting the expression from one type to another to avoid the
loss of information:
- All integer types to be converted to float.
- All float types to be converted to double.
- All character types to be converted
to integer.
--O—
I/O Functions in C
8.Explain the
Concept of I/O Functions in C?
Ans:
C has a number of standard functions
to perform input and output operations.
In C, The input/output (I/O) functions are of two
types:
1.
Non-formatted input/output functions
2. Formatted input/output functions.
Formatted input/output functions
The I/O statements that use specific
format codes for their I/O are known as Formatted I/O functions.
These
functions can handle different data types.
There are two important formatted
I/O functions in C:
1. scanf()
2.
printf()
printf(): printf() is a formatted output
statement. It can print the specified contents on the screen. It has the following
format:
1. Ordinary characters : These are copied to output.
2. Format
specifier field: It
is denoted by % and the code.
3. Control code: It includes control characters such as \n, \b,
and \t.
printf() uses the following
format codes:
scanf(): scanf() is
a formatted input statement. It can read the given input from the keyboard. It
has the following format:
scanf(“control_string”,variable1_address,
variable2_ address,...);
Here, The
control string is also known as “Format String”.
scanf() uses the following format codes:
Example: Write
a C Program to add two integer numbers and find their Sum Solution
#include <stdio.h>
main()
{
int a,b,c;
printf(“\nEnter the first number: ”);
scanf(“%d”,&a);
printf(“\nEnter the second number: ”);
scanf(“%d”,&b);
c=a+b;
printf(“Sum = %d \n”,c);
return 0;
}
Output: Enter the first number : 5
Enter the
second number: 10
Sum= 15
Non-formatted
input/output functions
The I/O statements that does not use
format codes are known as Non-Formatted I/O functions.
These
functions can handle one character at a time. There are two important non-formatted I/O functions in
C:
1. getchar()
2. putchar()
getchar(): It can read a single character at a
time. It has the following format:
char_variable = getchar();
Example: int
ch;
ch =
getchar();
The getchar()function reads a
character and places it in the memory location “ch”
putchar(): It
can displays a single character at a time on the monitor screen. It has the
following format:
putchar(char_variable);
Example: int ch = ‘x’;
puchar(ch)
The putchar() function displays the
character stored in the memory location “ch”.
1. Write a C Program to convert
alphabets from lower-case letters to Upper-case letters.
Solution
#include<stdio.h>
main()
{
int ch,n;
ch=getchar();
n=(ch>=‘a’)&&(ch<=‘z’)?putchar(ch-32):
putchar(ch);
putchar(n);
return 0;
}
I/O
(i) Input m
Output MM
(ii) Input b
Output BB
(iii) Input $
Output $$
--O--
2. Write a C program to display a
keyed in character.
Solution
#include<stdio.h>
main()
{
int ch;
ch=getchar();
putchar(ch);
return 0;
}
I/O
Input A
Output A
Operators
9.Explain Various Operators in C
language?
An operator is a symbol that
specifies the mathematical, logical, or relational operation to be performed.
Table gives the different types of operators.
Arithmetic Operators
Arithmetic operators can perform the
arithmetic operations. There are five main arithmetic operators in ‘C’. They
are:
‘+’ for additions, ‘-' for
subtraction, ‘*’ for multiplication, ‘/’ for division and ‘%’ for remainder
division.
Relational Operators:
’
Logical Operators
There are three logical operators in
C language, they are logical &&(and) , logical !!(or),
logical !(not).
true or if both
operands are true.
Assignment Operators
It has the following format:
v=exp;
Example: count
= 9;
sum = a+b;
C Provides a short hand notation of assignment. It has the following format:
v op=exp;
Conditional Operator
The conditional operator has three
expressions. It has the general form
expression1
? expression2 : expression3
First, expression1 is evaluated; it
is treated as a logical condition. If the result is non-zero, then expression2
is evaluated and its value is the final result. Otherwise, expression3 is
evaluated and its value is the final result.
int m = 1, n = 2, min;
min = (m < n ? m : n); /* min is assigned a value 1 */
In the above example, because m is
less than n, m<n expression evaluates to be true, therefore, min is assigned
the value m, i.e., 1.
Special Operators are as follows
1.Comma Operator
This operator allows the evaluation
of multiple expressions, separated by the comma, from left to right in order
and the evaluated value of the rightmost expression is accepted as the final
result. The general form of an expression using a comma operator is
expressionM = (expression1,
expression2, …, expressionN);
2.sizeof Operator
C provides a useful operator,
sizeof, for calculating the size of any data item or type. It takes a single
operand that may be a type name (e.g., int) or an expression (e.g., 100) and
returns the size of the specified entity in bytes.
Example: int
n;
n=sizeof(char);
Bitwise operators perform
manipulations of data at bit level. Bitwise operators are not applied to float
or double.
a |
b |
a&b |
a|b |
a^b |
0 |
0 |
0 |
0 |
0 |
0 |
1 |
0 |
1 |
1 |
1 |
0 |
0 |
1 |
1 |
1 |
1 |
1 |
1 |
0 |
Increment and Decrement operators
The unary ‘++’ and ‘--’ operators
are known as increment and decrement operators. These operators can
increment or decrement the value of a variable by 1.
These operators can be used in
‘prefix’ and ‘postfix’ formats:
Ø
var++;
//post increment
Ø
var--
; // Post decrement
Ø
++var;
// Pre increment
Ø
--var;
// Post decrement.
Difference between prefix and
postfix formats:
In a prefix format, First the
operand is incremented/decremented. Second its value will be assigned to the
variable on its left.
In a postfix format, First the
operand’s value will be assigned to the variable on its left. Second the
operand is incremented/decremented.
No comments:
Post a Comment