Uploaded by Maniharan Katukojwala

Veerachary CBCS C II SEM-watermark

advertisement
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
PROGRAMMING WITH C
Syllabus
Unit-I: INTRODUCTION TO C LANGUAGE, DATA TYPES AND I/O OPERATIONS
Introduction: Types of Languages- History of C languages- Basic structure- creating- compiling- linking and
Executing the C program- Preprocessors in “C”.
Types and I/O operations: Keywords & Identifiers- Constants- Variables- Scope and Life of a variable- Data
types- Storage classes- Reading a character or value- Writing a character or value- Formatted Input and Output
operations.
Unit-II: OPERATORS, EXPRESSIONS AND DECISION MAKING
Operators: Introduction- Arithmetic- Relational- Logical- Assignment- Conditional- Special operators
Expressions: Arithmetic- Evaluation- Type conversion.
Decision Making & Looping: Introduction- If statements- If- Else statements- Switch statements- Conditional
statements- While statements- Do statements- For statements.
Unit-III: ARRAYS AND STRINGS
Arrays: Introduction- Defining an array- Initializing an array- One dimensional array- Two dimensional arrayDynamic array.
Strings: Introduction- Declaring and initializing string variables- Reading and Writing strings- String handling
functions.
Unit-IV: BUILT-IN FUNCTIONS AND USER DEFINED FUNCTIONS
Built-In functions: Mathematical functions- String functions- character functions- Date functions.
User defined functions: Introduction- Need for user defined functions – Elements of functions – Return values
and their types- Function declaration- Function calls- Recursive functions.
Unit-V: STRUCTURES AND POINTERS:
Structures: Introduction- Declaring structures variables- Accessing structure members- Functions and
structures- Array of structures- Enumerated data types- Introduction to Unions.
Pointers: Fundamentals- Understanding pointers- Address- Declaration of pointers.
LAB: PROGRAMS USING C.
SUGGESTED READINGS:
1.
2.
3.
4.
Programming in ANSI C: Balaguruswamy, McGraw Hill.
Programming in C: Ashok Kamthane, Pearson.
C: The Complete Reference: H.Schildt, Mc Graw Hill.
Let Us C: Y. Kanetkar, BPB.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 1
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
UNIT-1
Program: Program is a set of instructions, which solve a particular problem with in the
computer. While instruction is a request selected by the programmer for developing the related
operation within the program.
Types of programming languages: All programming languages can be divided into two
categories. They are:
i)
Low level languages
ii)
High level languages
Low level languages: Computer understands one and only one language i.e. machine language.
Machine language is a collection of 0’s and 1’s, which is also known as Binary language.
Ex: Machine language, Assembly language

Instructions of a machine language program are immediately executable because the
computer understands these instructions directly and no conversion is required.

It is difficult to write the program using binary code so a new language is introduced,
called as High level languages.
High level languages: In these languages, instructions are written in English like languages
which we can understand.
Ex: COBOL, FORTRAN, PASCAL, C++ and JAVA.
 It is easy to write the program.
 Instructions of High level language program are not immediately executable, because the
computer does not understand English. So these languages require translation steps to
translate from English code to Machine language code. So the program execution is slow.
*** C is also a language. In C instructions are written in English like languages. Since it comes
under High level language category. Even though it is High level language, it is called as
Machine level language because of following reasons.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 2
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
i)
C satisfies the advantages of both Low level and High level languages.
ii) C can be used to write both system programs as in Low level languages and general
purpose programs in High level languages.
History of C language:
By 1960, there were only few computer languages are present; almost each language is
used for a specific purpose. For example, COBOL was used for solving the problems of
Business applications. FORTRAN is used for solving Engineering and Scientific applications.
The people at this stage started thinking that instead of learning so many languages, why not we
use only one language where any type of application problems can be solved.
Year
Language
1960 ALGOL
Developed by
International Committee
1963 CPL (Combined Programming
Language)
Cambridge University (UK)
1967 BCPL (Basic Combined
Programming Language)
Martin Richards (Cambridge University, UK)
1970
B
Ken Thompson (at AT & T Bell Laboratories, USA)
1972
C
Dennis Ritchie (at AT & T Bell Laboratories, USA)
Translators: Translators are the programs which converts the instructions written in High level
language to Machine understandable language. The translators are: Compilers and Interpreters.
i) Compiler: It is one of the translators that translate a program written in High level language
to Machine instructions. Compiler translates all the lines from source program to machine
code known as object code. Some of the languages that use compiler as their translators are C,
C++, COBOL, etc.
ii) Interpreter: Some High level languages often use Interpreter instead of compiler to translate
instructions into machine code.
Interpreter translates one line after the other into machine language. Some of the languages
that use interpreter as their translators are: dbase, basic, etc.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 3
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
***** C uses compiler as its translator. There are different types of compilers available in the
market. Among them few are TurboC, BorlandC, ANSIC, and QuickC.
Q: What are the characteristics of C? (OR) What are the advantages of C?
A:
C is the most popular programming language. C has many advantages, which are listed
below.
1) Middle level language: As a middle level language, it combines both the advantages of low
level and High level languages. It is easily understandable and programs in C are coordinate
with the hardware.
2) Modularity: Modularity is one of the important advantages of C. We can split (divide) the
program into number of modules instead of writing it sequentially. Modularity improves
understandability. It allows reusability of modules which reduces the length of the program..
3) Portability: C program is compatible with majority of operating systems. Hence it is
portable to other systems even if the operating system differs.
4) Flexibility: C allows a lot of flexibility in data conversion from one data type to another i.e.
converting from integer to character and character to integer.
5) Simple: C is more or less like English. It only has 32 keywords of its own. For a programmer
it becomes simple to write programs when programming language is simple.
6) General purpose programming language: C can be used to implement any kind of
applications such as Business applications and Scientific oriented applications.
7) Powerful programming language: C is very efficient and powerful programming language.
It is best used for Data Structures and designing System software.
Q: What are the characters of Lexical Set? (Or) What is C character set?
A:
There are so many characters used in C programming. C language consists of character
set, using which we can write programming instructions in C.
A character is any alphabet,
digit, or special symbol used to represent information. The following are the C character set.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 4
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
: A, B, C … Z
Alphabets
a, b, c, ……z
Digits
: 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9
White space characters : Blank space, new line, tab, etc.
Special characters
, comma
:
& ampersand
. period
^ caret
; semi colon
* asterisk
: colon
- minus sign
? question mark
+ plus sign
‘ apostrophe
< opening angle bracket
“ quotation mark
(or less then sign)
! exclamation mark
> closing angle bracket
| vertical bar
(or greater than sign)
/ slash
( left parenthesis
\ backslash
) right parenthesis
~ tilde
[ left bracket
_ under score
] right bracket
$ dollar sign
{ left brace
% percent sign
} right brace
# Number sign
Q: Define C tokens? (Or) Explain keywords, Identifiers, Constants and Variables?
A:
Token is a smallest individual part in the program. Every token has its own meaning and
used for specific operation. C has 6 types of tokens. They are:
C tokens
Identifiers
Keywords
Variables
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Constants
Special
Characters
Operators
Page 5
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
1) Identifiers: The names of variables, functions, Labels and other user defined items are called
as Identifiers.
 An identifier can include Alphabets (a-z, A-Z), digits (0-9) and Underscore (_) symbol.
 The length of an identifier can vary from one to several characters.
 It starts with a letter or underscore.
 It cannot include spaces.
 Uppercase and lowercase identifier names are treated as different. C is a case sensitive
language.
Ex: a1, rno, emp_name, etc.
2) Keywords: Keywords are defined by C compiler and each keyword has a special meaning.
These are the reserved words and cannot be used as names of variables or functions or labels. C
has 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.
3) Variables: A variable is a name given to the storage location, in which a constant value is
stored. Value of the variable can be changed from time to time.
Ex: int rno=10;
Here rno is a variable.
Variable naming rules: To give variable names some rules should be followed. They are:
 Variable name should start with an alphabet.
Ex: int empno=101;
 Variable names consist of alphabets, digits, or an underscore symbol.
Ex: roll_no=25;
(correct)
but,
roll.no=25; (wrong)
 Variable name should not contain spaces.
Ex: roll no=25; (wrong)
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 6
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
 Variable name can be of any length but some compilers restrict this.
 Two variables in the same block should not have same variable names.
4) Constants: A constant is a fixed value that does not change its value during the execution of
a program. C allows mainly two types of constants.
Constants
Numeric constants
Integer
Constants
Alphanumeric constants
Floating point
(or) Real
Constants
Single
Character
Constants
String
Constants
Boolean
Constants
Numeric constants: The constants which are related to numbers are called as Numeric
constants.
i) Integer constants: Integer constants are numbers without decimal points.
Ex: 123, 1003, -2345
ii) Floating point constants: Floating point constants are numbers with decimal points.
Ex: 120, 123.456, -4123.8695, etc
123.456=1.23456x102=1.23456E2 it is called as exponential notation.
Exponential notation:
Mantissa E
exponent
Alphanumeric constants: The constants which are related to characters are called as
alphanumeric constants.
i) Single character constants: A single character constant can be an alphabet or a digit or a
special symbol which is enclosed with in single quotes (‘ ’).
Ex: ‘a’, ‘3’, ‘*’, etc.
ii) String constants: A string constant is a sequence of characters enclosed with in double
quotes(“ ”).
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 7
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Ex: “program”, “ravi”, “student123”, etc.
iii) Boolean constants: Boolean constants are True or False. In C zero is false and non-zero is
True.
5) Special characters: They include characters such as “, ‘, /, &, etc.
6) Operators: Operator is a symbol which is used to perform some specific operation. In C
there are many types of operators. Ex: Arithmetic operators (+, -, *, /, %).
Q: Explain Backslash character constants (or) Escape sequences?
A:
C supports some special backslash character constants that are used in output functions.
For example, the symbol ‘\n’ stands for new line character. Some of the escape characters are
shown below.
Escape Sequence
Q:
A:
Meaning
\n
new line
\t
horizontal tab
\v
Vertical tab
\b
backspace
\r
carriage return
\f
form feed
\a
bell
\\
Back slash
\’
single quote
\”
double quote
Explain different types of data types in C?
 Data type determines the type of data a variable will hold.
 It specifies the size of a variable.
 Every variable, which is used in the program, must be declared as what data type it is.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 8
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Data types
User defined
Data types
System defined/
primitive Data
types
Derived Data
types
Structures
Empty Data
types
Arrays
Void
Numeric
Alpha
numeric
Unions
Enumerations
Integer
char
float, double
string
Pointers
Primitive Data types (System defined/ built in/primary/fundamental/ scalar data types):
The code of the Primitive Data types is declared and defined by the C compiler and stored in
library files. We can simply use these data types when required. The primitive data types are int,
float, double, char.
i) Integer data type: Integer data types are used to declare integer variables with the help
“int” key word. These integer variables can occupy 2 bytes in the memory.
Ex: int num; ----- num
ii) Floating point data types: This float data type is used to declare float variables with the
help of “float” key word. Float variables can occupy 4 bytes in the memory. Float variables
can have 6 decimal points.
Ex: float amount=10.95; ----
amount
10.950000
iii) Double data type: It is used to declare real variables same as float with the help of “double”
key word. Double variables can occupy 8 bytes in the memory. Double variables can have
16 to 18 decimal points.
Ex: double vector=3.44; ----
vector
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
3.440000
Page 9
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
iv) Character data type: It is used to declare character variables with the help of “char” key
word. Character variables can occupy 1 byte in the memory.
Ex: char star=’*’; -----
star *
Data type
Keyword
memory
Range of values
Integer type
int
2 bytes
-32768 to +32767
unsigned int
2 bytes
0 to 65535
short
1 byte
-128 to +127
unsigned short int
1 byte
0 to 255
long int
4 bytes
-2147483648 to +2147483647
unsigned long int
4 bytes
0 to 4294967295
float
4 bytes
3.4 E -38 to 3.4 E +38
double
8 bytes
1.7 E -308 to 1.7 E +308
long double
10 bytes
3.4 E -4932 to 3.4 E +4932
char
1 byte
-128 to +127
unsigned char
1 byte
0 to 255
Floating point type
Character type
int
User defined data types: These data types are defined and used by the programmer.
Ex: structures, unions, enumerations.
Derived Data types: These data types are derived from primitive data types.
Ex: Arrays and pointers.
Empty data type: “void” is empty data type. The void type has no values, this is used to
specify the type of functions. The type of a function is said to be void when it does not return
any value.
Q:
What is a variable and how to declare a variable?
A:
A variable is a name in which a constant value is stored. Values of variables can be
changed from time to time. Declaration of variable can be done before they are used in the
program.
Declaration of variable: Declaration does two things
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 10
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
i) It tells the compiler what the variable name is
ii) It specifies what type of data the variable will hold.
Syntax: datatype
Ex:
variable_name;
(Or)
datatype var1, var2, var3, ……;
int rno;
float fee, amount;
Q:
A:
Explain the structure of C program?
The general structure of C program contains:
Documentation section
Link section
Definition section
Global declaration section
main ( )
{
Declaration part
Executable part
}
Subprogram section
Function 1
Function 2
:
:
(User defined functions)
Function n
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 11
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
The documentation section: It consists of comment lines giving name of the program and
other details. Comments are the non executable statements. These are mainly used for
understanding the purpose of the program.(program name, date and time of creation, author
name). All the comments are enclosed in between /*…..*/ markers.
Ex: /*This program is used for addition of two numbers*/
The link section: It provides instructions to the compiler to link functions from the system
library. It contains preprocessor statements. The statements that are begin with “#” symbol is
said to be pre processor directive statement. These are processed (compiled) first before any
programming statements in the programs are processed. #include statement is used to include a
programming file into another file.
Ex: #include<stdio.h>, #include<math.h>
The definition section: It defines all symbolic constants.
The global declaration section: There are some variables that are used in more than one
function. Such variables are called global variables and are declared in this section that is
outside of all functions.
main( ) function: Every C program must have one main function section. This section contains
two parts, declaration and executable part.
 Declaration part declares all the variables used in the executable part.
 There should be at least one statement in the executable part which contains instructions
