0% found this document useful (0 votes)
19 views

II Bcom Structuring-Programming-Through-C

Uploaded by

lavarajugadi
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

II Bcom Structuring-Programming-Through-C

Uploaded by

lavarajugadi
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 36

Problem Solving and Algorithms

1) Explain various steps involved in development of a computer program (or)


Life cycle of program development of life cycle. (or) How to solve the problem solving

Programming is the process of solving a problem with computer. The five steps in the
programming process are listed below
1) Statement of problem 2) Development of solution 3) Coding 4) testing and debugging
5) Documentation
1) Statement of problem: Definition of a problem can be best achieved by writing
down the problem in clear statement. Better problem definition results in faster and accurate
solutions.
2) Solution development: this is the creative part of the programming process. At
this stage we have to construct a step by step procedure of solution. The useful tools in
development of a solution are (1) Algorithm (2) Flow Chart.
An algorithm is descriptive step by step problem solving procedure that can
be carried out by a computer.
A Flow chart provides visual representation of solution.
3) Coding: the next step in programming process is coding. This is the process of
converting a solution into o an actual computer program. Here the programmer has to choose
a particular programming language.
4) Testing & Debugging: Once coding is complete, we will enter the program into
the computer test it. We must verify that our program does everything that is supposed to do
the testing of program involves debugging. Debugging the process of finding out and
removing errors
5) Documentation: The final step in programming process is called documentation.
Documentation of a program consists a detailed procedure of operation of a program.
2) What is Top down Approach (or) Top down Design (or) Top down Programming?
A Module is a portion of program that also feels the definition of a program. These
subordinate modules can be further subdivided. Thus a hierarchical structuring of modules is
present with in the concept of modular programming. We have thus, superior modules and
subordinate module. Thus it is possible to design and develop a superior module before
designing subordinate module. This technique is known as top down approach. It is widely
accepted that top down approach provides visibility of the design and development process.
This makes the program less error-prone, and design and development activity takes less
time.
Thus to summarize, structured programming adopts the following 3 concepts that
helps to write good programs
1) structuring of control flow
2) Modular programming
3) Top down approach towards program design
The primary objective of structured programming is to increase readability and
understandability of a program. The structured program restricts transfer of control to
nearby places so that we don’t have to jump around while reading a program
Besides readability the other objectives that are achieved through structured
programming are as follows
2) The program becomes less error prone.
3) The programs become easily modifiable. This is the direct contribution of
modular programming.
4) The program development takes less time. This is again due to the simplicity of
methodology of structured programming.
(OR)
3) Explain the top down design approach?
It is one of the important design methodologies of programming. A program is
divided into different models or functions and there is one main program or model written
before all other models this main program or model can be called as a superior module and
all other models are called subordinate modules.
It is possible to design and develop their superior module before designing
subordinate modules this technique is know ass top down approach it is widely expected by
that top down approach provides visibility of the design and development process which
makes the program less error prom and less development time.

4) Explain the structure programming concept?

The goal of structured programming is to organized and displaying the programme design
and coding process. Process in order to prevent logical errors and to developed efficient
program. It consists of expression the logical of the program in term of three constructions

1) Sequence of two or more operations 2) Selections 3) Looping or ifferation


4) Modular approach 5) stepwise refinement 6) top down refinement

Sequence of two or more operations: it is the formalization of the idea of the program
statement expected in the order of their appearance.
Selection: it is the choice of alternative actions based on some conditions
(if, if else, if else if and etc)
Looping (or) ifferation: it s used to execute a piece of coin repeated while the condition
is true or some fixed no of times. Ex: for , while do while. Structured programming
breaking reducing the complicity of the program a structured may have the following
major characteristic
Modular Approach: it is the process of breaking up a programming problem into
logical parts called modules. It is of functional help in the modular design of the program
of the program. It reduces the program code make the debugging easier each functional
should be designed in such manner that is should be a logically self contained.
Step wise Refinement : The design stage consists of a sequences of requirement steps at
each step the given basic is broken into sub task until the subtask are simple enough to
be coded into a module with reliability
Top Down Design: It is one of the important design methodologies of programming. A
program is divided into different models or functions and there is one main program or model
written before all other models this main program or model can be called as a superior
module and all other models are called subordinate modules.
It is possible to design and develop their superior module before designing
subordinate modules this technique is know ass top down approach it is widely expected by
that top down approach provides visibility of the design and development process which
makes the program less error prom and less development time

4) What is an Algorithm?
Algorithm is one of the most central concepts in computer science. An algorithm is may
loosely be defined as an unambiguous (Clear cut) procedure for solving a problem. In turn, a
procedure is a finite sequence of well defined operations, each of which requires only a finite
account of storage and computer time.. Also, an algorithm should stop at finite time for any
input. Unambiguous procedure means a procedure that can be implemented on a specified
machine using a given language.
(OR)
An algorithm is set of sequential step usually written in ordinary English language with using
mathematical symbols or Algorithm is to solve the problem step by step processor with know
language.

Properties or Characteristics of an Algorithm


1) Preciseness: (Neatness, care): Each Step should state unambiguously the action to be
taken.
2) Effectiveness: (Success, Value) : Each step of a algorithm should be executable by a
specified machine
3) Finiteness: (Limited, restricted): An Algorithm should have a finite number of steps.
This does not mean that the amount of data or the number of processing steps should
be constant. This is done by repeatedly carrying out certain instructions.
4) Termination :( Killing, Slaughter): Each algorithm should terminate. Some
Termination condition should always be specified for repeatedly carried out steps. An
algorithm which does not terminate is no use.
Implementation of Algorithm:
When your write a algorithm we must require two key words (1) START, (2) STOP.
Start is used for beginning of the algorithm and stop is used for end of the algorithm. The
algorithm must have consists 4 steps they are

a) Declaration b) Input c) logical processing 4) output