to perform certain task.
 The declaration and executable part must appear between the opening and closing braces.
All statements in the declaration and executable parts should end with the semicolon (;).
The subprogram section: It contains all the user defined functions that are called in the main
function. User defined functions are generally placed immediately after the main function.
All sections, except the main function may be absent when they are not required.
Ex:
/*program to print a message*/
#include<stdio.h>
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 12
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
main( )
{
Output:
This is my first C program
printf(“ This is my first C program”);
}
Q:
Explain the procedure for creating, compiling, linking and executing a C program.
A:
Creating a C program:
 Open any C editor like TurboC.
 Now we select NEW option from the File menu.
 An edit window will appear with the filename NONAME.C.
 Write the program.
 Once we complete our typing we should save it to the disk as PROGRAMNAME.C by
selecting save from the file menu, or by pressing the F2.
Compiling the Source Program:
 To compile the source file, we select compile menu and will press enter key.
 If there is syntax error in the source program, then the resulting window- warning: 0,
errors: 0 and finally success: press any key.
 This compilation process creates an object file, which has an extension .OBJ
 However if there is error then the compiler displays the appropriate error messages, that
tells the cause of the error and the compilation process terminates. Therefore go back to
the source program, correct it and compile it again. You can also compile the source
program by pressing the ALT and F9 keys simultaneously.
Linking the program:
 The program is linked with functions that are needed from ‘C’- library.
 To link our object file, select link from the compile menu. After this the OBJ file will be
compiled with the one or more library files.
 The result of this linking process produces an executable file with .EXE extension.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 13
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Executing (Running) the program:
To execute (run) the .EXE file, select run from RUN menu and press enter key. The result will
be displayed on the screen and controls back to the editing screen.
However you can also execute the .EXE file by pressing CTRL and F9 keys simultaneously. To
see result select User Screen from RUN menu or by pressing ALT and F5 keys simultaneously.
Q:
A:
Explain conversion characters (Or) Format specifiers (Or) Conversion Strings?
Format specifiers are used to provide the format of the variables to be printed. Each
format specifier has to be preceded with a “%” sign.These are used in some of the input and
output statements, such as printf and scanf. The following are the various format specifiers.
Conversion character
Meaning
%d
Integer
%u
unsigned integer
%c
character
%f
floating point
%s
string
%o
octal value
%x
hexa decimal value
%ld
long decimal
Ex: /*Example program for format specifier*/
#include<stdio.h>
main( )
{
int n=10;
float salary=1000.00;
char symbol=’&’;
clrscr();
Output:
Value of n=10
Value of salary=1000.000000
Value of symbol is=&
printf(“\n value of n is=%d”,n);
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 14
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
printf(“\n value of salary=%f”,salary);
printf(“\n value of symbol is=%c”,symbol);
}
Q:
What is preprocessor statement? (Or) What are compiler directives (#include,
#define and #if directive).
A:
 The preprocessor mechanism allows different directives such as #include and #define.
 Before processing the actual program these are processed first.
 The preprocessor directives follow special syntax rules. They are begin with # symbol and
they are not terminated (ended) with semicolon.
 They are placed in the program before main ( ).
 Few other directives are: #if, #else, #endif, #undef.
Include directive (File inclusion directive): It includes the processed file that has been
mentioned in angle brackets or quotes.
Syntax:
Ex:
2) #include “filename”
1) #include<filename>
#include “abc.c”
#include<stdio.h>
Define directive (Macro substitute directive): Macro substitution is a process where an
identifier in a program is replaced by a predefined string.
Syntax:
#define
identifier
string
Ex:
#define
COUNT
100
1)
In this case whenever COUNT appears in the program it is replaced with 100.
2)
#define
PI
3.14
In this case whenever PI appears in the program it is replaced with 3.14.
Define directive with arguments: Define directive allows us to define identifiers which are
replaced with the other meaningful string.
Syntax:
#define
identifier (f1, f2, f3,….. , fn)
string
In the above syntax, f1, f2, f3,….., fn are the formal macro arguments.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 15
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Ex:
#define
big(x, y)
x>y? x: y
main( )
{
int i;
i= big(40, 50);
printf(“\n %d”, i);
/*prints the bigger value that is 50*/
}
In the above example we have used a macro (define with arguments). big(x, y) is
replaced with x>y? x: y.
If directive: If directive instructs the compiler to compile the statements between #if and
#endif, only if the condition is true.
Ex:
#define flag 1
#if flag
……….
Statements
……….
#endif
Q: Explain scope and Life of a variable.
A:
Life: Life of a variable means, the period of time the variable exist in memory.
Scope: Scope of a variable means, the area or place where a variable can be accessed.
The scope of any variable can be broadly categorized into three categories:
 Global scope: when variable is defined outside all functions. It is then available to all the
functions of the program and all the blocks program contains.
 Local scope: when variable is defined inside a function or a block, then it is locally
accessible within the block and hence it is a local variable.
 Function scope: when variable is passed as formal arguments, it is said to have function
scope.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 16
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Let’s understand this with the help of an example:
#include<stdio. h>
int global=100;
//global variable declared
void func1( );
void main ( )
{
int local= 10;
//local variable declared
printf (“Global variable is %d” , global);
printf (“Local variable is %d”, local);
func1( );
}
void
func1( )
{
printf(“Global inside func1 is %d”, global); // would print the global successfully.
}
Output:
Global variable is 100
Local variable is 10
Global inside func1 is 100
Q:
What are Storage classes? (Or) Explain scope, visibility and lifetime of a variable.
A:
A storage class specifies the scope, life and initial value of a variable.
Scope: Scope of a variable means, the area or place where a variable can be accessed.
Life: Life of a variable means, the period of time the variable exist in memory.
In C, there are four storage classes, they are:
1. auto
2. extern
3. static
4. register
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 17
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
auto: If a variable is declared as “auto” then it is called as “automatic variable”.
 Automatic variables are also known as Local variables.
 Automatic variables are declared within a function.
 Scope of automatic variable is limited to the function, in which it is declared.
 Life of automatic variable is till the function terminates.
 Automatic variables initialized to some garbage values if no data is given.
Ex:
# include<stdio.h>
void increment(void);
void main ( )
{
increment( );
increment( );
increment( );
increment( );
}
void increment(void)
{
auto int i= 0;
printf(“%d”, i);
i++;
}
Output: 0000
extern: If a variable is declared as “extern” then it is called as “external variable”.
 External variables are also known as Global variables.
 Scope of external variable is throughout the program. Other programs can also share
external variables.
 Life of external variable is till the program terminates.
 External variables get initialized to “zero”.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 18
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Ex:
#include<stdio.h>
extern int x=30;
void show( );
main( )
{
printf(“\n x=%d”, x);
show( );
}
void show( )
{
printf(“\n x=%d”, x);
Output:
X=30
X=30
}
static: If a variable is declared as “static” then it is called as “static variable”.
 Static variables defined within a function.
 Scope of static variable is within the function.
 Life of a static variable is till the program terminates.
 Static variables are initialized to “zero” automatically.