a) Declaration: to define the data after the start keyword with using a declare keyword
is know as declaration part.
b) Input: To define a data name at declaration those must be assigned some value
through keyboard. In this input processing we must require the “ READ” statement
c) Logical processing: to define a data name and assign the value to be performed
some operation between the data name by using operator like “ + ,- , *, / , % , >, < ,
>/ , /< , # “ these are logical processing
d) Output processing: to solve the desire output format in this format the “ PRINTF”
statement is used.

5) Explain program characteristics?


A program must be able to perform design user tasks with in the specification
that it is should be able to provide result for all a valid input.
1) A program must be consists that is some set of input should produce some output.
2) A program should easy to use and understand.
3) The program should follow well define logical flow.
4) This is one of the main region the unconditional statement recommended to used a
program should be all well documents
5) The documentation should be consists of the specification. The program design
method the meaning of the variable used the program.

6) What are requirements of programming languages? Explain


The following are requirements of the programming language
1) Expressivity 2) Well-defined ness 3) Data types and structures
4) Modularity 5) Input-Output Facilities 6) Portability
7) Efficiency 8) Pedagogy 9) Generality

1) Expressivity: It is the ability of a language to clearly reflect the


meaning intended by the algorithm designer (the programmer). Moreover, an
expressive language embodies notations which are consistent with those that are
commonly used in the field for which the language was designed.
2) Well-defined ness: this means that the language’s syntax and
semantics are free of ambiguity, are internally consistent, and complete.
3) Data Types and structures: This is the ability for a language to
support for a variety of data values (Integers, rules, strings, pointers etc) and non-
elementary collections of these.
4) Modularity: It has two aspects the language’s support for sub
programming and the language’s extensibility in the sense of allowing programmer-
defined operators and data types.
5) Input-Output Facilities: This is the support for sequential indexed
and random access files, as well as its support for database and information retrieval
functions
6) Portability: This is the ability of a language to be implemented on a
variety of computers.
7) Efficiency: An efficient Language is one which permits fast
computation and execution on the machines where it is implemented.
8) Pedagogy: Some Languages have better pedagogy than others. That is
they are intrinsically easier to teach and to learn.
9) Generality: Generality means that a language is useful in a wide range
of programming applications.

Write Algorithms for the following problems.


(a) Factorial Computation (b) Summation of a set numbers

Step1: Start
Step2: Read n ( n is value of factorial)
Step3: Initialise fact to 1; Initialise I to 1 which is control variable
Step4: Fact=Fact*i
Step5: i=i+1
Step6: if i>n then print Fact
Otherwise goto step4
Step7: Stop
What is a language?
Language is the communication media between two individuals. Every language is having a well
defined character set and a grammar.

What is a Computer language?


Computer language is the communication media between user and computer. It is used to write
computer programs to solve a problem using computer. Computer language is having well
defined character set and syntax rules.

What are the classifications of computer languages?


What are the generations of programming languages?

Computers languages are classifies as


1st generation: machine level language
2nd generation: assembly level language
3rd generation: high level languages like c, c++, FORTRAN, Pascal, COBOL and BASIC
4th generation: front end application programs like java, VB, web applications etc

What is machine level language?


Machine level language is a language which is written by using ‘1’ and ‘0’. It can be directly
executed by a system. The advantage of the language is it does not require any converter. It is
running at very high speed. The main disadvantage is it is very difficult to debug. It is system
dependent

What is Assembly Language?


it is a language written by using mnemonics. Each computer has its own instruction set defined
by developer depending upon the architecture. It is translated into machine level by using
assembler. The main disadvantage is it is very difficult to debug and upgrade

What is an assembler?
Assembler is used to convert assembly level language program to machine level program.

What is a high level language?


High level language is a language written by using English statements. It is translated into
machine level by using compiler or interpreter. The advantage is very easy to understand, debug
and upgrade.
FEATURES OF "C"
1. Highly portable, flexible and efficient
2. Lean object code specific to target hardware
3. Invisible functionality like memory management, stack frames, CPU-register
manipulation, inline assembly, etc.
4. POINTERS are used to access memory and devices
5. It is a structured programming language that supports top-down programming technique

THE HISTORY of C

Multics (Multiplexed Information and Computing Service) was an operating system developed in
the mid-60's by MIT that delivered a computing interface not seen before. It was the first
computing environment to deliver things like 1) dynamic linking 2) inter-process (really universal
daemon processes) communication 3) complete memory file mapping 4) hot-swappable devices
and 5) full security throughout the OS. Applications were written in an ancient language called
PL/1 and the OS ran on GE mainframes. The size, complexity and cost made multics and its
environment inhibiting for most companies/organizations to employ.

Unics (Uniplexed Information and Computing Service and later trademarked as UNIX) was an
answer to the cost and complexity of Multics. Ken Thompson decided to write UNIX on the much-
less expensive DEC PDP/7 (in comparison to the GE mainframes). Dennis Ritchie helped
Thompson on this project. Unics (UNIX) was able to support two simultaneous users; one of
which was Brian Kernighan the OTHER one is Dennis Ritchie

At the time writing assembly language applications was not only tedious but required an intimate
understanding of the target hardware. Ritchie (Kernighan and Thompson) wanted to develop a
language that was not only highly portable but still allowed for CPU-register manipulation,
memory management and (relatively) easy I/O (input/output).

For this reason the new language is to be developed. The C-language was developed in 1972 at
Bell laboratories by Dennis Ritchie. It is designed for the operating system called UNIX. 90% of
UNIX was written in ‘C’. It is derived from the ‘B’-language which is written by Ken Thompson at
Bell laboratories. It is excellent and efficient and general purpose programming language. By
using ‘C’, we can solve scientific, business, mathematical, research applications. The striking
feature of C-language is developing the system programs.

Write about C-Tokes?


Token is a smallest individual unit in a program recognized by a complier. It is used to write
expression and statements. There exist six types of tokens they are
1. keywords
2. Identifiers
3. operators
4. constant

5. string-literal

6. Separators

Keywords:

These keywords have some standard pre-defined meaning in C-language. This meaning is
assigned by the compiler. The user cannot modify the meaning of keywords. There are 32
keywords in C-language they are
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
Identifier:
Identifier is the name used to uniquely identify an item in a program. It is used to represent
variables, constants, function names etc.
Rules:
1. The first letter must be an alphabet
2. Keywords are never used as identifiers.
3. Maximum length of an identifier is 8 characters.
4. No special characters are allowed except underscore (_).
5. Underscore should not be used at the beginning (or) ending of a variable name.
6. Identifiers names are case sensitive
Operators
Operator is a symbols used within an expression to perform specific operation on operands.
C has 15 simple operators ( ! % ^ & * - + = ~ | . < > / ? ), 11 compound assignment operators (
+= -= *= /= %= <<= >>= &= ^= |= == ), and 10 other compound operators ( -> ++ -- << >> <= >= !
= && || ).

Separators: Separator is a symbols used to separate different parts of a C program statements.


It has 9 separator tokens ( ( ) [ ] { } , ; : ).

Constants
Constant can be defined as the value of an identifier does not change while executing a program.
It is also called as literal. There are 3 types of constants. They are Integral constants, Floating
point constants, Character constants

Integer constants
It is used to represent positive or negative whole number without a fractional part.
There are 3 types of integer constants.
(a) Decimal Integer Constants: It contains decimal number 0 to 9. By default every
constant is a positive decimal constant.
(b) Octal Integer Constants: octal integer constants must begin with 0. It contains decimal
numbers 0 to 7. For example 07, 015, 05 etc
(c) Hexa Decimal Integer constants: Hexa decimal integer constants must begin with 0X.
It contains 0 to 9 numbers and A to F. Hear A=10, B=11, C=12, D=13, E=14, F=15.
For example 0x1, 0xA, 0X1F, 0X54 etc
Float constants:
It is used to represent positive or negative decimal number with an integer part, a decimal
point and a fractional part. For example 9.0, 12.13, 400.00 etc

Character constants:
Character constant is a single character that is enclosed within single quotes.
For example ‘A’, ‘9’, ‘B’, ‘+’, ‘x’, ‘0’, ‘ ’

String Constants or string literals:


A string constant is a collection of characters enclosed within double quotes. In C-language the
end of string is indicated by a character known as ‘\0’ (back slash zero) (null character). It is
automatically provided by the compiler. Ex: “aditya”, “abc” , “D.No-2-40-23” etc.
Explain about Structure of A C - Program?
A C- program is a collection of functions. Every function is a collection of statements. Every C-
program must have a function called main ( ) function. Following is the general structure of a C-
program.
Preprocessor Directives
global variables;
main ( )
{
local variables
statements;
}
fun ( )
{
}
fun1 ( )

{
}
In a C-program, preprocessor directives are executed before the C-program passes
through the compiler.
Mostly used preprocessor directives are: # include, # define
# include is mainly used for including necessary header files to our C-program
# define is used for macro definition
Global variables accessed by all the functions where as local variable are accessed within the
block. Every C-program has one (or) more functions. If a program has only one function, then it
should be the main function. Hence the execution of a C-program starts with the main function.
The main function has 2 parts.
They are: a) Declaration Part
b) Statement Part
The declaration part contains the declaration of local variables required for necessary operations
The following is an example C-program:
#include <stdio.h>
main ( )
{
int a,b,c;
Scanf(%d%d” , &a, &b);
C=a+b;
Printf (“Sum is %d” , c);
}
Output: Sum is C

Explain various data types in C?

C DATA TYPES

User defined Standard data types Derived


Data type Data type

Structure Array
Union void Pointer
Enum Integral type Floating type Function

int char float double


Data types: -
C data types can be classified as
1. Standard data types
2. Derived (extended data types)
3. User defined data types

Standard data types:


Standard data types are used to tell the compiler what type of data to be handled by an identifier.
These data types give complete details of the behavior of a data type. It is used to handle only
one value at a time by using single identifier. For example int, char, float, double

Derived data types (extended data types):


Derived data types are used to extend the behavior of an existing simple data type to get more
functionality. It is used to handle more than one value at a time using a single identifier. For
example arrays

User defined data types:


User defined data types are created by a user by using simple, derived, user defined data types
as per the user requirement. The user has to decide the functionality and behavior of these data
types. By using these data types to handle more than one data type using single identifier For
example structures and classes

Void: this data type is introduce in ANSI – C. it is used to represent the following things
1) To specify the return type of a function when it is not returning any value.
2) To indicate an empty argument list to a function

Qualifier: qualifiers are used to extend the behavior of standard data type. There are two
qualifiers namely size and sign.

Size qualifier is used to extend the size of an existing data type Size qualifier: there are two size
qualifiers they are short and long. Short is used to decrees the size and ling is used to extend the
size to maximum. For example short int size is only 2 bytes irrespective of operating system. It is
not possible to apply size qualifier on char

Sign qualifier: sign qualifier used to make the data type as a signed number or unsigned
numbers. There are two sign qualifiers they are signed and unsigned. Unsigned qualifier is used
to make the number as a positive number. By default all number are positive. It is not possible to
apply sign qualifier on long, double.

Sizes of the data types

Sno Data type Size in bytes Range

1 Char 1 -128 to 127


2 Unsigned Char 1 0 to 255
3 Signed Char 1 -128 to 127
4 int 2 -32768 to 32767
5 Unsigned int 2 0 to 65,535
6 Signed int 2 -32768 to 32767
7 Short int 2 -32768 to 32767
8 long int 4 -2147483648to 2147483647
9 float 4 1.2e-38 to 3.4e38
10 double 8 2.2e-308 to 1.8e308
11 long double 10 3.4e-4932 to 1.1e+4932