Ex:
#include<stdio.h>
void increment(void);
void main( )
{
increment( );
increment( );
increment( );
increment( );
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 19
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
void increment(void)
{
static int
i = 0;
printf(“%d”, i);
i++;
}
Output: 0 1 2 3
register: If a variable is declared as “register” then it is called as a “register variable”.
 Register variables are also local variables, but stored in register memory. Whereas, auto
variables are stored in main CPU memory.
 Register variable will be accessed very faster than the normal variables since they are
stored in register memory rather than main memory.
 But only limited variables can be used as register since register size is very low. (16 bits,
32 bits or 64 bits)
Ex:
#include<stdio.h>
main( )
{
register int i=30;
printf(“\n i=%d”, i);
}
Storage class
Scope
Life
Initial value
auto (local)
Within the function
Till the function ends
Garbage value
extern (global)
Throughout
the Till the program ends
Zero
program
static
Within the function
Till the program ends
Zero
register
Within the function
Till the function ends
Garbage value
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 20
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Q:
Explain Input and output functions in C? (or) Discuss the elementory functions of
Input and Output in C?
A:
The Input functions of C are used to read the data values at execution time into the
declared program variables. In the same way, output functions are used to print the values on
the console at execution time.
Input/Output statements are categorized into two, they are:
i) Formatted Input/output functions (or) standard Input/Output functions
ii) Unformatted Input/Output functions
Formtted I/O functions: The I/O functions that use format specifiers such as %d, %f,..etc. in
their Input and Output operations are known as Formatted I/O functions. These functions allow
the input read from the keyboard and the output displayed on the monitor. Each program that
uses a standard Input/Output functions must contain the statement #include<stdio.h>. “stdio.h”
stands for standard input output headerfile. Formatted I/O functions are:
a) scanf( )
b) printf( )
Unformatted I/O functions: The I/O functions that does not use format specifiers in their input
and output operations are known as unformatted I/O functions. They are:
Character I/O functions
String I/O functions
getchar( )
gets( )
putchar( )
puts( )
getch( )
Q:
Explain Formatted Input and Output operations.
A:
The I/O functions that use format specifiers such as %d, %f,..etc. in their Input and
Output operations are known as Formatted I/O functions. These functions allow the input to
read from the keyboard and the output displayed on the monitor. Formatted I/O functions are:
a) scanf( )
b) printf( )
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 21
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
scanf( ): The standard input function scanf( ) is used to read all types of data from the keyboard
at runtime.
Syntax: scanf(“control string”, arg1, arg2, arg3, ….argn);
Where, control string is the format specifier in which the data is to bo entered and the arg1,
arg2, arg3,….argn are the address of locations where the data is stored. control stirng and
arguments are separated by comma’s.
Ex:
1) Inputting Integer Numbers:
int num;
scanf(“%d”, &num);
2) Inputting Real Numbers:
float fee;
scanf(“%f”, &fee);
3) Inputting characters:
char gender;
scanf(“%c”, &gender);
4) Inputting character Strings:
char name[20];
scanf(“%s”, name);
5) Reading Mixed Data types:
int num;
float fee;
char gender;
char name[20];
scanf(“%d%f%c%s”, &num, &fee, &gender, name);
printf( ): The standard output function printf( ) is used to print all types of data items on the
monitor at runtime.
Syntax: printf(“message”);
printf(“control string”, arg1, arg2,….argn);
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 22
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
The first syntax is used to print some message on the screen. Second syntax is used to print
arg1, arg2,….argn values including with format specification.
Ex:
1) Output of Integer numbers:
printf(“%d”, integer_variable);
int num=20;
printf(“%d”, num);
2) Output of Real numbers:
printf(“%f”, float_variable);
float fee=7500.00;
printf(“%f”, fee);
3) Printing a single character:
printf(“%c”, character_variable);
char gender=’m’;
printf(“%c”, gender);
4) Printing of Strings:
printf(“%s”, character_array);
char name[20]=”vdc”;
printf(“%s”, name);
5) Mixed data output:
printf(“%s%c%d%f”, name, gender, num, fee);
Q:
How to read a character and write a character in C?
A:
Reading a character: The simplest of all input/output operations is reading a character from
the ‘standard input’ unit (usually the keyboard) and writing it to the ‘standard output’ unit
(usually the screen). Reading a single character can be done by using the function getchar.
(This can also be done with the help of the scanf function). The getchar takes the following
form:
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 23
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Variable-name = getchar( );
Variable-name is a valid C name that has been declared as char type. When this statement
is encountered, the computer waits a key is pressed and then assigns this character as a value to
getchar function. Since getchar is used on the right-hand side of an assignment statement, the
character value of getchar is in turn assigned to the variable name on the left. For example
char name;
name = getchar( );
Will assign the character ‘H’ to the variable name when we press the key H on the
keyboard.
Example:
# include < stdio.h>
void main( )
{
char ch;
printf (“ \n enter a character : “);
ch = getchar( );
printf (“\n ch = %c”, ch);
}
Output:
Enter a character : k
ch = k
Writing a character: Like getchar, there is an analogous function putchar for writing
characters one at a time on the screen. It takes the form as shown below:
putchar(variable-name);
Where, variable-name is a type char variable containing a character. This statement
displays the character contained in the variable-name on the screen. For example, the
statements:
answer = ‘Y’;
putchar(answer);
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 24
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
will display the character Y on the screen. The statement
putchar(‘\n’);
would cause the cursor on the screen to move to the beginning of the next line.
Example program:
# include <stdio.h>
void
main( )
{
char ch = ‘A’;
putchar(ch);
putchar(‘s’);
putchar(‘z’);
}
Output:
A$Z
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 25
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
UNIT- II
Q:
What is meant by operator? And list out the operators in C.
A:
An operator is a symbol that performs a specific operation on operands. Operands may be
variables or constants on which the operator performs operation.
Ex:
int a=10, c;
C=a+20; here, a and 20 are operands, + is an operator.
Operators can be classified into two types based on the following.
(1)
Based on number of operands involved :
i)
Unary Operator : Unary operators can be applied on only one operand.
Ex : ++, --, Sizeof, Complement.
ii)
Binary Operators : Binary Operators can be applied on two operands
Ex: +,-,*, etc.
iii)
Ternary operators: Ternary operator can be applied on three operands.
Ex: Conditional operator (?: ).
(2) Based on Nature:
i) Arithmetic operators: +, -, *, /, %
ii) Relational operators: <, >, <=, >=, ==, !=.
iii) Logical operators: &&, ||, !
iv) Assignment operators: =
v) Increment and Decrement operators: ++, -vi) Conditional operators: ?:
vii)
Bitwise operators: &, |, ^, <<, >>, ~
viii) Special operators: comma(,), sizeof.
Q:
Explain the operators in C?
A:
1) Arithmetic operators: These operators are used to develop arithmetic operations.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 26
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Operator
Ex:
Meaning
+
Addition or unary plus
-
Subtraction or unary minus
*
Multiplication
/
Division (quotient)
%
Modulo division (remainder)
#include<stdio.h>
main()
{
int a, b, c, d, e, f, g;
clrscr( );
printf(“\n Enter two numbers”);
scanf(“%d%d”, &a, &b);
c=a+b;
Output:
d=a-b;
e=a*b;
f=a/b;
g=a%b;
printf(“\n Addition=%d”, c);
printf(“\n Subtraction=%d”, d);
printf(“\n Multiplication=%d”, e);
Enter two numbers
20
10
Addition=30
Subtraction=10
Multiplication=200
Division=2
Remainder=0
printf(“\n Division=%d”, f);
printf(“\n Remainder=%d”, g);
}
2) Relational operators: Relational operators are used to make comparisons between
operands. These operators require two operands so these are also called as binary operators.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 27
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Operator
Meaning
==
Equal to
!=
not equal to
<
less than
<=
less than or equal to
>
greater than
>=
greater than or equal to
After comparing the operands, these operators return either true or false.
Ex:
int a=10, b=20;
a==b
returns false
a<b
returns true
a> =b
returns false
3) Logical operators: These operators are used to form compound conditions by combining
two or more relations.
Operator
Meaning
&&
Logical AND
||
Logical OR
!
Logical NOT
Truth table:
Op-1
Op-2
Op-1 && Op-2
Op-1 || Op-2
True
True
True
True
True
False
False
True
False
True
False
True
False
False
False
False
4) Assignment operators: Assignment operators are used to assign values to variables.
Ex: int a=10; here, a is variable and it is assigned with 10.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 28
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
C supports a set of shorthand assignment operators, which are used in the form:
V Op = Exp;
Following are the some of assignment operators: +=, -=, *=, /=, %=
Statement with shorthand assignment operator
a+ =1
a - =1
a* =1
a/ =b
a% =b
Statement with simple assignment operator
a=a+1
a=a–1
a=a*1
a=a/b
a = a% b
5) Conditional operator: The character pair ?: is the conditional operator. It is also called as
ternary operator because it is used on three operands. The general syntax of the conditional
operator is:
exp1 ? exp2 : exp3
The conditional operator works as follows: exp1 is evaluated first, if it is true exp2 is
executed otherwise exp3 is executed.
Ex:
int a=10, b=20;
if(a>b) ? printf(“big value is=%d”,a) : printf(“big value is=%d”,b);
In the above example, exp1 is false so the exp3 is executed. Output is: big value is 20.
6) Special operators: C supports some special operators, they are: i) comma(,) ii) sizeof
Comma operator: It can be used to separate set of expressions and can be used to link the
related expressions together. A comma linked list of expressions are evaluated left to right and
the value of rightmost expression is the value of combined expression.
Ex:
res = (x=10, y=5, x+y);
It first assigns value 10 to x, then assigns 5 to y and finally assigns 15 (i.e. 10+5) to res.
#include<stdio.h>
main( )
{
int a, b;
a= (b=5, b*3);
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 29
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
printf(“\n a=%d”, a);
printf(“\n b=%d”, b);
Output:
a=15
b=5
}
Sizeof operator: This operator returns the number of bytes occupied by a variable or a constant
or a data type in the memory.
Syntax: sizeof(variabe or constant or data type);
Ex:
1) sizeof(int); // it returns 2
2) sizeof(float); // it returns 4
3) double d;
int x;
x=sizeof(d); // it returns 8
4) sizeof(3.4); // it returns 8
7) Increment and Decrement operators:
Increment operator(++): It increments the value of variable by 1 on which it is operating.
There are two types of increment operators. I) pre increment II) post increment.
i) Pre increment operator: It first increment the operand and then the result is assigned to the
variable on the left.
Ex:
int x=3, y;
y= ++x;
In the above statement: x=4, y=4
ii) Post increment operator: It first assigns the value to the variable on the left and then
increment the operand.
Ex:
int x=3, y;
y= x++;
In the above statement: x=4 but y=3.
Decrement operator(--): It decrements the value of variable by 1 on which it is operating.
There are two types of decrement operators. I) pre decrement II) post decrement.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 30
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
iii) Pre decrement operator: It first decrement the operand and then the result is assigned to the
variable on the left.
Ex:
int x=3, y;
y= --x;
In the above statement: x=2, y=2
iv) Post decrement operator: It first assigns the value to the variable on the left and then
decrement the operand.
Ex:
int x=3, y;
y= x--;
In the above statement: x=2 but y=3.
8) Bitwise operators: Bitwise operators are used to perform operations on bits(0 and 1). They
convert the numbers into binary system and then apply bitwise operators.
Operator
Name
&
Bitwise AND
|
Bitwise OR
^
Bitwise XOR
<<
left shift operator
>>
right shift operator
~
complement operator
Bitwise AND(&): It returns 1, when both bits are 1’s otherwise 0.
Ex:
x = 1101
y = 1001
x & y= 1001
Bitwise OR(|): It returns 1, when both or any one of two bits is 1 otherwise 0.
Ex:
x = 1101
y = 1001
x | y= 1101
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 31
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Bitwise XOR(^): It returns 1, only if one of the bits is 1 otherwise 0.
Ex:
x = 1101
y = 1001
x ^ y= 0100
left shift operator(<<); It moves the bits towards leftside and 0’s are added from rigrt.
Ex:
x
= 0000 0000 1011 1101
x<<3 = 0000 0101 1110 1000
Right shift operator(>>): It moves the bits towards right an 0’s are added from left.
Ex:
x
= 0000 0000 1011 1101
x>>3 = 0000 0000 0001 0111
Complement(~): It converts 0’s into 1’s and 1’s into 0’s.
Ex:
x = 0000 0000 0000 1011
~x= 1111 1111 1111 0100
Truth table:
Q:
A:
A
B
A&B
A|B
A^B
1
1
1
1
0
1
0
0
1
1
0
1
0
1
1
0
0
0
0
0
What is an arithmetic expression? And how do you evaluate the expression?
An arithmetic expression is a combination of variables, constants and operators arranged
as per the syntax of the language. C can handle any complex mathematical expressions. Some
of the examples of C expressions are shown below. Remember that C does not have an operator
for exponentiation.
Algebraic expression
C expression
ab-c
a*b-c
(m+n)(x+y)
(m+n)*(x+y)
3x2+2x+1
3*x*x+2*x+1
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 32
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Evaluation of expression: Expressions are evaluated using an assignment statement of the
form:
Variable=Expression;
The expression is evaluated first and then the result is assigned to the variable on the
leftside. All variables used in the expression must be assigned values before evaluation
attempted.
Ex:
x= a*b-c;
y= b/c*a;
z=a-b/c+d;
Precedence of Arithmetic operators: Arithmetic expressions are evaluated according to
BOEDMAS theory, i.e.:
B- Bracket.
O- Off.
E- Exponent.
D- Division.
M- Multiplication.
A- Addition.
S- Subtraction.
Q:
What is Type casting (Type conversion)? (Or)Explain the process of conversion of
variables in C.
A:
Type casting is the process of converting one data type to another data type. It makes the
variables compatible temporarily. Type casting can be of two types.
1. Implicit Type casting
2. Explicit Type casting
Implicit Type casting: When the constants and variables of different types are mixed in an
expression they are converted to the same type. This conversion is done by the ‘C’ compiler.
The compiler converts all the operands to the type of largest operand. For example, int type gets
converted to float type.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 33
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Ex:
float x=3;
printf(“%f”, x); /* prints 3.0 */
Here, the value ‘3’ is automatically converted to 3.0 because of implicit type casting.
Any implicit type conversions are made from a lower size type to a higher size type as shown
below.
short
char
long double
int
unsigned int
double
float
long int
unsigned long int
Explicit Type casting: If a user forcefully changes the data type into other allowable data type
it is said to be explicit type casting.
Ex:
int to float
float x;
x= 5/2;
/* x value will be 2.0 */
x= (float) 5/2;
/* x value will be 2.5 */
float to int
int x;
Q:
x= 3.2;
/* causes error */
x= (int) 3.2;
/* x will be 3 */
Explain control structures in C.
A:
Normally statements in C program are executed sequentially i.e. in the order in which they
are written. This is called Sequential execution. Transfering control to a desired location in a
program is possible through control structure. C allows many kind of control structures, which
include:
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 34
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
I) Conditional control structure ( Decision making with Branching statements)
1. if statement
2. switch statement
3. Conditional operator statement
4. goto statement
II) Looping control structures ( Decision making and Looping (or) Iterative statements)
1. while loop
2. do while loop
3. for loop
III)
Jumping control Structures
1. break (Jumping out of loop)
2. continue (Skipping a part of a loop)
3. exit (Jumping out of the program)
Q:
Explain Decision making and Branching statements (or) Conditional control
structures.
A:
Branching: When a program breaks the sequential flow and jumps to another part of
code is called as branching. C language possesses decision-making capabilities by supporting
the following statements:
1. if statement
2. switch statement
3. Conditional operator statement
4. goto statement
1. Decision making with if statement:
The if statement is a powerful decision-making statement and is used to control the flow
of execution of statements. It is basically a two-way decision statement and is used in
conjunction with an expression. It takes the following form:
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 35
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
if (test expression)
The if statement may be implemented in different forms depending on the complexity of
conditions to be tested. The different forms are:
i. simple if statement
ii. if…. else statement
iii. nested if….else statement
iv. else if ladder.
i) Simple if: The if structure is also called as conditional statement. If the “test expression” is
true then statement-block will be executed. Otherwise the statement-block is skipped and
the execution will jump to the statement-x.
Syntax:
Flowchart:
entry
if( test expression)
{
Statement-block;
test
expression
?
Statement-block
}
Statement-x;
true
false
Statement-x
Ex:
if(x>0)
printf(“x is a positive number”);
ii) if…else: This statement is an extension of simple if statement. In this type of statement if the
condition is true then the “true-block statements” will be executed. Otherwise “falseblock” statements will be executed.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 36
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Syntax:
Flow chart:
if (test expression)
{
True-block statements;
}
else
{
False-block statements;
}
statement-x;
True
entry
test
expression
false
?
True block
statements
False block
statements
Statement-x
Ex:
if(x > y)
printf(“ x is big number”);
else
printf(“y is big number”);
iii) Nesting of if…else: Writing of if…else statement in another if or else statement is called as
Nesting of if…else. In this, if the condition1 is false statement-3 will be executed,
otherwise it continues to perform condition2. If condition2 is true statement-1 is
executed. Otherwise statement-2 is executed.
Syntax:
if(condition1)
{
if(condition2)
{ Statement-1; }
else
{ statement-2; }
}
else
{
Statement-3;
}
Statement-x;
Flowchart:
false
true
Condition1
?
Statement-3
false
true
Condition2
?
Statement-2
Statement-1
Statement-x
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 37
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Ex:
if( a > b)
{
if( a > c)
printf(“ a is big”);
else
printf(“ c is big”);
}
else
{
if( b > c)
printf(“ b is big”);
else
printf(“ c is big”);
}
iv) else…if ladder: There is another way of putting ifs together when multipath decisions are
involved.
Flow chart:
Entry
True
False
Condition1
?
True
Statement-1
False
Condition2
?
True
False
Condition3
?
Statement-2
Statement-3
True
False
Condition n
?
Statement-n
default-statement
Statement-x
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 38
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
This construct is known as else…if ladder. The conditions are evaluated from the top to
downwards. As soon as the true condition is found, the statement associated with it is executed
and the control is transferred to the statement-x. When all the ‘n’ conditions become false, then
the final else containing the default-statement will be executed.
Syntax:
Example:
if(condition1)
statement-1;
if(a>b && a>c)
printf(“a is big”);
else if(condition2)
statement-2;
else if(b>c)
printf(“b is big”);
else if(condition3)
statement-3;
else
printf(“c is big”);
:
:
else if(condition n)
statement-n;
else
default-statement;
statement-x;
2. Decision making with switch statement: It is called as multi-way conditional control
structure. The switch statement tests the value of a given variable (or expression) against a list
of case values and when a match is found, a block of statements associated with that case is
executed. The general form of switch statement is:
Syntax: switch( expression)
{
case value-1:
block-1;
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 39
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
break;
case value-2:
block-2;
break;
:
:
default:
default_block;
break;
}
Statement-x;
The “expression” is an expression or characters. Value-1, value-2,….. are the constants
and are known as case labels.
Flow chart:
Entry
expression
expression=value-1
block-1
expression=value-2
block-2
:
:
(no match found) default
default-block
Statement-x
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 40
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Example: program to display the name of the day depending on the number entered from
keyboard.
#include<stdio.h>
main( )
{
int day;
clrscr( );
printf(“\n Enter a number between (1-7)”);
scanf(“%d”, &day);
switch (day)
{
case 1:
printf(“\n Monday”);
Output:
Enter a number between (1-7)
2
Tuesday
break;
case 2:
printf(“\n Tuesday”);
break;
case 3:
printf(“\n Wednesday”);
break;
case 4:
printf(“\n Thursday”);
break;
case 5:
printf(“\n Friday”);
break;
case 6:
printf(“\n Saturday”);
break;
case 7:
printf(“\n Sunday”);
break;
default:
printf(“\ U entered a wrong number”);
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 41
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
break;
}
}
3. Decision making with Conditional operator: The character pair ?: is the conditional
operator. It is also called as ternary operator because it is used on three operands. The general
syntax of the conditional operator is:
exp1 ? exp2 : exp3
The conditional operator works as follows: exp1 is evaluated first, if it is true exp2 is
executed otherwise exp3 is executed.
Ex:
int a=10, b=20;
if(a>b) ? printf(“big value is=%d”,a) : printf(“big value is=%d”,b);
In the above example, exp1 is false so the exp3 is executed. Output is: big value is 20.
4. Decision making with goto statement: goto is used as a conditional control structure and
looping control structure.
a) Jumping forward:
b) Jumping backward:
statement-1;
statement-1;
goto label;
label:
statement-2;
statement-2;
label:
goto label;
statement-3;
statement-3;
In the Jumping forward after executing statement-1 goto moves the control to the labeled
statement i.e. statement-3. Here statement-2 is not executed.
In the Jumping backward, after statement-1 gets executed statement-2 is executed for
infinite times, because goto moves the control to statement-2 repeatedly.
Example Program for Forward Jump:
# include <stdio.h>
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 42
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
# include <conio.h>
void main( )
{
clrscr ( );
printf(‘\n statement1”);
printf(“\n statement2”);
goto A;
printf (“\n this statement does not execute”);
A:
printf (“\n statement4”);
getch ( );
}
Output:
statement1
statement2
statement4
Example program for Backward jump:
# include <stdio.h>
# include <conio.h>
void main( )
{
int i=1;
clrscr( );
START:
printf (“\t %d”, i);
i++;
Output:
1 2 3 4 5 6 7 8 9 10
if (i<=10)
goto START;
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 43
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
getch( );
}
Q: Explain Looping control structures (Iterative control structures).
A:
The process of repeatedly executing a block of statements is known as looping. In
looping, a sequence of statements are executed until some conditions for the termination of the
loop are satisfied.
Depending on the position of the control statement in the loop, a control structure may be
classified into
i) Entry controlled loop
ii) Exit controlled loop
Entry
Test
Condition
Entry
False
Body of the
Loop
True
Body of the
Loop
Test
Condition
True
False
a) Entry controlled loop
Ex: while, for
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
b) Exit controlled loop
Ex: do-while
Page 44
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
In the Entry controlled loop, the conditions are tested before the start of the loop
execution. If the conditions are not satisfied then the body of the loop will not be executed.
In the Exit controlled loop, the test is performed at the end of the body of the loop and
therefore the body of the loop is executed unconditionally for the first time.
A looping process would include following four steps:
i) Setting and initialization of a counter
ii) Test for a specified condition for execution of the loop
iii) Execution of the statements in the loop
iv) Increment the counter.
i) While loop: The basic form of the while statement is:
Initialization;
while(test condition)
{
condition
True
Body of the loop
Body of the loop
}
False
The while is an Entry controlled loop statement. The test condition is evaluated and if the
condition is true then the body of the loop is executed. After execution of the body, the
condition is once again evaluated and if it is true, the body is executed once again. This process
of repeated execution of body continues until the condition is false.
Ex:
main( )
{
int i=1;
while(i<=10)
{
printf(“\n hello”);
i=i+1;
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 45
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
}
}
Above program prints “hello” for 10 times.
ii) do-while loop: It is an Exit controlled loop statement. The basic form of do-while statement
is:
Initialization;
do
True
{
Body of the loop
Condition
Body of the loop
} while(condition);
False
On reaching the do statement, the program proceeds to evaluate the body of the loop first.
At the end of the loop, the condition is evaluated. If the condition is true once again the body of
the loop is executed.
Ex: main( )
{
int i=1;
do
{
printf(“\n hello”);
i=i+1;
} while(i<=10);
}
The above program prints “hello” for 10 times.
iii) for loop: The for loop is another entry controlled loop, this provide a more concise loop
structure. The basic form of the loop is:
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 46
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
for (initialization ; condition ; increment/decrement)
{
Body of the loop
}
initialization
Condition
True
Body of the loop
Increment/decrement
False
The execution of for loop is as follows:
1. Initialization of control variable is done first, using the assignment statements.
Ex: int i=0, count=1,…. Etc.
2. The value of control variable is tested using the condition. If the condition is true, the
body of the loop is executed, otherwise the loop is terminated.
3. When the body of the loop is executed, the control is transferred back to the for
statement. Now the variable is incremented (or decremented) and the new value of
control variable is again tested using the condition. This process continues until the
condition becomes false.
Ex: main( )
{
int i;
for( i=1 ; i<=10 ; i++)
{
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 47
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
printf(\n hello”);
}
}
The above program prints “hello” for 10 times.
Q:
A:
Explain Jumping control structures.
1. break (Jumping out of loop)
2. continue (Skipping a part of a loop)
3. exit (Jumping out of the program)
i) break:
break stops the corresponding iterative loop. Break is used in switch, while, do-while and for
loops. When break statement is occurred in a loop the loop is immediately exited and the
program continues with the statement immediately following the loop.
Ex:
for(i=1; i<=10; i++)
{
printf(“\n hello”);
if (i= =5)
break;
}
The above program prints “hello” for 5 times.
ii) Continue: It may be necessary to skip a part of the body of the loop under certain
conditions. This can be possible by using continue statement. “continue” is used in loops. It
omits the statements written after “continue” and restarts the iterative loop.
Ex:
for(i=1; i<=5; i++)
{
if(i= =3)
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 48
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
continue;
printf(“%d”, i);
}
The above program prints: 1 2 4 5, it means 3rd iteration is skipped.
iii) exit( ): We can jump out of a program by using the library function exit( ). In case, due to
some reason, we wish to break out of a program and return to the operating system, for this we
can use the exit( ) function, as shown below:
…………
…………
if(test-condition) exit (0);
…………
…………
The exit( ) function takes an integer value as its argument. Normally zero is used to
indicate normal termination and a nonzero value to indicate termination due to some error or
abnormal condition. The use of exit( ) function requires the inclusion of the header file
<stdlib.h>.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 49
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Q:
UNIT-III
What is an Array? What are its advantages and disadvantages?
A:
Array is set of values of similar type. Array elements share common name and stored in
sequential memory locations. An array is a derived data type. To refer the elements of the array,
we use indexes accordingly. Array index starts from “zero” to “array size-1”.
Array variables in C can be declared as follows.
Syntax:
datatype arrayname[size];
here, size is also called as subscript.
Ex: int a[10]; This is an example of an array with 10 elements.
Advantages of Arrays:
 It is capable to store many elements at a time.
 It allows random access of elements, using indexes.