Array:
Array can be defined as collection of similar data items which are stored in continuous sequence
to memory locations. Example int x[10]

Struct:
Struct can be defined as collection of dissimilar data items under a common name
Example struct test
{int a,
char b;
};
Union:
Union can be defined as collection of dissimilar data items under a common name
Enum: it stands for enumerated data type. It is used to attach name to numbers
String: collection of characters terminated by a null character
Function: a set of statements having well defined specific task. It is a sub program which
performs a specific task.

Explain about operators in C?


Operator is a symbols used within an expression to perform specific operation on
operands. C supports a rich set of operators. They are
1. Arithmetic Operators (+, -, *, /, %)
2. Relational Operators (<, <=, >, >=)
3. Logical Operators (!, &&, ||)
4. Increment / Decrement Operators (++, --)
5. Compound Assignment Operators (or) Short cut Operators( +=, -=, *=, /=, %=, &=, |=, ^=,
<<=, >>=)
6. Conditional Operators (or) Ternary Operators (? :)
7. Assignment operators(=)
8. Bitwise Operators(~, &, |, ^)
Arithmetic Operators:
These are used for numerical calculations. There are 2 types of arithmetic operations. (i) Unary
(ii) Binary
Unary : It requires only one operand.
Example : Unary nious (-) is the unary operator available in this category. Eg : -y, -5 etc. Here -
changes the sign of operand y.
Binary : It requires two operands. There are five operators in C-language that support Binary
Arithmetic Operation.
They are :
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division (Quotient)
% Modulus operation (Remainder)
Note : The percentage (mod) operator cannot be applied with real numbers (floats).
Let us consider the following two integer variables a and b with the values 17 & 4
respectively.
Expression Result
a+b 21 (integer)
a-b 13 (integer)
a*b 68 (integer)
a/b 4 (integer)
a%b 1 (integer)
In the case of / and % operators, the second operand must be a non-zero value.
Consider the following table.
Relational Operators:
Relational operators are used to compare two values. The result of the comparison is either true
or false.
The following table give the list of relational operators :
Operator Meaning
> Greater than
< Less than
== Equal to
!= not equal to
<= less than or equal to
>= greater than or equal to
Let a=9, b=5 then the operations with relational operators are listed below.
Expression Result
a>b 1
a<b 0
a==b 0
a!=b 1
a<=b 0
a>=b 1
Logical Operators: The logical operators are used to combine two or more relational
expressions. C-language has three logical operators and they are listed below.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
AND Operator : It gives the net result as true if and only if condition (1) and condition (2) are
true.
C1 C2 C1&&C2

0 0 0
1 0 0
0 1 0
1 1 1
Let a=10, b=5 then the logical expression (a = = 10) && (b<a) gives the result as 1.
OR Operator: This operator gives the net result as false if and only if both the conditions have
false value. Otherwise the net result is true.
C1 C2 C1 C 2

0 0 0
1 0 1
0 1 1
1 1 1
Let a=7, b=12 then the logical expression (a < = b) (b>50) gives the result as 1.
NOT Operator: This is the only unary operator available in logical operators. This operator
negates the value of given condition. If the value of condition is false, the net result is 1 and if the
value of condition is true, the net result is 0.
C1 ! C1

0 1
1 0
Let a=10 then the logical expression! (a = = 10) gives the net result as 0.
Assignment Operator: A value can be stored in variables with the help of assignment operator.
= symbol denotes the assignment operator. The assignment operator has the following syntax.
Variable = expression;
For example a = 10; b = 20 ;x = a+b ;
Therefore x is assigned the value 30 which is the sum of a and b.
Compound assignment operator: it is a combination of operators. They contains +=,-=,*=./= etc
For example: a+=b  a= a+b
a-=b  a= a-b
a*=b  a=a*b
a/=b  a= a/b
Increment & Decrement Operators:
The increment operator (++) increments the value of the given variable by one and the decrement
operator (- -) decrements the value of the given variable by one.
For example a++ for a = a + 1 and a - - for a = a - 1
These operators are of two types :
(i) Pre increment / decrement
(ii) Post increment / decrement
1) Pre increment / decrement: Here the value of given variable is incremented first then this
incremented value is taken for the next operation.
Eg : (i) x = + + a ;
If the value of a=5, then in the above statement first a will be incremented by 1 (i.e) the
recent value of a is 6 which is assigned to the variable x.
(ii) x = - - a ;
If the value of a=5, then first a will be decremented by 1 (i.e) the recent value of a is 4
which is assigned to the variable x.
2) Post increment / decrement: Here the old value of the given variable will be operated with
the specified operation and later the increment/decrement is carried out.
Eg : (i) x = a + + ; let a=5
Here first the old value of a is assigned to x and then incrementation take place x=8, a=6
(ii) x = a - - let a = 5
In the same way, the old value of a is assigned to x and then decrementation take place
x=5, a=4.
Conditional operator or ternary operator:
The conditional operator are ? and : they are used for check the condition true or fale
Example: a > b ? printf( “big is A”): printf(“big is B”)

Bitwise operators
Different types of bitwise operator in C –language are 1. &bit wise and, 2 | bit wise or 3<< left shift
4>> right shift
For example a=3 the equal binary value is 0000 0000 0000 0010 then a<<1
Equal to 0000 0000 000 0100 it is equal to decimal 4

What are the Input and Output statements in c?


I/O Statements: -
The following are the two popular formatted input / output statements.
i) Scanf
ii) Printf
Scanf:
Input data can be entered into the memory from a standard input device keyboard. C-
Language provides scanf statement for supplying the input data. This statement can read all
types of data values.
The general syntax of scanf statement can be given as follows:
scanf(“control string with format specifiers” , addresses of variables);
Format specifiers are used to provide some information to the scanf statement regarding the type
of data and size of the data. Each format specifier must begin with a percentage sign (%).
Some of the format specifiers are given below:

The scanf statement should have at least 2 parameters. First parameter is a control string which
includes format specification characters. Second parameter is the address of the variable. To get
the address of any variable, it must by preceded by ampersand sign (&).
Example: scanf (“%d” , &a);
In the above scanf statement, there are 2 parameters. One is the control string with %d
format. Specifier and another is an integer variable ‘a’ preceded by Ampersand Symbol.
The following example shows the way of reading multiple variables using a single scanf
statement.
# include <stdio.h>
main ( )
{
int a;
float b;
char ch;
double d;
scanf (“%d %f %c %lf” , &a, &b, &ch, &d);
}
Printf: -
C provides printf statement for displaying output data. Printf statement moves the data from
computer’s memory to the standard output device Monitor. The variable names are optional and
the variable name should not be preceded with ampersand symbol.
The general syntax of printf statement is as follows:
1. printf (string constant”);
2. printf (“control string”, list of variables);
Example:
1. # include <stdio.h>
main ( )
{
printf (“This is my first C- program”);
}
Output: This is my first C-program.

Explain about control statements?


Control structures are used to control the flow of execution of a program with in the block. Control
statements are used to design control structures. In C control statements can be classified as
1. Conditional control statements (if, if else, ladder if, switch .. case )
2. Iterative control statements ( for, while, do .. while)
3. Unconditional control statements (goto, continue, break, exit)

Conditional control statements:


Conditional control statements are used to control the flow of a program based upon a condition
statement. For example if, if else, switch etc.

If statement:
Syntax: 1. if (condition) statement; // simple if statement
2. if (condition ) // if else statement
Statement
else
Statement

for example if (a > b) a = b; or


if (a> b) Printf(” a is big “); else printf(”b is big”);

In if statement the value of the condition is equal to true or 1 then the statement in the true block
are executed and if the value of a condition is false the statements in the false block are
executed. In simple if statement only true block is available.

Switch
It is a multi-way branching statement. It is used to check multiple conditions against a list of case
values. When a match is found the statements under the case are executed
Syntax
Switch ( variable)
{
Case value1 : statement; break;
Case value2 : statement; break;
- - - -
- - - -
Case valuen : statement; break;
Default : statement;
}
Example
Switch (a)
{
Case 0: printf(“zero”); break;
Case 1: printf(“one”); break;
Default : printf(“ invalid “);
}
If no match is found the default is executed

Iterative control statements:


Iterative control statement is used to repeatedly execute a finet set of statement for a finet
number of times depend upon a condition. There are two types of iterative control statements
they are 1. Entry control statement and 2. Exit control statements.
Entry control statements: first it check the condition. If it is true then enter into the loop otherwise
exit the loop. For example for, while.

For statement:
Syn for (initialisation; condition; step value ) Statement;

Example for (int i=1; I < 10; i++)


Printf(“%d”,i);
For statement is having three parts initialisation, condition, step value first the initialisation part is
executed only once and check the condition. If the condition value is true or 1 the control enters in
to the loop and come back to step value to get the next value and check the condition. The above
process is repeated until the condition is false. The minimum number of time the loop executed is
0.

While statement:
Syntax initialization;
while (condition)
{statements;
Step value:
}
Example while (I ++> 0) Printf(“%d”,i);
If the condition value is true or 1 the statements in the while loop are executed and if the condition
is false the control come out of loop. The minimum number of times a loop executes is zero.

Exit control statements: in exit control statements first the control enters in to the loop and checks
the condition. If the condition value is equal to true or 1 repeats the statements other wise break
the loop. The minimum number of times the exit control loop executed is 1. For example do..
while.
Syntax initialization;
do
{
Statement;
Stepvalue:
} while (condition).

Unconditional statements:
Unconditional statements are used to transfer the control from one place to other with out any
condition. They are generally used to branch or termination process. For example goto, break,
continue, and exit;

Syntax: goto – used to branch the control to a particular place


Break – to terminate the iterative statements
Continue – to get the next iterative value
Exit – terminate the entire program

What is the differences between while & Do While Loops?

While Loop Do- While Loop


it is an entry control loop It is an exit control loop

the minimum number of times executed is The minimum number of times executed is
zero one
no semicolon at the end of while It must be terminated by a semicolon
The following is the general The following is the general of the do-while
syntax loop.

syntax of the while loop Initialization

Initialization do