Disadvantages of Arrays:
 Predetermining the size of the array is must.
 Memory wastage will be there.
 To delete an element in the array, you need to traverse (visit) throughout the array.
 To insert an element in the array, you need to traverse (visit) throughout the array.
12 Q: What are the types of arrays? And how do you initialize the arrays.
A:
There are mainly three types of arrays.
1. One dimensional arrays (or) Single Dimensional arrays
2. Two dimensional arrays (or) Double dimensional arrays
3. Multi dimensional arrays
One dimensional array: An array with one subscript is called as One dimensional array or
single subscripted variable.
Syntax:
datatype arrayname[size];
Ex: int a[10];
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 50
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
In the above example, for the array ‘a’ 20 bytes of memory will be allocated.
Initialization of One dimensional array: giving starting values to a variable is called as
initialization. One dimensional array can be initialized as follows:
datatype
Syntax:
arrayname[size] = {value0, value1, value2,……};
Ex: int a[5]= {10, 20, 30, 40, 50};
a
0
1
2
10
20
30
3
4
40
50
In the above example, to access the third element of the array we may use a[2], i.e. the
index of third element is 2.
To print the array, we may write:
for (i=0; i<5; i++)
printf(“%d”, a[i]);
To read the values into a One dimensional array, we may write:
for (i=0; i<5; i++)
scanf(“%d”, &a[i]);
Two dimensional arrays: Array with two subscript values is called as two dimensional arrays,
i.e. it uses two indexes to refer its elements. It represent the data in the form of rows and
columns.
Syntax: datatype arrayname[row-size][col-size];
Ex:
int a[3][3];
In the above example, for the array ‘a’ 18 bytes of memory will be allocated and the array
can hold 9 integers at a time.
Initialization: Two dimensional arrays can be initialized as follows:
int a[3][3]={ {10,20,30}, {40,50,60}, {70,80,90} };
0
1
2
In the above example, a[1][1]=50
0
10
20
30
a[0][2]=30
1
40
50
60
a[2][2]=90
2
70
80
90
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 51
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
To print the array, we may write,
for( i=0; i<3; i++)
{
printf(“\n”;
for( j=0; j<3; j++)
printf(“\t %d”, a[i][j]);
}
To read the values into a double dimensional array, we may write:
for ( i=0; i<3; i++)
for ( j=0; j<3; j++)
scanf(“%d”, &a[i][j]);
Q:
Explain about Dynamic Arrays.
A:
In C it is possible to allocate memory to array at run time. This feature is known as
dynamic memory allocation and the arrays created at run time are called dynamic arrays.
This effectively postpones the array definition to run time.
Dynamic arrays are created using what are known as pointer variables and memory
management functions malloc, calloc and realloc. These functions are included in the header
file <stdlib.h>. The concept of dynamic arrays is used in creating and manipulating data
structures such as linked lists, stacks and queues. In dynamic memory allocation, after our
purpose is served we can release (De-allocation) the memory to avoid blocking of memory
using free( ) function.
malloc( ): It allocates a block of memory dynamically to the program. The general format of
malloc( ) is:
Ex:
int n=10;
int *iptr;
iptr=(int *)malloc(sizeof(int)*n);
In the above example malloc( ) allocates 20 bytes of memory.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 52
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
calloc( ): This function can also be used to allocate memory dynamically. It works similar to
the malloc( ). The difference between these two can be identified in their syntax. The calloc()
function declared in stdlib.h and also in alloc.h. The general format of calloc is:
Ex:
int *p;
p=(int *)calloc(5, sizeof(int));
In the above example calloc( ) allocates 10 bytes of memory.
De-allocation of memory: After utilizing the memory that is allocated using the malloc( ) can
be deleted (released) so that the memory can be used for other purpose. This can be achieved
using free( ) in C.
Syntax:
free( pointer_variable);
Ex:
free(iptr);
Q: What is String (Character array)? How to declare and initialize string variables?
A:
A string is set of characters enclosed in double quotes. As we know that at the end of the
string a null character (\0) stored in the character array. Any group of characters defined
between double quotation marks is a string constant.
Example: “well done!”
Declaring String variables: C does not support strings as a data type. However, it allows to
represent strings as character arrays.
Syntax: char
string_name[size];
Here, size determines the number of characters in the string.
Examples: char city[10];
char name[30];
Initialization of String variables: C permits a string to be initialized in any of the following
forms.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 53
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
 char
city[20] ={‘N’, ‘E’, ‘W’, ‘ ‘, ‘Y’, ‘O’, ‘R’, ‘K’, ’\0’};
(Or)
 char
city[20] = “NEW YORK”;
(Or)
 char
city[ ] = “NEW YORK”;
 Differences between above declarations are, when we declare string as “city[20]”, 20
bytes of memory space is allocated for holding the string value.
 When we declare string as “city[ ]”, memory space will be allocated as per the
requirement during execution of the program.
Q: How to read and write a string?
A:
Reading Strings: This can be done by using scanf( ) and gets( ) functions.
i) Using scanf( ) function: The input function scanf( ) can be used with %s format
specification to read in a string of characters.
Example:
char address[10];
scanf(“%s”, address);
ii) Using gets( ): It is unformatted string input function that reads string from the keyboard.
Syntax:
gets (string-variable);
gets( ) reads string from the keyboard and stores into the string-variable given in the ( ).
This function even stores spaces because it stores enter key as null termination (\0).
Writing Strings: This can be done by using printf( ) and puts( ) functions.
i) Using printf( ) function: The output function printf( ) can be used with %s format
specification to print strings on the screen.
Example:
printf(“%s”, address);
ii) Using puts( ) function: It is unformatted output function that prints strings on the monitor.
The puts( ), after printing the string, it prints the new line character (\n) so that the cursor
moves to next line.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 54
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Syntax: puts(string-variable or constant);
puts( ) prints the given string on the monitor. The string may be a variable or constant but
not both.
Example program:
#include<stdio.h>
#include<conio.h>
void main( )
{
char
name[15];
char
address[20];
clrscr ( );
printf (“\n Enter your name :”);
gets(name);
printf(“\n Enter your address :”);
scanf(“%s”,address);
printf (“\n Your name is :”);
puts(name);
printf(“\n Your address is :%s”,address);
getch( );
}
Output:
Enter your name: Rajkumar
Enter your address: Karimnagar
Your name is: Rajkumar
Your address is: Karimnagar
Q: Explain about String handling functions.
A:
A string is a sequence of characters enclosed with in double quotes (“ “). (Or) A character
Array with null character (\0) is known as string. String functions are declared in the header
file “string.h”.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 55
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Function
Syntax
Description
strlen( )
int strlen(char *s)
Returns length of given string
strcpy( )
void strcpy(char *s1, char *s2)
Copies the string s2 to s1
strcat( )
char strcat(char *s1, char *s2)
Concatenates s1 and s2 to s1
strrev( )
char *strrev(char *s)
Returns the given string in reverse
strupr( )
char *strupr(char *s)
Converts the given string into uppercase
strlwr( )
char *strlwr(char *s)
Converts the given string into lowercase
strcmp( )
int strcmp(char *s1, char *s2)
Compares s1 and s2 and
Returns 0 if s1 and s2 are equal
Returns positive if s1>s2
Return negative if s1<s2
The following programs explains the usage of string functions.
1) Length of a string:
#include<stdio.h>
#include<string.h>
main( )
{
int L;
Output:
Enter a string:
Apple
Length of given string=5
char x[10];
printf(“\n enter a string:”);
scanf(“%s”, x);
L=strlen(x);
printf(“\n length of given string=%d”,L);
}
2) To compare two strings:
#include<stdio.h>
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 56
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
#include<string.h>
Output:
main( )
Enter two strings:
{
Ramesh
char x[10], y[10];
Rajesh
int k;
Ramesh is big
printf(“\n Enter two strings:”);
scanf(“%s”, x);
scanf(“%s”, y);
k= strcmp(x,y);
if(k>0)
printf(“\n %s is big”, x);
else if(k<0)
printf(“\n %s is big”, y);
else
printf(“\n both strings are equal”);
}
3) To concatenate two strings:
#include<stdio.h>
#include<string.h>
main( )
Output:
Enter two strings:
{
char x[10], y[10];
printf(“\n Enter two strings:”);
Hello
Welcome
Strings after concatenation: Hello Welcome
scanf(“%s”, x);
scanf(“%s”, y);
strcat(x,y);
printf(“\n strings after concatenation:%s”, x);
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 57
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
}
4) To copy two strings:
#include<stdio.h>
#include<string.h>
Output:
main( )
Enter a string:
Hello
{
char x[10], y[10];
String copied in y= Hello
printf(“\n Enter a string:”);
scanf(“%s”, x);
strcpy(y, x);
printf(“\n String copied in y=%s”, y);
}
5) To convert into lower and uppercase:
#include<stdio.h>
#include<string.h>
main( )
{
char x[10];
printf(“\n enter a string:”);
Output:
Enter a string:
Apple
String in uppercase=APPLE
String in lowercase=apple
scanf(“%s”, x);
strupr(x);
printf(“\n String in uppercase=%s”, x);
strlwr(x);
printf(“\n String in lowercase=%s”, x);
}
6) To reverse a string:
#include<stdio.h>
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 58
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
#include<string.h>
main( )
{
char x[10];
Output:
Enter a string:
Apple
String after reversing= elppA
printf(“\n enter a string:”);
scanf(“%s”, x);
strrev(x);
printf(“\n String after reversing=%s”, x);
}
Q: Explain typedef with example.
A:
“typedef” is used for giving aliases for data types, i.e. user can give another name for the
data types to be used in the program.
Example:
main ( )
{
typedef int rama;
typedef float F;
rama x=30;
F y=4.5;
printf(“\n %d \t %f”, x, y);
}
In the above example, “rama” and “F” are the aliases for int and float data types.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 59
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
UNIT-IV
1 Q: What is a function? Explain its advantages?
A:
A function is a self contained block of statements that carries out a specific, well defined
task or operation. It is also called as a sub-program (or) module.
Identification of function: After a name, if there is a set of parentheses “( )” then it is said to be
a function.
Ex: printf( ), scanf( ), display( ),…. are functions.
Advantages:
 It improves the understandability of a program.
 It reduces the code.
 It allows reusability. A function can be called any number of times.
 Programs with functions need less maintenance.