while (condition) {

{ :

: Body of loop

Body of loop Increment;

: } while (condition);

Increment,

Explain about if statement?


‘If’ is a conditional control statement. There are different type of if statements are available in c
they are simple if, nested if, if else and if else ladder
Simple if:
In the simple if statement there is only true block/ the block of statement will be executed
if the condition is true
Syntax : if (condition) if (a>b)
Statement printf(“big is a”);
Nested if
It contains multiple if statements. It check another condition if it is true
Syntax : if (condition) if (a>b)
{if (condition) {if(a>c)
{if (condition) printf(“big is a”);
Statement}} }
If – else
It is a two way statement. The condition is true then true block is executed otherwise
false block is executed
Syntax : if (condition) if (a>b)
Statement printf(“big is a”);
Else else
Statement; printf(“big is b”);
Else – if ladder
In this statement the else block contains if statement i.e check the condition
Syntax : if (condition) if (a>b) && (a>c)
Statement printf(“big is a”);
Else else
{ if (condition) if (b>c) printf(“big is b”);
} else printf(“big is c”);

Write about arrays?


An Array can be defined as collection of similar data items stored in continuous sequence of
memory location. It can be represented by a common name. the starting index of an array is 0
and the last index of an array is n-1 where n is the size of an array.

Type of arrays: there are three types of arrays they are one dimension, double dimension and
multi dimension array
One Dimensional Arrays:-
A list of items can be given one variable name using only one subscript one- Dimensional
Array.
Syntax
datatype name[size]:
Where the datatype specifies the type of the element that will be contained in the array
such as int, float (or) char. Name indicates the name of the array.
Size indicates the maximum number of elements stored in the array.
For example:
float height [50];
Declares the ‘height’ to be an array containing 50 float elements
Initialising Arrays:
The array can be initialised with some initial values at the time of declaration is called
initialisation
For example
1. int num [6] = {2,4,12,5,9,3};
2. int a[ ] = {11, 12, 13, 14};
3. Float Press [ ] = {12.3, 14.5, 16.7, 18.9};
Note the following points from the above examples:
1. While initialising an array, it is optional to mention the size of the array. The size will be
automatically assumed by the compiler.
2. An uninitialised array contains garbage values as its initial values.
3. It is also possible to initialise an array by having the initial values less than the size.
Ex: int a[5] = {11, 12, 13};
Reading Arrays:
The following for loop explains the way of reading one - dimensional arrays :
int a[10];
:
for (i = 0; i<10;1++)
Scanf (“%d”, &a[i]);
Writing Arrays: (or) Displaying Arrays:
The following for loop explains the way of displaying the elements of the array:
int a[10];

for (i = 0; i<10;1++)
Printf (“%3d ”, &a[i]);
Double - Dimensional Arrays:
an array having both rows and columns. The following is the general syntax of declaring
a two - dimensional array:
datatype name [rows] [columns];
The following is an example of declaring a 3 x 3 matrix:
int a[3][3];
Sincerely the element at ith row and jth column can be referred as a [i] [j]
Initialising Arrays :
Like one-dimensional arrays, two-dimensional arrays can also be initialised at the time of
declaration.
The following are some examples of initialising 2D arrays:
1) int a [3] [3] = {
{11,12,13} ,
{14,15,16} ,
{17,18,19}
};
The following points are noted from the above initialisation :
(i) While initialising 2-D arrays, it is optional to specify the no.of rows.
(ii) As per the above example (1), a[0] [0] will be assigned with 11, a[0] [1] with 12 .........
a[2] [2] with 19.
(iii) As uninitialised 2-D array contains garbage values.
Reading 2-D Arrays:
The following nested for loops describes the way of reading 2-D arrays:
int a[3] [3] ;
:
for (i = 0; i<B; i++)
for (j = 0; j<B; j++)
Scant (“%d”, & a [i] [j]) ;
Writing 2-D Arrays:
The following nested for loops display the elements of 2-D array in the matrix format :
int a [3] [3] ;
:
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
printf (“%3d”, a[i] [j]),
printf (“\n”);
}
Write about string handling functions?
String can be defined as collection of characters terminated by a null character. It is an array of
characters.
Syntax char name [size] ;
Where name is the name of the string variable size determines the number of characters
that the string can hold.
When the compiler assigns a character string to a character array, it automatically
supplies a null character (‘\0’) which is denoted by “\0”. Hence the maximum no. of
characters required are size +1.
Reading Strings:
Scanf : sting can be read by using scanf with %s format. For example:
char S [15] ;
:
scanf (“%s”, S)
In the above scanf statement, a collection of characters can be taken into the string ‘S’.
The problem with the scanf function is that it terminates its input on the first space
character (or) first tab character (or) enter key. Therefore if the following line of text is
typed for the above scanf statement,
New York
Then, only the string ‘new’ will be taken into the string ‘S’. This is because the space
character after the word ‘New’ will terminate the string ‘S’. Hence the scanf statement
cannot read Multi Word Strings.
The scanf statement with %S format specifier does not need the usage of ampersand
symbol before the variable name. The name of the character array itself indicates the
address.
gets : gets is an unformatted input function and it can accept a string from the key board.
Syntax: gets (string name) ;
The gets function is able to read multi-word strings and it recognises only the enter key
as the terminating character for inputting a string. For example
char S [80] ;
:
gets (S) ;
String Initialisation : C permits a string to be initialised in the following ways :
1. char name [7] = “aditya” ;
char name [ ] = {‘a’, ‘d’, ‘i’, ‘t’, ‘y’, ‘a’, ‘\0’} ;
From the above examples, the following points are noted.
In the example 1 the sting is automatically teminated by null character
In the example 2 the string is terminated by ‘\0’ null character supplied by user
Writing string:
The ‘printf’ function with %s format specification is used to display the string.
The following is an example:
char name [7] = “aditya” ;
:
printf (“%S”, name) ;
In the above example, name is initialised with a string constant “aditya” and it can be
displayed by the printf statement as: aditya
String Handling Library Functions : (String-h)
The C-library supports a large number of string handling functions that can be used to
manipulate the strings in many ways.
The following are the most commonly used string library functions :
Library Functions Action
Strlen ( ) Finds the length of a given string
strcmp ( ) Compares the given 2 strings.
strcpy ( ) Copies are string to another
strcat ( ) Concatenates the given two strings
strrev ( ) Reverse the given string

Define function? How it is to be created in C? (Or) Explain components of a function?


A function is a set of executable statements having well defined specific task that can be
processed independently. It can be designed, developed, and implemented independently by
different programmers. When the function is called, control is transferred to the first statement in
the function and executes the body and the control returns to the calling program.

Advantages of functions: -
1. Modular programming.
2. Program and function debugging is easier.
3. Division of work is simplified
4. Code reusability.
5. implement standard Library of functions

Function components:
Components of a function are
 Function declaration or prototype
 Function definition
 Function call
 Return

Function prototyping: -
The prototype tells the compiler function name, return data type, number of arguments and their
data types When a function call is occurred the compiler checks the function calls with its
prototype so that correct argument types are used. It should be declared as a first line of a main
program and must be terminated by semicolon (;).

Syntax: Return type function name (argument-list);


Example int add (int a, int b) or int add (int , int);