Types of functions: Functions are categorized into two. They are
1. System defined functions ( Built-in functions)
2. User defined functions.
Q:
Write about built-in functions.
A:
The functions that are already defined in the system are known as built-in or system
defined functions. These functions should be used in the same manner in which they are given.
Ex: printf( ), scanf( ), sqrt( ), gets( ),….
These functions are also called as “Library functions”. These function declarations are
present in header files like: stdio.h, math.h, string.h, …etc. Some of built-in functions are:
 Mathematical functions
 String functions
 Character functions
 Date functions
Q:
Explain mathematical functions in C?
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 60
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
A:
C supports several mathematical functions. These functions are defined in math.h header
file. To use any of these functions in a program we should include the line: #include<math.h>
Function
Meaning
i) Trigonometric functions:
sin(x)
returns the Sine of angle x in radians
cos(x)
returns the cosine of angle x in radians
tan(x)
returns the tangent of angle x in radians
asin(x)
returns arc sine of x
acos(x)
returns arc cosine of x
atan(x)
returns arc tangent of x
atan2(x,y)
returns arc tangent of x/y
ii) Hyperbolic:
sinh(x)
returns hyperbolic sine of x
cosh(x)
returns hyperbolic cosine of x
tanh(x)
returns hyperbolic tangent of x
iii) Other functions:
ceil(x)
x rounded up to the nearest integer
floor(x)
x rounded down to the nearest integer.
exp(x)
e to the x power (ex)
fabs(x)
absolute value of x
log(x)
natural log of x, x>0
log10(x)
base 10 log of x, x>0
pow(x,y)
x to the power y (xy)
sqrt(x)
Square root of x, x>=0
Q: Explain about String functions.
A:
A string is a sequence of characters enclosed with in double quotes (“ “). (Or) A character
Array with null character (\0) is known as string.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 61
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
String functions are declared in the header file “string.h”.
Function
Syntax
Description
strlen( )
int strlen(char *s)
Returns length of given string
strcpy( )
void strcpy(char *s1, char *s2)
Copies the string s2 to s1
strcat( )
char strcat(char *s1, char *s2)
Concatenates s1 and s2 to s1
strrev( )
char *strrev(char *s)
Returns the given string in reverse
strupr( )
char *strupr(char *s)
Converts the given string into uppercase
strlwr( )
char *strlwr(char *s)
Converts the given string into lowercase
strcmp( )
int strcmp(char *s1, char *s2)
Compares s1 and s2 and
Returns 0 if s1 and s2 are equal
Returns positive if s1>s2
Return negative if s1<s2
Q:
Explain character functions.
A:
The ctype.h header file of the C standard library declares several functions that are
useful for testing and mapping characters.
All the functions accepts int as a parameter, whose value must be EOF or representable
as an unsigned char.All the function return non-zero (true) if the argument c satisfies the
condition described, and zero (false) if not.
1.int
isalnum(int
c):
This
function
checks
whether
the
passed
charter
is
alphanumeric.
2.int isalpha(int c):
3.int
This function checks whether the passed character is Alphabetic.
iscntrl(int c):
This function checks whether the passed character is Control
character.
4.int isdigit(int c): This function checks whether the passed character is decimal digit.
5.int isgraph(int c):
This function checks whether the passed character has graphical
representation using locale.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 62
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
6.int islower(int c):
This
function
checks
whether
the
passed
character
is
Lowercase letter.
7.int isprint(int c): This function checks whether the passed character is printable.
8.int ispunct(int c):
This function checks whether the passed character is a punctuation
character.
9.int isspace(int c): This function checks whether the passed character is white-space.
10.int isupper(int c):
This function checks whether the passed character is an uppercase
letter
11.int isxdigit(int c):
This function checks whether the passed character is a hexadecimal
digit
12.int tolower(int c):
This function converts uppercase letters to lowercase.
13.int toupper(int c): This function converts lowercase letter to uppercase.
Q:
Explain date and time functions.
A:
Date & Time functions in C are used to interact with system routine and formatted date &
time outputs are displayed.
Function
Description
setdate( )
This function used to modify the system date
getdate( )
This function is used to get the CPU time
clock( )
This function is used to get current system time
time( )
This function is used to get current system time as structure
difftime( )
This function is used to get the difference between two given times
mktime( )
This function interprets tm structure as calendar time
localtime( )
This function shares the tm structure that contains date and time
informations
ctime( )
This function is to return string that contains date and time informations
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 63
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Q:
What is the need for user defined functions?
A:
The functions that are defined (or) created by the user (programmer) to perform his own
operations are known as user defined functions.
Ex: display( ), sum( ) are user defined functions, because they are not defined in the computer.
Need for user-defined functions:
main is a specially recognized function in C. Every program must have a main function to
indicate where the program has to begin its execution. While it is possible to code any program
utilizing only main function, it leads to a number of problems. The program may become too
large and complex and as a result the task of debugging, testing and maintaining becomes
difficult. If a program is divided into functional parts, then each part may be independently
coded and later combined into a single unit. These independently coded programs are called
subprograms that are much easier to understand, debug, and test. In C, such subprograms are
referred to as ‘functions’.
This “division” approach clearly results in a number of advantages.
1. It facilitates top-down modular programming as shown in the figure.
2. The length of a source program can be reduced by using functions at appropriate places.
This factor is particularly critical with microcomputers where memory space is limited.
3. A function may be used by many other programs. This means that a C programmer can
build on what others have already done, instead of starting all over again from scratch.
Main Program
Function A
Function B
B1
Function C
B1
Top-down modular programming using functions
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 64
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Q: Explain the procedure to create a function? (Or) What are the components (elements)
of a function?
A:
Any function whether it is a system or user defined, should contain three main
components. They are:
1. Function prototype or function declaration
2. Definition of function
3. Function call
Function prototype: Before the function is defined in the program, the function name and its
details should be provided to the compiler. It can be done by declaring the function above the
main function is called as “Prototype of a function” or “forward declaration of function”.
Syntax:
return_type function_name ( [parameters list] );
Ex: void message( );
Definition of function: It is the actual function that contains programming statements to
perform the operation of function. The programming statements should be written between “{
}”. The header of definition of function should be similar to the prototype of function but the
difference is prototype should end with semicolon(;), whereas definition should not. The
definition should be written outside all functions. Definition of function is also called as
“Called function”.
Syntax: return_type function_name( [parameters list] )
{
Programming statements;
}
Ex:
void message( )
{
printf(“\n This is sample function”);
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 65
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Function call: Defining the function does not do anything without execution. To execute the
function, it should be called. A function can be called by the name of the function and such
statement is known as “Function call”. And it is also called as “calling function”.
Syntax:
function_name( [parameters list] );
Ex: message( );
Let us write the complete program by creating the function “message( )”.
#include<stdio.h>
void message( );
Function prototype
main( )
{
message( );
Function call ( calling function)
message( );
Function call ( calling function)
}
void message( )
called function
{
printf(“\n This is sample function”);
}
Argument (Parameter): Argument is a value or variable which we can pass to a function. The
arguments present in calling function are known as “actual arguments” and the arguments
present in called function are known as “Formal arguments”.
Q:
What are return values and their types?
A:
A function may or may not send back any value to the calling function. If it does, it is
done through the return statement. While it is possible to pass to the called function any
number of values, the called function can only return one value per call, at the most.
The return statement can take one of the following forms:
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 66
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
return;
or
return (expression);
The first, the ‘plain’ return does not return any value; it acts much as the closing brace of the
function. When a return is encountered, the control is immediately passed back to the calling
function. An example of the use of a simple return is as follows:
if(error)
return;
The second form of return with an expression returns the value of the expression. For
example, the function
int mul(int x, int y)
{
int p;
p=x*y;
return(p);
}
returns the value of p which is the product of the values of x and y. The last two statements can
be combined into one statement as follows:
return (x*y);
A function may have more than one return statement. This situation arises when the
value returned is based on certain conditions. For example:
if(x < = 0)
return(0);
else
return(1);
What type of data dose a function return? All functions by default return int type data.
But what happens if a function must return some other type? We can force a function to return a
particular type of data by using a type specifier in the function.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 67
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
When a value is returned, it is automatically cast to the function’s type. In functions that
do computations using doubles, yet return ints, the returned value will be truncated to an
integer. For instance, the function
int product (void)
{
return (2.5 * 3.0);
}
will return the value 7, only the integer part of the result.
Q:
What are Recursive functions?
A:
If a function is called within the same function, is said to be recursion. It means recursion
is the process by which a function calls itself; such function is called as recursive function.
Recursion is again of 1) linear recursion and 2) non- linear recursion
Linear recursion: If a function is called itself only once then such functions are said to be
linear recursive functions.
Non-Linear recursion: If a function is called itself more than one time such functions are said
to be non-linear recursive functions.
void main( )
{
void main( )
{
A( );
}
A( );
}
void A( )
{
void A( )
{
:
A( );
A( );
:
:
A( );
}
:
}
Linear recursive function
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Non-linear recursive function
Page 68
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Ex: To find the factorial of a given number, the recursive logic is as follows
#include<stdio.h>
int factorial( int n);
main( )
{
int n, fact;
clrscr( );
printf(“\n Enter a number”);
Output:
Enter a number
5
Factorial of 5 is 120
scanf(“%d”, &n);
fact= factorial(n);
printf(“\n factorial of %d is=%d”, n, fact);
}
int factorial( int n)
{
if( n= = 1)
return 1;
else
return (n* factorial(n-1));
}
When the above program gets executed, the order of the execution is as follows for n=5:
factorial(5) = 5*factorial(4)
= 5*4*factorial(3)
= 5*4*3*factorial(2)
= 5*4*3*2*factorial(1)
= 5*4*3*2*1 = 120
Q:
Explain different ways of writing a function? (Or) What are the types of functions
based on argument and return type?
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 69
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
A:
In c a function can be written in four different ways.
1. No Argument, No Return (Or) Function without argument & without return type
2. Argument, No Return
(Or) Function with argument & No return value
3. No Argument, Return
(Or) Function without argument & with return type
4. Argument, Return
(Or) Function with argument & with return type
1. No Argument, No Return: A function, which does not take any arguments and does not
return any value.
Ex:
#include<stdio.h>
void message( );
main( )
Output:
{
This is sample function
This is sample function
message( );
message( );
}
void message( )
{
printf(“\n This is sample function”);
}
2. Argument, No Return: A function, which takes arguments, but do not return any value.
Ex:
#include<stdio.h>
void sum( int x, int y);
main( )
{
clrscr( );
sum( 10, 20);
sum( -5, 25);
}
void sum( int x, int y)
{
int z= x+y;
printf(“\n Sum= %d”, z);
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Output:
Sum=30
Sum= 20
Page 70
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
3. No Argument, Return: A function, which does not take arguments but returns a value.
Ex:
#include<stdio.h>
int sum( );
main()
{
int k;
Output:
clrscr( );
Sum=30
k= sum( );
printf(“\n Sum=%d”, k);
}
int sum( )
{
int x=10, y=20;
return (x+y);
}
4. Argument, Return: A function, which takes argument and returns a value.
Ex:
#include<stdio.h>
int sum( int x, int y);
main( )
{
int k;
clrscr( );
Output:
k= sum( 20, 30);
Sum=50
printf(“\n Sum=%d”, k);
}
int sum( int x, int y)
{
return (x+y);
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 71
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Q:
Explain different ways of parameter passing techniques? (or) Demonstrate call by
value, call by reference?
A:
C provides two types of mechanisms to pass arguments (parameters) to a function. They
are:
1. Passing argument by value (or) call by value (or) pass by value
2. Passing argument by address (or) call by reference (or) pass by reference
Call by value: It is also called as pass by value. In this method, the values of arguments are
passed from calling function to the parameters of called function. Since, if any changes made to
the arguments in the called function (function definition) do not reflects in the arguments of
calling function.
Ex:
#include<stdio.h>
void swap(int x, int y);
main( )
{
int a=10, b=20;
Output:
a=10, b=20
after swapping: a=10, b=20
clrscr( );
printf(“\n a=%d, b=%d”, a, b);
swap(a,b);
printf(“\n after swapping: a=%d, b=%d”, a, b) ;
}
void swap(int x, int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 72
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
In the above example, swapping is done in the parameters of called function(x, y) only,
whereas these changes are not made in the arguments of calling function (a, b).
Call by reference: It is also called as pass by reference. In this method, the addresses of
arguments are passed to the parameters of called function (function definition). Since, the
parameters should be declared as pointers. When we make any changes to the parameters of
called function, those changes reflects in the arguments of calling function.
Ex:
#include<stdio.h>
void swap(int *x, int *y);
main( )
{
int a=10, b=20;
clrscr( );
Output:
a=10, b=20
after swapping: a=20, b=10
printf(“\n a=%d, b=%d”, a, b);
swap(&a, &b);
printf(“\n after swapping: a=%d, b=%d”, a, b) ;
}
void swap(int *x, int *y)
{
int temp;
temp= *x;
*x= *y;
*y=temp;
}
In the above example, if we make any changes to the parameters of called function, that
changes reflects in the arguments of calling function.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 73
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
UNIT-V
Q:
What is structure? Explain how to declare structure variables and accessing
structure members.
A:
Structure is a derived data type. A structure variable can hold set of dissimilar (different)
or similar values.
Creation of a structure is of two step process:
i) Defining the structure template
ii) Declaring structure variables
Defining structure template: structure template can be defined by using following syntax:
struct
tag-name
Here, “struct” is the keyword which is used to create a
structure. “tag-name” is the name of the structure. The
{
data-type member1;
list of variables declared in between { and } are known
data-type member2;
as “structure members” or “member variables”.
:
};
Example:
struct
student
{
char name[15];
int rno;
int marks;
};
Declaring structure variables: Memory is allocated to the structure members when structure
variables are declared. A structure variable declaration is similar to the declaration of variables
of any other data types. It includes the following elements:
1. The keyword “struct”.
2. The structure tagname.
3. List of variable names separated by commas.
4. A terminating semicolon.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 74
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
tag-name
var1, var2, var3, ……;
Syntax:
struct
Example:
struct student s1, s2;
Accessing structure members: We can access and assign values to the members of a structure
in a number of ways. Normally, members of a structure are accessed by using structure variable
name followed by a dot (.) operator.
Syntax:
structurevariable. membervariable;
Example:
strcpy(s1.name, “Ravi”);
s1.rno=35;
s1.marks=98;
s2.name=”Raju”;
s2.rno=45;
s2.marks=95;
Let us write complete program:
#include<stdio.h>
main( )
Memory
S1
name
Ravi
rno
35
marks
98
{
struct
student
{
char name[15];
int
rno;
int
marks;
};
Output:
Ravi 35
98
struct student s1;
clrscr( );
strcpy(s1.name, “Ravi”);
s1.rno=35;
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 75
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
s1.marks=98;
printf(“%s \t %d \t %d”, s1.name, s1.rno, s1.marks);
}
In the above example, student is the tag-name and it consist of three different properties
“name”, “rno”, “marks”. These are called as structure members. “s1” is the structure variable of
student. The members of a structure are accessible with dot (.).
Q:
Explain Structure initialization.
A:
Data members of a structure can be initialized at the point of its declaration. Members of
a structure are initialized inside a pair of braces.
Ex: struct bank b1={“ramesh”, 120, 15000};
Example program:
#include<stdio.h>
Memory
b1
name
Ramesh
acno
120
main( )
{
struct bank
amount
15000
{
char name[20];
Output:
int acno;
Name= Ramesh
int amount;
AccountNo=120
};
struct bank b1={“ramesh”, 120,15000};
Amount=15000
/* structure initialization */
clrscr( );
printf(“\n Name=%s”, b1.name);
printf(“\n AccountNo=%d”, b1.acno);
printf(“\n Amount=%d”, b1.amount);
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 76
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Q:
Explain Functions and Structures?
A:
Structure variables can also be passed from calling function to called function in the same
way as the normal variables are passed. When the structure variable is passed to a function the
entire structure is copied into the receiving formal parameter variable.
The general format of sending a copy of a structure to the called function is:
function_name(structure_variable_name);
The called function takes the following form:
data_type function_name(struct_type
st_name)
{
…………….
…………….
}
Ex:
#include<stdio.h>
struct student
Memory
S1
s
name
chandu
name
chandu
char name[20];
rno
24
rno
24
int rno,marks;
marks
95
marks
95
{
};
void display(struct student s);
main( )
Output:
{
Name=chandu
struct student s1={"chandu",24,95};
clrscr( );
Roll No= 24
Marks=95
display(s1);
}
void display(struct student s)
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 77
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
{
printf(“\n Name=%s”, s.name);
printf(“\n Roll No=%d”, s.rno);
printf(“\n Marks=%d”, s.marks);
}
Q:
What are arrays of structures?
A:
Array is a set of similar values, whereas array of structures is a set of structure variables.
It means structure variables can also be array.
Ex:
#include<stdio.h>
main( )
Memory
0
{
int i;
s
struct student
name
rno
{
marks
1
sri
15
98
name
rno
marks
nivas
25
85
2
name
rno
marks
shiva
35
89
char name[15];
int rno, marks;
};
struct student s[3]={“sri”, 15, 98, “nivas”, 25, 85, “shiva”, 35, 89};
clrscr( );
for(i=0; i<3; i++)
printf(“\n %s \t %d \t %d”, s[i].name, s[i].rno, s[i].marks);
}
Output of above program is:
sri
15
98
nivas 25
85
shiva 35
89
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 78
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Q:
What is Enumerated data type? Explain with an example.
A:
Enumeration is a way of defining user defined data type. It allows us to declare string
constants with integer equivalent values. The general format of an enumeration declaration is:
enum tag-name
{
member_1, member_2, member_3, ……., member_n
};
The members of the enumerations are automatically assigned with consecutive constant
values starting from 0. Also a variable can be declared to enumeration by following syntax:
enum tag-name variable1, variable2,…….;
Example:
#include<stdio.h>
main( )
{
enum colors{red=10, green=20, blue=30 };
enum colors c1,c2;
clrscr( );
Output:
10
30
c1=red;
c2=blue;
printf(“\n %d \t %d”, c1,c2);
}
Q:
What is a Union? Explain with example.
A:
Union is a derived data type. It is also like a structure, except that only one variable in the
union is stored in the allocated memory. It means that all the members of union can share same
physical memory. Size of a union variable is the size of its largest member variable. A union is
defined as follows:
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 79
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Syntax:
union tag-name
{
data-type member-variable1;
data-type member-variable2;
:
};
Example:
#include<stdio.h>
main( )
{
union alpha
{
int a;
float b;
};
union alpha a1;
clrscr( );
a1.a=30;
printf("\n a=%d",a1.a);
a1.b=20.5;
printf("\n b=%f",a1.b);
}
In the above example, the size of the alpha would be 4 bytes.
Q:
An employee information consists of Name 20 characters, age, designation 10
characters, Net_pay. Define the structure.
A:
The structure with the given members can be defined as follows:
struct employee
{
char name[20];
int age;
char desg[10];
int net_pay;
};
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 80
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
To create a structure variable of that type and give values, we use the following:
struct employee e1={“srinu”, 30, “manager”, 25000};
printf(“\n %s \t %d \t %s \t %d”, e1.name, e1.age, e1.desg, e1.net_pay);
Q:
Compare Structure and Union. (Or) Write differences between structures and
unions.
A:
Unions
Structures
1. It is a user defined data type.
1. It is also a user defined data type.
2. Structures are declared with the keyword
2. Unions are declared with the keyword
“union”.
“struct”.
3. Each variable in the structure is allocated
3. All the variables in the union is allocated
with common memory.
with separate memory.
4. The size of the structure is equal to the
4. The size of the union is equal to the
largest variable inside the union.
sum of sizes of all variables inside the
structure.
5. Structure occupies more memory.
5. Union occupies less memory.
6. All the members of the structure are
6. All the members of the union are
accessed with dot (.).
accessed with dot (.).
Q:
What is a pointer? What are its advantages and disadvantages?
A:
Pointer variable is a variable that holds the address of another variable of same type.
Pointing to an address variable gives the value at that address.
Advantages of pointers:
 It allows dynamic memory allocation.
 It allows call by reference mechanism for arguments.
 Pointers improve the efficiency of the program.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 81
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Disadvantages of pointers:
 Pointer variables require extra memory
 Programmer finds writing pointers tiresome.
Let us consider an example, int a=30, here
‘a’ is the name of the variable.
‘&a’ is the address of the variable.
30 is the value of the variable.
Understanding pointers:
The computer’s memory is a sequential collection of storage cells. Each cell, commonly
known as a byte, has a number called address associated with it. Typically, the addresses are
numbered consecutively, starting from zero. The last address depends on the memory size. A
computer system having 64 K memory will have its last address as 65,535.
Memory Cell
Address
0
1
2
3
4
5
:
:
65,535
Memory Organization
Whenever we declare a variable, the system allocates, somewhere in the memory, an
appropriate location to hold the value of the variable. Since, every byte has a unique address
number this location will have its own address number.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 82
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Accessing the address of a variable:
The actual location of a variable in the memory is system dependent and therefore, the
address of a variable is not known to us immediately. How can we then determine the address
of a variable? This can be done with the help of the operator & available in C. we have already
seen the use of this address operator in the scanf function. The operator & immediately
preceding a variable returns the address of the variable associated with it. For example, the
statement
P = &quantity;
Would assign the address 5000 (the location of quantity) to the variable p. The & operator can
be remembered as ‘address of’.
The & operator can be used only with a simple variable or an array element. The
following are illegal use of address operator:
1. &125
(pointing at constants).
2. int x[10];
&x
(pointing at array names).
3. &(x + y)
(pointing at expressions).
If x is an array, then expressions such as
&x[10] and &x[i+3]
are valid and represent the addresses of 10th and (i+3)th elements of x.
Q:
How do you declare a pointer?
A:
Pointer variables can be declared in the same way as we declare normal variables. Pointer
variables are declared by using the ( * ) operator.
Syntax:
Ex:
datatype
*pointervariable_name;
int *p;
float *iptr;
Example program using pointers:
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 83
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
#include<stdio.h>
main( )
n
101 102
10
p
201 202
101
{
int n=10, *p;
p= &n;
printf(“%d”, n);
/* prints 10 */
printf(“%d”, *p);
/* prints 10 */
printf(“%d”, *(&n));
/* prints 10 */
printf(“%u”, p);
/* prints the address*/
}
Q: What is a file, file management? What are the file operations?
A:
File is a collection of information or group of records. (OR) File is a place where group
of related data is stored. File management is a methodology provided in C to deal with the files.
File management includes following transactions (file operations).
 Creating a file/Naming a file
 Opening a file
 Closing a file
 Reading data from the file
 Writing data to the file
 Deleting a file

Renaming a file
Modes of opening a file: In C, a file can be opened in different modes. The details are shown
below.
Mode
Meaning
Description
“r”
Read
Opens a file for reading content, returns NULL if file does not
exist
“w”
Write
Opens a file for writing. It overwrites if the file exists and
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 84
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
returns NULL if it fails to create a file.
“a”
Append
Opens a file for appending, creates if it does not exist.
“r+”
Read/ Write
Opens a file for both reading and writing. File must exist.
“w+”
Read/Write
Opens a file for both reading and writing. Creates a file it does
not exist and over writes if it is existing.
“a+”
Read/ Append
Opens a file for both reading and appending. Creates a file if
it does not exist.
“rb”
Read binary
Opens a file for reading in binary mode.
“wb”
Write binary
Opens a file for writing in binary mode.
Q: Explain different File input, output functions.
A:
File functions are defined in “stdio.h”. These functions can be used to manage the files
i.e. performing file transactions such as creating a file, reading a file and copying a file and etc.
Functions
Description
fopen(fname, mode)
To open a file in specified mode
fclose(fp)
To close a file pointed by the file pointer
fputc(ch, fp)
To write characters into a stream
fgetc(fp)
To read characters from a stream
putw(i, fp)
To write integers into a stream
getw(fp)
To read integers from a stream
fputs(s, fp)
To write strings into a stream
fgets(fp)
To read strings from a stream
fprintf(fp, s, arg.…)
To write formatted text into a stream
fscanf(fp, s, add....)
To read formatted text from a stream
fwrite(void*, size, size, fp)
To write user defined types into a stream
fread(void*, size, size, fp)
To read user defined types from a stream
rewind(fp)
To move a file pointer to the beginning of the file stream
unlink(fname)
To delete a specified file
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 85
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
rename(source, target)
To change the name of the file
FILE *fp, char ch, int i, char *s, arg-arguments, add- addresses, char *fname
Q: What is a file? Explain the method of i) opening a file ii) closing a file iii) writing a
character iv) reading a character of a file?
A:
A file is a collection of information. Whenever we enter data, the data moves into
temporary buffer, but not stored permanently. If we want to store the data permanently, we
should use files. Information stored in the file is permanent in the computer. Until and
otherwise we delete the file from computer, information in the file exist in the computer.
Opening a file: To perform input and output operations i.e. reading and writing contents of a
file, the file should be opened.
To create a new file or open an existing file in C, fopen( ) can be used. But while
opening a file we should specify the mode in which it should be opened. Following is the
general format for declaring an opening a file is:
FILE *fp;
fp= fopen(char *filename, char *mode);
Example:
FILE *fp;
fp= fopen(“a.txt”, “r”);
The above code opens the file in read mode, it returns file pointer. If the file not exists
“fp” will have NULL when opened in read mode.
Closing a file: When a file is opened for input and output operations, it should be closed after
performing all the required operations. We use “fclose( )” function to close a file.
Syntax:
fclose(file_pointer);
Example:
fclose(fp);
Writing a character to a file: If we want to write characters into a file, we will use “fputc( )”
function. To write characters, the file must be opened in write mode.
Syntax:
fputc(character, FILEpointer);
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 86
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Example:
1. fputc(‘A’, fp);
2. char ch=’B’;
fputc(ch, fp);
Reading a character from a file: If we want to read characters from a file, we will use “fgetc(
)” function. To read characters, the file must be opened in read mode.
Syntax:
fgetc(FILEpointer);
Example:
fgetc(fp);
A program to read and write characters into a file.
#include<stdio.h>
#include<conio.h>
void main( )
{
Output:
FILE *fp;
File successfully created: sample.txt
clrscr( );
File reading:APPLE
fp=fopen(“sample.txt”, “w”);
if(fp= =NULL)
{
printf(“\n file unable to create: sample.txt”);
exit(1);
}
else
{
printf(“\n file successfully created: sample.txt”);
}
fputc(‘A’, fp);
fputc(‘P’, fp);
fputc(‘P’, fp);
fputc(‘L’, fp);
fputc(‘E’, fp);
rewind(fp);
fp=fopen(“sample.txt”, “r”);
if(fp= =NULL)
{
printf(“\n file unable to read”);
exit(1);
}
else
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 87
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
{
printf(“\n file reading:”);
}
printf(“%c”,fgetc(fp));
printf(“%c”,fgetc(fp));
printf(“%c”,fgetc(fp));
printf(“%c”,fgetc(fp));
printf(“%c”,fgetc(fp));
fclose(fp);
getch( );
}
Steps to open C Editor
 Click on START button and then click on RUN.
 Type ‘command’ or ‘cmd’ in RUN dialog box then click on OK
 It opens console with: c:\ Documents and Settings>
 C:\Documents and Settings> cd\
 C:\> cd tc2