The variable names are optional in prototype declaration. It should be terminated by semicolon.
Each parameter must be declared independently inside the parenthesis. A combined declaration
is not allowed.

Function definition / declaration:-


The body of the function that defines the task of the function can be called as function definition.
The first line of the function definitions is known as function declaration. The declaration must
use same functions name, same number of arguments, the arguments type and return type. No
other function definitions are allowed within a function definition.

Syntax return type function_name( list of arguments)


{
Body of a functions;
Return;
}
Example float volume (int a, float b, float c)
{ float v;
v= 12.23;
}
The function volume can be invoked or called as follows
x= volume (10,10.5,8.6);
We can also declare a function with an empty argument list and without having a return
value.
void display ( ); (or) void display (void) ;

Function call: -
A function gets life only when a call to the function is made. A function call is specified by the
function name followed by the arguments enclosed in parentheses and terminated by a
semicolon. The return type is not mentioned in the function call.

Example: float x = volume (1,2.2, 3.4);

return:
The return statement is used to return the control back to the main program. It always returns
only one value at a time. There is no limitation for the number of return statements in a function
body. Once a return statement is executed control automatically transferred to the calling
program and leaves the remaining statements after the return statement in the function body.

Syntax return (variable or expression or value);


Example return (n);

Explain about pointers in C?


Pointers
A pointer is a variable which holds the address of memory or any variable or a function.

Syntax: data type *variable; for example: int *x;


Address of operator (&):
Syntax: pointer variable = & variable;

Address of operator & is used to get the address of a variable

Value at address operator or dereference operator (*)


Syntax: *pointer_varible;

Value at address operator is used to access the value pointed by a pointer.

Pointer initialization:
Syntax: pointer variable = & variable;

Pointers are always initialized with an address of any variable by using & symbol.

For example: char *x = “hello”

In this case, memory space is reserved to contain "hello" and then a pointer to the first character
of this memory block is assigned to variable x. The pointer x points to a sequence of characters
and can be read as an Array

Some common uses for pointers are:


 To access elements of an array or members of a structure
 To access an array of characters as a string.
 Passing parameter using call by reference method
 The size of any pointer variable is 2 bytes

Limitations of pointer variables:


 It is not possible to use pointers to refer variables declared as register storage class
 It is not possible to refer to a bit field
 A pointer can hold only one value at a time

What is pointer arithmetic? What are the different types of pointers?


Pointer arithmetic means that applying arithmetic operations on pointer variable. Only addition
and subtraction operations are allowed on pointers. Both addition and subtraction have a different
behavior with pointers according to the size of the data type of pointer variables. For example:
assume that *x is of type char pointer and *y is of type integer then
If x++ is equal to the address of x + 1* size of (char);
Similarly y - - is equal to the address of y-1* size of (int);
Type of pointers:

Pointers to pointers
Pointers to pointer or ** pointers. ** Pointers are used to declare a double dimensional array.
Each * represents one dimension

Syntax: data type * * variable;


For example int **x;
Void pointer:
Syntax: void *variable
For example: void *x;

The void pointer is a special type of pointer. It points to a value that has no type. It is used to
point any data type like integer, float, string etc.

What is null pointer?


A null pointer is a pointer that it is not pointing to any valid reference or memory address.
Syntax: data type * variable = NULL
For example int *x = NULL:

Write about dynamic memory management?


Allocate the memory at the time of execution is called dynamic memory allocation. In C-language
memory is allocated by using malloc and calloc. The allotted memory must be deleted by using
free command

Explain parameter-passing technique in C?


The parameters can be passed in 2 ways. They are
1) Call by value 2) Call by address 3
Call by value: -
By default parameters are passed by call by value method
In this method the values of actual parameters passed to formal parameters
Any changes made to formal parameters will not affect the actual parameters.
Only one value to be return from function

For example: swap two numbers


void swap (int x, int y) // function definition.
{ int t; t=a; a=b; b=t;
pintff( “inside the function a = %d b=%d“a,b); }
void main ()
{ void swap (int, int); // function prototype
int a=10,b=50;
swap(a,b); // function call as call by value
pintff( “inside the main a = %d b=%d“a,b); }
}

Output: inside the function a=50, b=10


Inside the main a=10, b=50

Call by address:-

 In call by address method the formal parameters must be a pointer type and they
receive the address of actual parameter.
 Any changes to the formal parameters are automatically reflected back to the actual
parameters in the main program.
 It is possible to return more than one value
 The address can be generated by using address operator &

Thus the complete program of swapping 2 numbers using call by address is as follows.

For example: swap two numbers


void swap (int *x, int *y) // function definition.
{ int t; t=*a; *a=*b; *b=t;
pintff( “inside the function a = %d b=%d“a,b); }
void main ()
{ void swap (int *, int *); // function prototype
int a=10,b=50;
swap(&a, &b); // function call as call by value
pintff( “inside the main a = %d b=%d“a,b); }
}

Output: inside the function a=50, b=10


Inside the Main a=50, b=10

From the above example, it is clear that the main() function can display the swapped values of a
and b

Explain about inline functions?


Inline functions are special function in which at the time of compilation the function body is
inserted in place of the function call. An inline function definition is similar to an ordinary function
except that the keyword inline precedes the function definition.
Syntax inline function- header ( )
{ Body of the function;
}
The inline functions are similar to macros. But the major drawback with macros is that the
error checking does not occur during compilation.

The following cases inline functions may not work properly


1. Functions returning values, having a loop, a switch or a go to exists
2. If the function contains static variables
3. If inline functions are recursive

Benefits: -
1. Inline function makes a program to run faster, because function call and return is
eliminated
2. For the small functions it is always convenient to use inline functions.

Disadvantages: -
1. Inline functions require more memory because they expanded while compiling the
program
2. it is not good for function if the size of a function is increased
3. The inline key word sends a request but not a command to the compiler. Hence the
compiler can ignore the request if the function definition is too long