(OR) c:\> cd tc
 C:\TC2>tc
(OR) c:\TC> tc
 It opens TurboC editor.
Steps to execute a C program
 Open C editor.
 To write a new program press ALT+F and select “New” option.
 Write program in C editor.
 Save the program for further use ( by pressing F2)
 Compile the program (Alt+F9)
 Execute or run the program (Ctrl+F9)
 Get output (Alt+F5)
 To exit from the C editor press ALT+F and select “Quit” option.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 88
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
FACULTY OF COMMERCE, SATAVAHANA UNIVERSITY, KNR
B.Com.(Computer Applications) CBCS, Semester-II
Subject: PROGRAMMING WITH C
Computer Lab- Practical Question Bank
Time: 2 hrs
Record
: 05
Skill Test : 15
Total Marks : 20
1. Write a program to find largest of three numbers using ternary operator.
2. Write a program to check whether the given number is palindrome or not
3. Write a program to print the prime numbers in given range. (mininum and maximum
vaiues be accepted from the user).
4. Create a menu driven application using switch to find addition, subtraction,
multiplication and division of two numbers.
5. Write a program to sort the elements of an array using bubble sort technique.
6. Write a program to search an element in an array using binary search method.
7. Write a program to perform matrix multiplication.
8. Write a program to find factorial of a given number using recursion.
9. Write a program to print Fibonacci numbers using recursion(0 1 1 2 3 5 8…)
10. Write a program to demonstrate local and global variables.
11. Write a program to demonstrate auto and static variables.
12. Write a program to concatenate two strings with and without using string functions.
13. Write a program, to sort the strings, passing array to function.
14. Write a program to find area of a circle using macros.
15. Write a program to find length of string using pointers and functions.
16. Write a program to swap two values using parameter passing mechanism.
17. Write a program to create a structure, store the values and display them.
18. Write a program to create array of student objects.
19. Write a program to demonstrate passing structures to functions using pointers.
20. Write a program to demonstrate Nesting of structures.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 89
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
1. Write a program to find largest of three numbers using ternary operator.
#include<stdio.h>
#include<conio.h>
void main( )
Output:
{
Enter three numbers
int a, b, c, big;
10
clrscr();
25
printf("\n Enter three numbers");
15
scanf("%d%d%d",&a,&b,&c);
The biggest number is=25
big=(a>b&&a>c?a:b>c?b:c);
printf("\n The biggest number is=%d",big);
}
2. Write a program to check whether the given number is palindrome or not.
#include<stdio.h>
#include<conio.h>
void main( )
{
Output:
int n, rem, rev=0, dup;
Enter a number
clrscr( );
323
printf(“Enter a number”);
Palindrome
scanf(“%d”, &n);
dup=n;
while(n>0)
{
rem = n%10;
rev = rev*10+rem;
n= n/10;
}
if(dup = = rev)
printf(“\nPalindrome”);
else
printf(“\n Not palindrome”);
getch( );
}
3. Write a program to print the prime numbers in given range. (mininum and
maximum vaiues be accepted from the user).
#include<stdio.h>
#include<conio.h>
void main( )
{
int min, max, flag, temp, count=0,i, j;
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 90
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
clrscr( );
printf("\n enter min and max values");
scanf("%d%d", &min, &max);
if(min<2)
{
printf("\n there are no primes upto 2");
exit(0);
}
printf("\n prime numbers are:\n");
temp=min;
if(min%2= =0)
{
Output:
min++;
enter min and max values
}
70
for (i=min;i<=max;i=i+2)
85
{
prime numbers are:
flag=0;
71
for (j=2;j<=i/2;j++)
73
{
79
if (i%j==0)
83
{
number of prime numbers between 70
flag=1;
&85=4
break;
}
}
if(flag==0)
{
printf ("%d\n",i);
count++;
}
}
printf ("\n number of prime numbers between %d &%d=%d", temp, max, count);
}
4. Create a menu driven application using switch to find addition, subtraction,
multiplication and division of two numbers.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a, b, ch;
clrscr( );
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 91
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
printf(“\n Enter two numbers”);
scanf(“%d%d”, &a, &b);
printf(“\n Menu \n 1.Addition \n 2.Subtraction \n
3.Multiplication \n4. Division”);
printf(“\n Enter your choice”);
scanf(“%d”, &ch);
switch(ch)
{
case 1: printf(“\n Sum=%”, a+b);
break;
case 2: printf(“\n Difference=%d”, a-b);
break;
case 3: printf(“\n Multiplication=%d”, a*b);
break;
case 4: printf(“\n Division=%d”, a/b);
break;
case 5: printf(“\n Remainder=%d”, a%b);
break;
default:
printf(“\n Invalid option”);
break;
}
getch( );
Output:
Enter two numbers
5
6
Menu
1.Addition
2.Subtraction
3.Multiplication
4. Division
Enter your choice
3
Multiplication=30
}
5. Write a program to sort the elements of an array using bubble sort technique.
#include<stdio.h>
#include<conio.h>
Output:
main ( )
Enter size of the array
5
{
Enter 5 elements
int a[10], i, j, n, temp;
6
clrscr( );
4
printf(“\n Enter size of the array”);
7
scanf(“%d”, &n);
1
printf(“\n Enter %d elements”, n);
5
Elements after sorting:
for(i=0; i<n; i++)
1
scanf(“%d”, &a[i]);
4
for(i=0; i<n-1; i++)
5
{
6
for(j=i+1; j<n; j++)
7
{
if(a[i] > a[j])
{
temp= a[i];
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 92
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
a[i]= a[j];
a[j]= temp;
}
}
}
printf(“\n Elements after sorting:”);
for(i=0; i<n; i++)
printf(“\n %d”, a[i]);
}
6. Write a program to search an element in an array using binary search method.
#include<stdio.h>
#include<conio.h>
main( )
{ int a[10], low, high, mid, key, n, i, found=0;
clrscr( );
printf(“\n Enter size of the array”);
scanf(“%d”, &n);
printf(“\n Enter %d elements in sorted order”, n);
for(i=0; i<n; i++)
scanf(“%d”, &a[i]);
printf(“\n Enter searching element”);
scanf(“%d”, &key);
low = 0;
high = n-1;
mid = (low + high)/2;
while( low < = high)
{
if ( key = = a[mid])
{
printf(“\n Element found at %d index
position”, mid);
found = 1;
break;
}
else if( key < a[mid] )
{
high = mid-1;
}
else if( key > a[mid] )
{
low = mid+1;
}
mid = (low + high)/2;
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Output:
Enter size of the array
10
Enter 10 elements in sorted order
10
20
30
40
50
60
70
80
90
100
Enter searching element
60
Element found at 5 index position
Page 93
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
if ( found = = 0)
printf(“\n element not found”);
}
7. Write a program to perform matrix multiplication.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[3][3], b[3][3], c[3][3], i, j, k;
clrscr( );
printf(“Enter values into 1st matrix”);
for(i=0; i<3; i++)
for(j=0; j<3; j++)
scanf(“%d”, &a[i][j]);
Output:
printf(“\n Enter values into 2nd matrix”);
Enter values into 1st matrix
for(i=0; i<3; i++)
1
2
1
for(j=0; j<3; j++)
3
2
1
scanf(“%d”, &b[i][j]);
1
2
3
for(i=0; i<3; i++)
Enter values into 2nd matrix
for(j=0; j<3; j++)
1
2
1
{
3
2
1
c[i][j]=0;
1
2
3
for(k=0; k<3; k++)
Matrix multiplication is:
c[i][j]= c[i][j]+a[i][k]*b[k][j];
8
8
6
}
8
12
8
printf(“\n Matrix multiplication is:\n”);
10
12
11
for(i=0; i<3; i++)
{
printf(“\n”);
for(j=0; j<3; j++)
printf(“\t %d”, c[i][j]);
}
getch( );
}
8. Write a program to find factorial of a given number using recursion.
#include<stdio.h>
#include<conio.h>
int factorial( int n);
void main( )
{
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 94
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
int n, fact;
Output:
clrscr( );
Enter a number
printf(“\n Enter a number”);
5
scanf(“%d”, &n);
Factorial of 5 is 120
fact= factorial(n);
printf(“\n Factorial of %d is=%d”, n, fact);
getch( );
}
int factorial( int n)
{
if( n= = 1)
return 1;
else
return (n* factorial(n-1));
}
9. Write a program to print Fibonacci numbers using recursion(0 1 1 2 3 5 8…)
#include <stdio.h>
int fib(int);
void main( )
{
int n, i=0, c;
Output:
clrscr( );
enter range of values
printf ("\n enter range of values");
8
scanf ("%d",&n);
fibonacci series
printf ("\n fibonacci series \n");
0
for (c=1; c<=n; c++)
1
{
1
printf ("%d\n",fib(i));
2
i++;
3
}
5
}
8
int fib(int n)
13
{
if (n= =0)
return 0;
else if (n= =1)
return 1;
else
return(fib(n-1)+ fib(n-2));
}
10. Write a program to demonstrate local and global variables.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 95
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Local variable:
#include<stdio.h>
void sample( );
main( )
{
int a=10;
printf(“\n a=%d”, a);
sample( );
}
void sample( )
{
int b=20;
printf(“\n b=%d”, b);
a= a+20;
Error because ‘a’ is a local variable of main ( ).
}
Global variable:
#include<stdio.h>
void sample( );
int a=10;
Output:
main( )
Value of a before sample=10
{
Value of a after sample=20
clrscr( );
printf(“\n value of a before sample=%d”, a);
sample( );
printf(“\n value of a after sample=%d”, a);
}
void sample( )
{
a=a+10;
}
11. Write a program to demonstrate auto and static variables.
auto:
# include<stdio.h>
void increment(void);
void main ( )
{
increment( );
increment( );
increment( );
increment( );
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 96
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
void increment(void)
{
auto int i= 0;
printf(“%d”, i);
i++;
}
Output: 0000
Static:
#include<stdio.h>
void increment(void);
void main( )
{
increment( );
increment( );
increment( );
increment( );
}
void increment(void)
{
static int i = 0;
printf(“%d”, i);
i++;
}
Output: 0 1 2 3
12. Write a program to concatenate two strings with and without using string functions.
With string function:
#include<stdio.h>
#include<string.h>
main( )
Output:
{
Enter two strings:
char x[10], y[10];
Hello
printf(“\n Enter two strings:”);
Welcome
scanf(“%s”, x);
Strings after concatenation: Hello Welcome
scanf(“%s”, y);
strcat(x,y);
printf(“\n strings after concatenation:%s”, x);
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 97
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
Without string function:
#include <stdio.h>
void main( )
{
char s1 [25], s2 [25];
Output:
int i=0, j=0;
enter first string
clrscr( );
Sri
printf ("\n enter first string\n");
enter second string
gets(s1);
Vaagdevi
printf ("\n enter second string\n");
concatenated string is SriVaagdevi
gets (s2);
while (s1[i] !='\0')
i++;
while (s2[j]!='\0')
{
s1[i]=s2[j];
j++;
i++;
}
s1[i]='\0';
printf ("\n concatenated string is %s", s1);
}
13. Write a program, to sort the strings, passing array to function.
#include<conio.h>
#include<stdio.h>
Output:
enter no of string to be sorted
#include<string.h>
3
void main( )
Enter the string 1
{
welcomes
int i, n=0;
Enter the string 2
char *s[20];
vaagdevi
void sort(int n,char *s[ ]);
Enter the string 3
sri
clrscr( );
printf("\n enter no of string to be sorted");
reorder list is:
scanf("%d",&n);
1sri
for(i=0; i<n; i++)
2vaagdevi
{
3welcomes
printf("\n Enter the string %d", i+1);
s[i]=(char *)malloc(20*sizeof(char));
scanf("%s", s[i]);
}
sort(n, s);
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 98
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
printf("\n reorder list is:\n");
for(i=0; i<n; i++)
{
printf("%d%s\n", i+1, s[i]);
}
getch();
}
void sort(int n, char *s[ ])
{
int i,j;
char temp[20];
for (i=0; i<n-1; i++)
for (j=i+1; j<n;j++)
if strcmp (s[i], s[j])>0)
{
strcpy (temp,s[j]);
strcpy (s[j], s[i]);
strcpy (s[i], temp);
}
return;
}
14. Write a program to find area of a circle using macros.
#include<stdio.h>
#include<conio.h>
#define circlearea(r) 3.14*r*r
Output:
void main( )
Enter radius of circle
{
7
float r, area;
Area of a circle=154.000000
clrscr( );
printf(“\n Enter radius of circle”);
scanf(“%f”, &r);
area=circlearea(r);
printf(“\n Area of a circle=%f”, area);
getch( );
}
15. Write a program to find length of string using pointers and functions.
#include <stdio.h>
int strlength(char*);
void main( )
{
char s[20];
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 99
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
int len;
clrscr( );
printf("\n enter any string\n");
gets(s);
len=strlength(s);
printf("\n length of given string %s is=%d",s,len);
getch( );
Output:
}
enter any string
int strlength(char *p)
vaagdevi
{
int count=0;
length of given string vaagdevi is=8
while(*p!='\0')
{
count++;
p++;
}
return count;
}
16. Write a program to swap two values using parameter passing mechanism.
#include<stdio.h>
#include<conio.h>
void swap(int *x, int *y);
Output:
void main( )
a=10, b=20
{
after swapping: a=20, b=10
int a=10, b=20;
clrscr( );
printf(“\n a=%d, b=%d”, a, b);
swap(&a, &b);
printf(“\n after swapping: a=%d, b=%d”, a, b) ;
getch( );
}
void swap(int *x, int *y)
{
int temp;
temp= *x;
*x= *y;
*y=temp;
}
17. Write a program to create a structure, store the values and display them.
#include<stdio.h>
void main( )
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 100
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
{
struct bank
{
char name[20];
int acno;
int amount;
};
struct bank b1={“ramesh”, 120,15000};
clrscr( );
printf(“\n Name=%s”, b1.name);
printf(“\n AccountNo=%d”, b1.acno);
printf(“\n Amount=%d”, b1.amount);
Output:
Name= Ramesh
AccountNo=120
Amount=15000
/* structure initialization */
}
18. Write a program to create array of student objects.
#include<stdio.h>
#include<conio.h>
struct student
Output:
{
Enter number of students
char name[10];
2
int rno;
Enter name, rno, marks:
int marks;
Shiva
};
1
580
void main( )
Enter name, rno, marks:
{
Srinu
struct student s[10];
2
int i, n;
582
clrscr( );
printf(“Enter the number of students”);
Shiva
1
580
Srinu
2
582
scanf(“%d”, &n);
for(i=0; i<n; i++)
{
printf(“\n Enter name, rno, marks:\n”);
scanf(“%s%d%d”, s[i].name, &s[i].rno, &s[i].marks);
}
for(i=0; i<n; i++)
printf(“\n %s \t %d \t %d”, s[i].name, s[i].rno, s[i].marks);
getch( );
}
19. Write a program to demonstrate passing structures to functions using pointers.
#include <stdio.h>
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 101
downloaded from: www.sucomputersforum.com
Programming With C (B.Com-I year Semester- II)
#include <string.h>
struct student
{
int id;
Output:
Id is: 1
char name[20];
Name is: Raju
float percentage;
Percentage is: 86.500000
};
void func(struct student *record);
int main( )
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0;
}
void func(struct student *record)
{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}
20. Write a program to demonstrate Nesting of structures.
#include<stdio.h>
#include<conio.h>
struct student
Output:
{
char name[10];
Raju 10
76
85
92
int rno;
struct marks
{
int m1, m2, m3;
}m;
};
void main( )
{
struct student s1={“Raju”, 10,76,85,92};
printf(“%s \t %d \t %d \t %d \t %d”, s1.name, s1.rno, s1.m.m1, s1.m.m2, s1.m.m3);
getch( );
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET
Page 102
Download