The following is an example program for defining inline functions


inline float getdata (int a, float b)
{ return (a+b); }
void main ()
{
int a= 35; float b= 18.5;
printf(“The sum is %d“getdata (a,b));
}

What is recursion? Explain?


Calling a function into itself is known as recursion. For each function call a separate copy of local
variables are created. The following are the requirements to write a program using recursion.

1) The problem must be expressed in recursive nature


2) They should be one terminating condition to break the recursion.
3) By using backtracking mechanism to evaluate recursive function.
The following is an example program for calculating the factorial using recursion
#include <iostream.h>
#include<iomanip.h>
void main()
{ int n,f;
int fact(int n);
printf(“enter n value...");
scanf(“%d”,&n);
f= fact (n);
printf("factorial= %d",f );
}
int fact (int n)
{ if (n==0) return (1);
else
return(n*fact(n-1)); }

Sample run: in the above program the value of n = 3 the expected output is 6

Explain about storage clauses?


There are four types of storage clauses in c language. They are
1. Auto storage clause
2. Static storage clause
3. Register storage clause
4. Extern storage clause
The storage clause explain the following
 Where the arable is stored
 What is the initial value
 What is the scope of variable
 What is the life time of the variable
Auto storage clause:
The features of an auto storage class variable is as follows
Storage RAM or Main memory
Initial value garbage value
Scope local to the block
Life time till the control remains with in the block
The default storage clause in C-language is auto.
Syntax auto datatype varibalename;
Example auto int x;

Static storage clause


The features of an static storage class variable is as follows
Storage RAM or Main memory
Initial value 0
Scope local to the block
Life time till the control remains with in the block
The default storage clause in C-language is auto.
Syntax auto datatype varibalename;
Example auto int x;

main()
{
Incr();
Incr();
Incr();
}
Incr()
{
static n;
printf(“%d”,n++);
}
Output: 0,1,2

Register storage clause


The features of an register storage class variable is as follows
Storage CPU registers
Initial value garbage
Scope local to the block
Life time till the control remains with in the block

Syntax register datatype varibalename;


Example register int x;

Extern storage clause


The features of an extern storage class variable is as follows
Storage RAM or main memeory
Initial value 0
Scope through out the program
Life time through out the program

Syntax extern datatype varibalename;


Example extern int x;

Write about structures?


Structure is user defined data type. It is a collection of dissimilar data types having a common
name
Syntax: struct structure_name
{
datatype variable;
datatype variable;
};
Example struct student
{
int roll_number;
char name[10];
};
The structure can be defined by using the keyword struct
The members of a structure are also known as fields or data member
‘.’ Operator is called member of operator used to access fields of a structure
The sizeof the structure is defined as the sum of the sizes of the individual data members
In the above example the size of the structure is 22 bytes

Write about unions?


union is user defined data type. It is a collection of dissimilar data types having a common
name
Syntax: union union_name
{
datatype variable;
datatype variable;
};
Example union student
{
int roll_number;
char name[10];
};
The union can be defined by using the keyword union
The members of a structure are also known as fields or data member
‘.’ Operator is called member of operator used to access fields of a structure
The sizeof the structure is defined as the maximum size of the data member of the union
In the above example the size of the structure is 10 bytes
What is the difference between struct and union?

Structure Union
It can be defined as collection of dissimilar It can be defined as collection of dissimilar
data items data items
The size of the structure is equal to the sum The size of the union is equal to the
of the sizes of the individual data members maximum size of the data member of the
union

What is file? Explain file handling functions?


File can be defined as collection of records. Each record contains set of fields. The purpose of
files is to store data permanently on the disk. C-language support number of functions to perform
the file operations they are
Naming the file
Opening the file
Reading data from the file
Writing data to the file
Closing the file

Defining and opening file:


The following is general format for defining and opening file
FILE *fp;
fp = fopen(“filename”,”mode”);

The first statement declares the variable fp as pointer to the data type FILE.
The fopen function contain two parameters they are filename and mode
The modes are
r  open for read only
w  open for write only
a  open for append only

Closing file
The following is the general form of closing a file
Syntax: fclose(fp);

Input / output functions


Once a file is opened you can perform reading or writing operations depending on the mode of
operation

fprintf:
The general form of fprintf statement is
Syntax fprintf(fp,”format string”, variable);
Example fprintf(fp,”%d%s”,rno, name);
Here rno and name values are write into the file through the file pointer fp

fputc
The general form of fpuc statement is
Syntax fputc(ch,fp);
Example fputc(‘a’,fp);
Here ‘a’ value write into the file through the file pointer fp

fscanf:
The general form of fscanf statement is
Syntax fscanf(fp,”format string”, variable);
Example: fscanf(fp,”%d%s”,&rno,&name);
In this example the rno and name values are read form file using file pointer fp

fgetc
The general form of fgetc statement is
Syntax ch= fgetc(fp);
Example ch=fputc(fp);
Here character ch value read form file through the file pointer fp

Write about enum statement?


Enum stands for enumerated data type which is used to attaching name to numbers. The syntax
of enum statement is
Syntax enum < name>
{
Names;
};
Example enum color
{
Red;
White;
Green;
};
The numbers are 0,1,2, .. Which are automatically incremented by 1. In the about example the
value of Red =0, White=1, Green =2
Example 2: enum color
{
Red;
While = 15;
Green;
}
In the about example the value of Red =0, White=15, Green =16
What is type casting?
The type casting is used to convert the values of expression to particular data type
For example: int a=5; b=2; float c:
C=(float)a/b; gives 2.5

What is preprocessor?
#is the preprocessor directive which is used to declare header file. They are execture before the
main function
Example: #include <stdio.h> which contains printf() and scanf ()
#include<math.h> which contains sqrt(), pow()
#include<conio.h> which contains clrscr()

You might also like