0 ratings0% found this document useful (0 votes) 165 views38 pagesC Programming Unit-1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
PROGRAMMING IN C
NOTES
Prepared By
Prof. Prabhu Kichadi, ge yrecu
9880437187
UNIT -I
Introduction to C Programming: Overview of C; History and Features of C;
Structure of a C Program with Examples; Creating and Executing a C Program;
Compilation process in C.C Programming Basic Concepts: C Character Set; C
tokens - keywords, identifiers, constants, and variables; Data types;
Declaration & initialization of variables; Symbolic constants. Input and output
with C: Formatted 1/0 functions - printf and scanf, control stings and escape
sequences, output specifications with printf functions; Unformatted 1/0
functions to read and display single character and a string - getchar, putchar,
gets and puts functions.
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 1Programming in C Unit-1
Ce ,
Overview of C
C Is a general-purpose, high-level language, procedure-oriented programming
language that was originally developed by Dennis M. Ritchie to develop the UNIX
operating system at Bell Labs. C was originally first implemented on the DEC PDP-11
computer in 1972.
In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available
description of C, now known as the K&R standard.
‘The UNIX operating system, the C compiler, and essentially all UNIX application
programs have been written in C, C has now become a widely used professional
language for various reasons ~
Reasons to use C Language
+ Easy to learn
+ Structured language
+ It produces efficient programs
« Itcan handle low-level activities
+ Itcan be compiled on a variety of computer platforms
Uses/Applications of C Language:
+ Development of video games
+ Applications using graphical user interfaces
+ Databases and computer operating systems
+ Browsers on the internet
+ Computational and graphical methods
+ Banking
+ Cloud computing and distributed systems
+ Compilers
‘+ Embedded systems are systems that are integrated into a larger system.
+ Integrated software libraries for enterprises
«Server applications on alarge scale
+ Compilers of code
+ To develop system software's like 0S, Unix OS, Kernel
+ To develop utility software's,
+ To develop driver software's
ya unr par rvur eevee >see eseeneseeersseeeeeeeenerseenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 2Programming in C
Features of C Language
Portable | Mid-level
Struetur
C Language H Rich library
Extensible
) (me
Cis the widely used language. It provides many features that are given below.
Simple
Machine Independent or Portable
Mid-level programming language
structured programming language
Rich Library
Memory Management
Fast Speed
Pointers
yeu ene eee
Recursion
10, Extensible
1, Simple:¢ is a simple language in the sense that it provides a structured approach (to
break the problem into parts), the rich set of library functions, data types, etc,
2, Machine Independent or Portable: Unlike assembly language, c programs can be
executed on different machines with some machine specific changes. Therefore, C is a
machine independent language.
ya unr par rvur eevee osepeyseresr-eneeeneseeersseeeneeeeneneeeenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 3Programming in C Unit-1
Ce ,
3. Mid-level programming language: Although, C isintended to do low-level
programming, It is used to develop system applications such as kernel, driver, ete. That
is why it is known as mid-level language.
4, Structured programming language: is a structured programming language in the
sense that we can break the program into parts using functions. Functions also provide
code reusability.
5. Rich Library: provides a lot of inbuilt functions that make the development fast.
6. Memory Management: It supports the feature of dynamic memory allocation. In C
language, we can free the allocated memory at any time by calling the free() function.
7. Speed: The compilation and execution time of C language is fast since there are lesser
inbuilt functions and hence the lesser overhead.
8. Pointer: C provides the feature of pointers, We can directly interact with the memory
by using the pointers, We can use pointers for memory, structures, functions, array, ete,
9, Recursion: In C, we can call the function within the function, It provides code
reusability for every function, Recursion enables us to use the approach of backtracking,
10. Extensible: language Is extensible because it can easily adopt new features,
Programming Languages and its classifications
Programming Langtiage: Languages which are used to develop software having a well-
defined grammar, comprises set of instructions to produce outputs.
- Every programming language have well defined grammar, set of symbols that are
required to solve a given problem with computer.
Classification: Programming languages are classified into two broad categories.
1. High Level Programming Languages.
2. Low Level Programming Languages.
3, Assembly Level Programming Languages.
1. High Level Programming Languages: Programming languages which are
understood by human those languages are said to be High Level Programming
Languages.
Features:
ya unr par yur eevee osepeyseresrseneseseersseseeeneeeerenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 4Programming in C
These are human understandable languages.
* Easy to Learn and Understand.
+ User Friendly languages.
© Bx:
2, Low Level Programming Languages:
, C++, Java, Python, Pascal, HTML etc
anguages which are understood by machines
those languages are called low level programming languages.
Features:
+ Also called machine level languages, Binary Languages,
‘* Every statement is represented in terms of 0 & 1 only.
Ex:
nary Language. Cor
ists of O Sel.
Differences between High Level &Low-Level Programming Languages
High Level Programming Languages
Low Level Programming Languages
Human understandable
‘Machine Understandable
Easy to Learn
Complex to Learn
Requires Grammar of the language
Requires knowledge of computer
architecture
Easy to debug
Complex to debu;
Machine Independent
Machine Dependent
Requires Translators
No Need of Translators
Slower Execution
Faster Execution
Portable
Not Portable
‘More memory efficient
‘Less memory efficient
Requires more time for translation
No translation required
Ex: C, C+#, Java, Python, Pascal
Ex: Binary Language ie 010101010101
Translators, Compiler, Interpreter, Loader, Linker
In order to make computer understand all high-level programming language code are
need to be translated to low level code, Hence there is a need of translators.
Translators: Translator is a software /set of programs which translates a program
written in one language to another language.
‘Types of Translators: Compiler, Interpreter, Assembler,
Compiler: Compiler is a software/set of programs that converts a program/source
written in high level language to a machine code/low level code and It display errors in
the program.
Generally, compiler converts code written in high level programming language to an
Intermediate code/object code, thus object code is executable,
Compilation: A process of conversion of source code written using high level
programming language into machine code by the compile
s called compilation,
Prof. Prabhu Kichadi, precy (9880437187)
BCA-ISem 5Programming in C
Job of Compiler:
Converts program written in high
executable,
Compilation Process:
level language into machine code that is
Lists errors present in the source code while in conversion,
Program/Source Machine Code/Object
Code/File Compiler) code/it Exerutable
(High Level Language) (Low Level)
program1.c program 1.0
Compilation: A process of conversion of:
programming language into machine cod
Job of Compile
Converts program written in bigh
executable,
Compiler converts a program which is wr
into an Object code/machine code /Intermediate code which is executable.
process it is shown that a sample progran
source code written using high level
le by the compiler is called compilation.
level language into machine code that is
Lists errors present in the source code while in conversion,
ritten using high level programming language
othe
m program Lc is converted into program Lo file.
Interpreter: Interpreter is a program/software which converts& executes one
statement of source code at atime. It will
not generate intermediate object code,
Instead, it will execute line by line at a time,
Differences between Compiler &
Interpreter
Compiler
Interpreter
1. Converts entire source code into an
intermediate /machine code, then it is
executable
Executes one statement ata time, it stops
execution when it encounters an error.
2, Generates intermediate code
It won't generate Intermediate code
3. Complete source code analysis
No source code analysis
4. More memory required as it generates
object code
Less memory required, as it won't
generate object code
5, More time to analyze source code
Less time
6, After successful compilation of the
entire code then only we can execute.
Tt will execute till it encounters an error
7. G+, Java uses compiler
Python, Ruby uses interpreter
Loader: Loader is a part of operating syst
tem which loads source code/program from
Secondary storage into memory (RAM) for successful execution of the program. It
$$
Prof. Prabhu Kichadi, precy (9880437187)
BCA-ISem 6Programming in C Unit
ee"
allocates memory for program execution on RAM, Generally, it takes object code as
input.
Linker: Linker is a program which links all the modules which are required for
successful execution of the program. It links object modules of the program into single
object file and that is executable. Below diagram depicts working of loader, linker,
compiler.
[coumcen | _. es ee
a _I
Software, Program, and Instruction
Software: Software is set of Programs that performs a Specific task. Software is
developed using high level programming languages. Collection of related programs
constitutes software,
«Every software has some specific use and purpose.
* Software's run /execute on computers/mobiles/device.
* Software is intangible in nature it means we cannot touch and feel software.
Examples:
Software Use
Calculator - For mathematical, scientific calculations
Code Blocks ~To Fait, Compile, Execute, Develop ¢ programs.
MS-Word - For creating documents such as letters, brochures, learning
Facebook + for social networking
Adobe Reader __- To open/read pdffiles
TurboC - To Edit, Compile, Execute, Develop C programs.
Program: is a collection of good instructions that can be executed by a computer to
rm a specific task. It isa building unit of software.
+ Programs are developed using high level programming languages like C, C++,
Java ete.
Instruction; Instruction is a command in program, which does small task; instructions
are also called as statements/lines of code,
yar unr unr rvur ensue >seneysesr-eneeeneseeersseeeeeeeereneel
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 7Programming in C Unit-1
C Program Structure
[a linea Documentation secon
#headectdn> -
I Preprocessor Directives
Heinen i))} —_——_=a $< Defirtion secon
vida);
intl,
| ————— Gobel dederation section
itm) ———— main() Function section / Entry Pont
{ otal; —_»_ ee Variable dedlaration
it Hel iy
al | Body of Main function
]
vial
" seta ———, Faneton Definition
}
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 8Programming in C Unit-1
Ce ,
1, Document Section: - A C program is to be documented when itis to transfer to
other programmers or to amodule. We can use single line comments or multiline
comments to describe ac program.
2. Pre-Processor Directives: using preprocessor directives we can include header
files such as #include. #include.
3. Macro Definitions: - Macros are symbolic constants which are used in many
programs to avoid constants to remember.
4, Global Variables Declarations & Function Prototypes: - Variables which are
required for many functions in a program are declared in this section. Functions
declarations are placed here
5. main () Function:-main() Is system function, itis an entry point to ac program. if
we want to execute ac program, program must contain a main() function,
6. Functions Body: - These are subprograms in programs which are defined outside
main() body.
Creating & Executing a C Program
Steps:
1. Create a C Source Code/Program using any editors like Codeblocks, Turbo, vi, VS.
2, Save the program with .c Extension.
3. Compile the source code which generates 0 file (Object file)
4, Execute The program which gives results at output screen /console screen,
Compilation Process
Program/Source Machine Code/Object
Code/File Code/IL Executable
(High Level Language) (Low Level)
program1. program1.o
Compiler converts a program which is written using high level programming language
into an Object code/machine code /Intermediate code which is executable. In the
process it is shown that a sample program program .c is converted into program.o file,
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 9Programming in C
Ce ,
C Programming Basic Concepts
Overview of C Character Set
C Supports following character set for creating any C program.
1. Alphabets: Uppercase(A-Z) & Lowercase(a-2)
2. Digits: 0-9
3. Special symbols/operators:
Comma (,),
Period/dot(.)
Ampersand (&)
Arithmetic operators:
Relational operators: <,>,
Termination symbols: :,;,
Special: $,_,%, ~, #, 1, () () ete.
4, Escape characters/Escape Sequences: \n-Newline,
\t-Tab
\v- Vertical tab
\r ~carviage return etc.
C Tokens
Tokens are smallest unit/building block of ac program statements.
Tokens are the smallest elements of a program, which are meaningful to the
compiler.
‘The following are the types/Classification of tokens:
Keywords, Identifiers, Constant, Strings, Operators, etc.
Identifiers and Keywords: - Words: Group of characters represents some
meaning. Examples: Home, Go, Examination, prepare, ete.
Keywords: - “These are reserved words in C, represents some meaning &
functionality”. Keywords are building blocks/units of c programming languages.
Every G program contains a well combination of keywords and identifiers.
Feature:
¥ Meaning is fixed, User cannot change their meaning.
¥ Alsocalled as Predefined words, Reserved words, b
System defined words
Helpful in creating programs
All keywords are small case
There are 32 keywords present in C
Cannot use as identifiers
ya unr par rvur eee vunenneny>sepepsererer-eseseersseseeeennneeseeenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 10Programming in C
Ce ,
List of keywords in C languages
void char int float
double long signed unsigned
register volatile ‘const short
else for while
do return goto break
continue default static switch
sizeof{) union struct typedef,
auto case enum extern
Identifiers:
“A Name in C Program is called an identifier, it can be a variable name, a function
name, a structure name, label etc., these are user defined words”.
Uses: -
To give a name to entities like variable, function, labels, structures in C program etc.
Identifiers are used for identification purpose.
Rules for Defining an Identifier.
1. Allowed Characters are: -
a, Alphabets: - Uppercase(A-Z) & Lowercase (a-z)
b. Digits: - (0-9)
¢. Special Symbols: _(Underscore), $ (Dollar)
2. Identifier should not start with digits,
3. Identifier should not be a keyword.
4. Identifiers are case sensitive.
5. Identifier name must be unique ina program
6. There is no space between an identifier word.
Test the following related to identifiers,
Abed Valid Identifier
abc@# Invalid Identifier
123abe Invalid Identifier
Abc_abe Valid Identifier
_ab-ab Valid Identifier
Xyzabel23 Valid Identifier
$abe Valid Identifier
ya unr par rvur eee veneer osepepserer eres
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. uProgramming in C Unit-1
Ce ,
Constants/Symbolic Constant:
Constant: A constant is a value or variable that cannot be changed in the program, for
example: 10,20, 'a’, 3.4, "c programming’ ete,
These are fixed value in C.
These are also called as literals.
Any value which is directly referred in a program is a constant.
EX: 5, 44.55,
KLE,
Constants are classified as:
Constants
Numeric Character
Constants Constants:
Single
Integer string
Real Constants character
Constants, cence Constents,
eg, “Hello”,
157432445
eu.
o.o0s3,
eg 128,123.0
List of Constants in C
Constant Example
Decimal Constant 10,20, 450 ete
eal or Floating-point Constant 103,202, 4508 ete.
Octal Constant (21,033, 046 ete
Hexadecimal Constant (0122, Ox7b, uaa ete
Character Constant a,b, ¥ ete
String Con 1, "c program’, “cin jacatpoint etc
ya unr par rvur eee veneer ssepepseresereeseseersseseeeeneneeeeenenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 12Programming in C
Ce ,
Ways to define constant in C:
There are two ways to define constant in C programming,
1. const keyword
2, #define preprocessor
1. Using const keyword:
Syntax:
const datatype variablename = value;
const float PI = 3.142;
Example Program:
#inchude
int main()
{
const float Pl=3,142;
printf("The value of PI is: %f",P1);
return 0;
}
- inthis program we cant change the value of PI, we cant perform reassignment on
PI variable, as it is a const variable.
2. Using #define preprocessor:
‘The #tdefine preprocessor is also used to define constant.
Exi:
#includexstdio.h>
define PI 3.142
int main()
{
printf("The value of P1 is: %f",P!
return 0;
ya unr par rvur eee veneer >see ereneseersseseeesnneeeeenenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 13Programming in C Unit-1
Variables
“Variable is a name given to memory location; it is used to store data/values of
different types’.
Features
= Values of the variables may be changed during program execution.
- Variable name must be a valid identifier
- Variables are containers to hold values.
= Atatime one variable can hold maximum one value.
Variable Declarations/Creation
“Reserving/Allacating a memory for storing data, it specifies variable name, which
type of data it stores and size of the vartable”.
+ Before using/accessing a variable it must be defined /declared.
+ After declaration every variable in C is initialized to Garbage value.
Syntax: | datatype variablename;
©) withthe neIpsyntax we can create avariable in C program.
datatype -> datatype means we need to specify one valid data type from C, here we
have to write keywords related to data types like int, float, double, char etc.
variablename -> it must be a valid identifier. And it is the name of the memory location.
Ex:
int num;
- datatype->int
- variablename -> num
- When this line executes 4 bytes of memory will reserve for a variable num, num
is the name of the memory location.it stores any integral value within the range
of int.
float area;
char ch;
double salary;
Variable Declaration and Initialization
- Variable declaration is nothing but reserving/allocating a memory, specifying variable
hame and type of value it stores.
syntax
datatype variablename;
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 4Programming in C
Ce ,
Ex:
int x;
float y:
double dj
char eh;
Variable Initialization: variable initialization means storing some initial value to
the variable., using assignment operator (=) we can store data to variables, variable
value may be changed thought the program-based need.
Syntax:
Example1:
int num;
hum = 100;
- In this example variable num is of type int, it can store any integral value within the
range of int data type. 100 is value of int type itis stored inside allocated variable num.
Example1:
char ch;
che‘a
- chs variable of type of char, means it can store only single character at a time,
Format Specifiers in C
‘The format specifier is used during input and output.
Itis a way to tell the compiler what type of data Is in a variable during taking Input
using scanf() or printing using printf(). Some examples are %c, %d, %f, ete.
%d Integer format specifier
%f and %e or %E Floating point specifier
%e Character format specifier
%s String format specifier
%o Octal number for Integer
x Hexadecimal number for Integer
%p Address pointed by a pointer
ya unr par rvur eee veneer >see ereerneseeersseeeeennneeneerenenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 15Programming in C U
Ce ,
Data Types:,ata: Data is a collection of raw facts, statistics such as numbers, words,
measurements, observations or just descriptions of things.
Data is anything that we get around us it can be raw facts, figures, statistics, files,
maps, charts, etc.
Ex: 122, 33.55, 'a’,"Ravi”
Data Type: Data type refers to the type or form of the data, data is classified in
different formats.
Different forms of data are available hence to place our data in which type we have to
follow data types.
Every data type specifies size, range and type of data it stores.
Ex:
11 Is of integral type-int
33.33 is of floating-point type-float, double
a’ is of character type-char
“hello” is of string type- char array
Data Types: In c language data type are classified into 3 main types.
1. Primitive data types-int, char, float, double
2. Derived data types-array, pointers, strings.
3. User defined data types-structure, union, enum, typedef.
Data types
pes li npes
pes types pes
Numeric data Non-numet
types data types
J Group of
Integral data eee Character date | | characters(strin
types - int ioe eubie type-ichar 9)- char avr[25]
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 16Programming in C Unit-1
Ce ,
1. Primitive data types:
These are basic/built-in data types in C, these are readymade and predefined data types
available when we install any C compiler.
We cannot break down these data types into more simpler data types.
These are classified as
1.1 Numeric data type
1.2 Non numeric data type
1.1 Numeric data type: These data types talk about numerals like integral and floating-
point data,
Classified into two categories.
1.1.1 Integral data types
1.1.2 Floating point/real number data types
EX: 22, 55, 66.66, 88.9009
1.1.1 Integral data types: These data types refer numbers data which is in the
form of integers, data type is also specifies size, range of value and type of value,
Keyword: int.
Size: 4 Bytes (based on compiler & OS architecture)
Ranges 2, 147,483,648 to +2,147,483,647
‘Type: Only it accepts integral data (33, 4545454, etc.)
‘Type Modifiers/qualifiers: signed, unsigned, long, short
Format specifier: %d
1.1.2 Floating data types/Real: These data types refer numbers data which is
in the form of fractions. Any numerical data which is having a precision or decimal
point, data type specifies its own size and range of value and type of value,
Keywords: - float, double
float:
Size: 4 Bytes (based on compiler & OS architecture)
Range: -3.46+48 to +3.4E+38
Types it accepts both integral and floating-point data (33.00, 4545454.666, etc.)
Format specifier: %f
double:
Size: 8 Bytes (based on compiler & OS architecture)
Range: -1.7E+308 to +1,7E+308
Typezit accepts both integral and floating-point data (33.00, 54.666, 45.66 etc)
Format specifier: %If %Lf
1.2 non-Numeric data type/Character data types:
These data types talk about Non numbers, it means these data types are nothing data
which is in the form single character/group of characters.
Represents any symbol/letter/digits as characters.
ya unr par rvur eevee >sepepsrererenmeneseersseseeeeeeneseeenenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 7Programming in C
Ce ,
Classified into two categories
1.2.1 Single character data types
1.2.2 Group of characters /string data types
Ex: 'X', ‘71, "#01, “hello”, "',""
1.2.1 Single character data types:
Using char keyword, we can represent character data type in G. single quoted
value/literal letter /digit/symbol/Space is a character in C. Maximum only one is
allowed in a single quote. Space Is also a character in C.
Bx: 71/18, A' "a,"
Keyword: char
Size: 1Byte
Range: 0 to 256 ‘al-> 97 ASCII Value
‘Type: single quoted any literal
Format Specifier: %c
1.2.2 String data types:
Group of characters are said to be string in C. If any combinations of letters and/or
symbols and/or digits enclosed in a double quote are strings in C,
Ex: “Rahul”, “Hello123","B_ ys", "56566",""
Keyword: using char array concept
Size: Depends on number of characters
Range: No limit
Type: double quoted any literals
Format Specifier: %c, %s,
Input and Output with C
Input, it means to feed some data into a program. An input can be given in the form ofa
file or from the command line, C programming provides a set of built-in functions to
read the given input and feed it to the program as per requirement.
Output, it means to display some data on screen, printer, or in any file, C programming
provides a set of built-in functions to output the data on the computer screen as well as,
to save it in text or binary files.
Functions in C
“Function is a re-usable block of code that performs a specific task”.
> Itis ike a subprogram in C.
> [tis a modularization technique.
Instead of writing all the code inside in single main( ) function, we can decompose the
code into modular(functions). Where each function és assigned a part of the work.
————_—_—_—_——————————
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 18Programming in C
Ce ,
Advantages of Functions:
1. Code re-uses
2, Write Once Gall Many Times.
3. Code length decreases,
4, Code maintenance becomes easy.
5. Code becomes more modular.
Regarding Functions,
> Generally, every function takes some inputs and processes it and returns some
outputs to the caller,
> Inputs are supplied to the function in the form of function arguments(parameters)
(Variable Declarations).
> Every function returns maximum one value to the caller,
> Every function has its own unique name (identifier), optional parameters, and a
return type (valid data type).
Every function has 3 main things
1, Function Declaration/prototype~ First Line of the function to indicate
compiler,
2, Function Definition/Body/Implementation — Actual work of the function
is defined inside Curly Braces {}.
3. Function Call/Invoke (Optional) - To execute the function body, we need to
call the function.
1. Function Declaration/prototype - This is the First Line ofthe function to
indicate compiler the signature of the function.
syntax:
returntype functionname(optional parameters);
1, returntype - it must be a valid data type related keywords, it tells what type ofa
value is going to return by the function when it completes its execution. Ex: void,
int, float, char, double, Student, Employee etc.
2. Functionname - It is the name of the function provided by the programmer; it
must be a valid identifier.
3. Optional parameters - These are inputs to the function; list of variables
declarations is written here.
It must be written, generally outside all functions body and after preprocessor
directives, It must be global.
2, Function Definition/Body /Implementation - The actual task of the function is
defined inside {}
syntax:
ya unr par rvar ene veneer >see eseneseersseseeeenneeeesseenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 19Programming in C Uni
Ce ,
| returntype functionname (optional parameters)
{
//Actual task of the function
/{Statements representing function implementation
// return statement
}
k
xl:
include
id display(),;, ————————+ Function declaration /Prototype
int main( )
t
printf¢"\n main Fa Starts");
display(); Function Call/Invoke
printf("\n main Fn Ends");
return 0;
i
void display()
t
rintf("\n display Fn starts”), ———Funetion Definition/Body
rintf("\n display Fn ends");
return;
a
Functions are classified into two types.
1, User Defined Functions,
2. Library Functions.
1. User Defined functions:
Functions which are created by the programmer as per his/her software development
requirement,
There are four types(variations) of user defined functions can be created.
1. Without rettype and without parameters.
2. Without rettype and with parameters.
3. With retype and without parameters.
4, With rettype and with parameters.
ya unr par rver eee veneer ssepeyserereeeneseeersseeeeeennereenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 20Programmin;
Ce ,
1.Without rettype and without parameters,
- The function which is not going to return any value to the caller and not going to take
any parameters.
Ex:
#include
void disp); //Function declaration
void disp() //Called Function
‘ printf("\nHello KLE BCA");
return;
}
int main() //Calling Function
‘ dispQ; //Function Call
return 0;
}
2, Without rettype and with parameters.
ex:
#include
void disp(int x); //FN declaration
void disp(int x) //Called Fa
{
printt(
return:
J
int main()_//Calling Function
{
int y;
y = 100;
print{("\n main(). y= %d"y);
disp(y);//Fn Call
retur
}
3. With rettype and without parameters.
ex:
itinclude
IntgetNum(); //FN declaration
intgetNum() //Called Fn
{
return 100;
3
int main() //Calling Function
{
int ys
ya unr par rvar er vunenneny>senepsyererps-neneseersseeeeeeneeseeeenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 21etNum();
printi("\n main) y = %d"y);
return 0;
Z
4, With rettype and with parameters.
EX:
#include
int square(int x);
Int main()
{
printf("\n main Fn Starts”);
Int x = square(4);
printf("\n Square = %d"x);
printf("\n main Fn Ends");
return 0;
J
int square(int num)
{
int a;
a= num*num;
return a;
J
2. Library Functions/Built-in Functions/Predefined Functions:
“Library functions in C language are inbuilt functions which are grouped together
and placed in a common place called library (Header Files). Each library
function in C performs specific operation”.
We can make use of these library functions to get the pre-defined logic instead of
writing our own code to get those outputs.
Ex : printi();, seanf{ ), geteh( ), putch( ), exit(), strlen( ), streat(), ete
Input Functions: -Data/Value can be read from standard input Device(Keyboard),
Functions which are used for reading data from keyboard.
Ex: scanf(), getch( ), gete( ), gets( J, getchar() etc.
Output Functions: -Functions which are used for printing/displaying results on the
standard output that is output screen.
Ex: printf{ ), putch(), putchar( ), puts( ), pute() ete.
1/0 Library functions are classified into 2 types.
1. Formatted 1/0 Functions
2. Unformatted 1/0 Functions
Cae ae aeer er ane
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 22Programming in C U
Ce ,
1. Formatted 1/0 Functions:
> Gallows read/write data in a formatted way,
> C language provides 2 formatted 1/0 functions for formatting the data.
printf() : Formatted Output Function
scanf( ) : Formatted Input Function
1.1 Formatted Output Function:
printf() is Formatted Output function used to print any string with format
specifiers like %d, %s, %c, %6f corresponds list of variables on the standard output
Screen.
Syntax:
int printf(“Formatted String+Format Specifiers”, List of variables);
OR
int printf(“ String , Format Specifiers”, var1, var2, var3,
Ex: printi("x = %d \ty = %d".xy);
1.2 Formatted Input Function:
scanf();
> scanf{ is a predefined formatted input function. it is used to read/scan
character data from standard input device(keyboard) at run time.
> The output screen will wait for user input, unless& until user doesn’t provide
input at run time; the rest of the program won't be executed.
3
Whatever the input read from user will be stored in an address of a variable.
Ex1:
printf("\nEnter x & y Values :");
scanf("%d %d", &x, By);
printf("\nx = %d\ty=%d"xy);
Output
Enter x & y Values : 12 24
x=12 y=24
ya unr pny rvar ee vuneenneyosepepsrer rr eeseseerseeeeeecel
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 23Programming in C U
Ce ,
2. Unformatted 1/0 Functions
“Functions which are used to read/write data without user format, user cant
modify the format”
Ex: Unformatted Input Functions :getch( ), gete( ).gets(). getchar( )
Unformatted Output Functions: putch( ), putc( ),puts( }, putchar()
2.1 Unformatted Input Functions:
1. getchar() :
syntax: char getchar();
The getchar() function reads character type data form the input. The getchar() function
reads one character at a time till the user presses the enter key.
Ex:
char ¢;
print{("\nEnter a Characte
c= getcharQ);
print{("\nEntered Character : %c",c);
2. getch():
Syntax:
The getch() function reads the alphanumeric character input from the user. But, that the
entered character will not be displayed.
Present in conio.h header file.
Ex:
char ch =A’;
printf("\nCharacter : %¢" ch);
getch();
gets(): char * gets(char *str);
Syntax: OR
char * gets(char[] str);
Se
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 24Programming in C Unit-1
Ce ,
gets() standard library string input function is used to read string data at runtime from
standard input device.it reads even white space character also.
Ex:
char str[25];
printf("\nEnter a String :");
gets(str);
printf("\nString : %s" str);
2.2 Unformatted Output Functions:
1, putcharQ):
syntax :
int putchar(int char);
- [tis used to write a specified character to standard output device(console), must
be passed a character as argument.
- Ex:
char ch;
eh='ai
putehar(ch);
2. putchQ) :
Syntax:
putch{ ) function prints a specified character at standard output device(console).
- Ex:
char ch;
ch= ‘ai
putehar(ch);
3. puts() : itis string library function it writes a string character on output screen.[f
successfull, non-negative value Is returned, On error, the function returns EOF.
ya unr par rvur eevee osepepsererereeneseerersseseeeeseeneeeeenenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 28Programming in C
Ce ,
Syntax:
int puts(const char *str)
oR
int puts(char{] str);
char name [25];
printf("\nEnter a String :
gets(name);
puts(name);
return 0;
It is used to read/write all types ofdata _It is used to read/write only character
types of data
Requires Format Specifiers to read and Requires No Format Specifiers to read and
write write
Exs: printf(), scanf() Exs: getchar(), getch(), gets(), putchar(),
puteh(), puts()
aya unr par rvur ene veneer >see er-eeseseersseseeeennereecenenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 26Programming in C
Ce ,
UNIT-WISE QUESTION ANK ANSWERS
UNIT-I
1. What is C Programming? Who developed C?
Cis a general-purpose, high-level, Robust, procedure-oriented programming
Ianguage that was originally developed by Dennis M. Ritchie.
2. List out the uses of C language.
* To develop system software's like OS, Unix OS, Kernel
To develop utility software's.
To develop driver software's.
Development of video games
Applications using graphical user interfaces
Databases and computer operating systems
* Browsers on the internet
3. List & explain features of C language.
«Simple: C is a simple language in the sense that it provides a structured
approach (to break the problem into parts), the rich set of library functions, data
types, etc.
* Machine Independent or Portable: Unlike assembly language, c programs can
be executed on different machines with some machine specific changes.
Therefore, Cis a machine independent language.
+ Mid-level programming language: Although, C is intended to do low-level
programming. [tis used to develop system applications such as kernel, driver,
ete. That is why it is known as mid-level language.
«Structured programming language: is a structured programming language in
the sense that we can break the program into parts using functions. Functions
also provide code reusability.
+ Rich Library: provides a lot of inbuilt functions that make the development fast,
* Memory Management: It supports the feature of dynamic memory allocation. In
C language, we can free the allocated memory at any time by calling
the free() function.
Explain the basic structure of aC Program.
Any c program contains following parts,
© Document Section: - AC program is to be documented when it is to transfer to
other programmers or to a module. We can use single line comments or multiline
comments to describe ac program.
+ Pre-Processor Directives: using pre-processor directives we can include
header files such as #include, #include.
* Macro Definitions: - Macros are symbolic constants which are used in many
programs to avoid constants to remember,
ya unr par rvur eee vunenneny >see er-eeseseeersseseeeenneereeeenenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 27Programmin;
* Global Variables Declarations & Function Prototypes: - Variables which are
required for many functions in a program are declared in this section, Functions
declarations are placed here,
main () Function:-nain() is system function, itis an entry point to ac program.
if we want to execute ac program, program must contain a main() function.
© Functions Body: - These are subprograms in programs which are defined
outside main() body.
Data 5
th 2
uo ——$—+ Documentation section
includedtdiol» -_—
‘eiteany, | Preprocessor Directives
‘ele max) —————+ Definition section
veld; } Global declaration section
intx=10
‘ntmain) ———— main) Function section / Entry Point
{inte=l0;] np Variable declaration
ream “\— Body of Main function
}
iit
" lien ———, Function Definition
]
5.What is translator? Give examples.
‘Translator is a software/set of programs which translates a program written in
one language to another language.
‘Types of Translators: Compiler, Interpreter, Assembler.
6. What is compiler, Interpreter and Assembler?
Compiler is a software/set of programs that converts a program/source written
in high level language to a machine code/low level code and it display errors in the
program,
ya unr par ryur ee vunenneny>sepepsreereeseseeersseseeeeneneeeeeeenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 28Programming in C
Unit-1
Interpreter is a program/software which converts& executes one statement of
source code at a time. It will not generate intermediate object code. Instead, it will
execute line by line at atime.
An assembler is a type of computer program that interprets software programs
written In assembly language Into machine language.
7. What is compilation process? Explain with diagram,
Compilation Process:
Program/Source Machine Code/Object
Code/File Compiler} code/It Executable
(High Level Language) (Low Level)
program1.c program1.0
Compilation: A process of conversion of source code written using high level
programming language into machine code by the compiler Is called compilation.
Job of Compiler:
© Converts program written in high level language into machine code that is
executable,
* Lists errors present in the source code while in conversion,
Compiler converts a program which is written using high level programming language
into an Object code/machine code /Intermediate code which is executable.
In the process it is shown that a sample program program 1.c is converted into
program1.o file.
8. Give differences between compiler and interpreter.
‘Compiler
Interpreter
1. Converts entire source code into an
intermediate /machine code, then it is
executable
Executes one statement at a time, it stops
execution when It encounters an error.
2, Generates intermediate code
It won't generate Intermediate code
3, Complete source code analysis
No source code analysis
4. More memory required as it generates
object code
Less memory required, as it won't
generate object code
5, More time to analyze source code
Less time
6. After successful compilation of the
entire code then only we can execute.
It will execute till it encounters an error.
7.G G++, Java uses compiler
Python, Ruby uses interpreter
Prof. Prabhu Kichadi, prec, (9880437187)
BCA-ISem 29Programmin;
Ce ,
9. What is C Programming? State its features.
Cis ageneral-purpose, high-level language, procedure-oriented programming
Tanguage that was originally developed by Dennis M. Ritchie to develop the UNIX
operating system,
Features:
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4, structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10.£xtensible
10. What are C-Character set in C?
1. Alphabets: Uppercase(A-Z) & Lowercase(a-z)
2. Digits: 0-9
3. Special symbols /operators:
Comma (,),
Period /dot(.)
Ampersand (&)
Arithmetic operators: +, -,*, /,%
Relational operators: <, >, <=, >=,
Termination symbols: :,
Special: $,_,%,~, #1 () {yete.
4. Escape characters/Escape Sequences: \n-Newline,
\t-Tab
\v—Vertical tab
\r~ carriage return ete.
11. What are tokens in C? Give examples.
Tokens are smallest unit/building block of ac program statements.
Tokens are the smallest elements of a program, which are meaningful to the
compiler.
The following are the types/Classification of tokens:
Keywords, Identifiers, Constant, Strings, Operators, etc.
12. What are reserved /keywords in C? list examples.
These are reserved words in C, represents some meaning & functionality”. Keywords
are building blocks /units of ¢ programming languages. Also called as predefined words.
Examples: int, float, char, double, long, enum, struct, union, if, else, do, while, for etc.
13, What are identifiers? List the rules for defining an identifier?
A Name in C Program is called an identifier, it can be a variable name, a function
name, a structure name, label etc,, these are user defined words,
Rules for Defining an Identifier.
1, Allowed Characters are: -
ya unr par rvur eevee >sepepsreser-eneeneseeersseseeeennneneeseenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 30Programming in C
Ce ,
a, Alphabets: - Uppercase(A-Z) & Lowercase (a-z)
b. Digits: - (0-9)
c. Special Symbols: _(Underscore), $ (Dollar)
2. Identifier name should not start with digits.
3. Identifier should not be a keyword,
4, Identifiers are case sensitive.
5. Identifier name must be unique in a program.
6. There is no space between an identifier word.
14, What is data? Classify data types in C.
Data is a collection of raw facts, statistics such as numbers, words, measurements,
observations or just descriptions of things. Data is anything that we get around us
it can be raw facts, figures, statistics, files, maps, charts, etc.
1. Primitive/Basic data types-int, char, float, double
2. Derived data types-array, pointers, strings,
3. User defined data types-structure, union, enum, typedef,
i ectatees
raimve dat || Derived data | [User deine dot]
pes
Pr
L
15. What is symbolic constant? Classify constants in C.
A constant is a value or variable that cannot be changed in the program, for example: 10,
20, 'a', 3.4, "e programming" etc,
‘These are fixed value in C.
Character
Constants
‘Numeric
Constants
Single
Integer string
Constants Bool copes cae Constants
eg. "Helios
wtbeaeaes.
8.123-2230 FI oostSoes
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 31Programming in C
Ce ,
List of Constants in C
Constant Example
Decimal Constant 10,20, 450 ete
Real or Floating-point Constant 103,202, 4506 ete
Octal Constant 021,033, 046 ete
Hexadecimal Constant 0220, Ox7b, rae ete
Character Constant a,b, ¥ ete
Sting Constant 1," program’, ‘cin javatpoint ete
16. What is variable? How to declare a variable in C?
Variable is a name given to memory location; it is used to store data/values of
different types.
Variable Declarations /Creation:- “Reserving/Allocating a memory for storing
data, it specifies variable name, which type of data it stores and size of the
variable”.
Syntax: datatype variablename;
datatype -> datatype means we need to specify one valid data type from C, here we
have to write keywords related to data types like int, float, double, char etc.
variablename -> it must be a valid identifier. And it is the name of the memory location.
Examples: int num;
float area;
char ch;
double salary;
17. How to declare a variable? Give an example.
Varlable Declarations/Creation: - “Reserving/Allocating a memory for storing
data, it specifies variable name, which type of data it stores and size of the
variable”.
Syntax: datatype variablename;
datatype -> datatype means we need to specify one valid data type from C, here we
have to write keywords related to data types like int, float, double, char etc.
varlablename -> it must be a valid identifier. And it is the name of the memory location.
Examples: int num;
float area;
char ch;
double salary;
yar unr unr rvar eevee sep es-eneeneseeersseseeeereeeeeeenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 32Programmin;
Ce ,
18. What are formatted and unformatted 1/0 functions in C?
1, Formatted 1/0 functions are built in functions which are used to read data from
standard input device and write the data onto the output screen using format specifiers
like %d, %c, %s etc with user format.
Ex: Formatted Output function : printf()
Formatted Input function : scanf()
printf); printf{) is Formatted Output function used to print any string with format
specifiers like %d, %s, %c, %6f corresponds list of variables on the standard output
Screen.
Syntax: int printf("Formatted String+Format Specifiers’, List of variables);
Ex1: printf{(“ Hello World");
Ex2: int x=10,y=20;
printf("x= %d \ty = %d"x.y);
scanf() : scanf() is a predefined formatted input function. it is used to read/scan
character data from standard input device(keyboard) at run time.
Syntax: Int scanf(“FormatSpecifiers”, &var1, &var2,
printf(\nEnter x & y Values :");
scanf(“%d %d", &x, &y);
2. Unformatted 1/0 functions are built in functions which are used to read data from
standard input device and write the data onto the output screen without using format
specifiers and these doesn’t support user formats like %d, %s, 96f ete,
Ex: Unformatted Output function: putchar(), putch(), puts()
Unformatted Input function: getchar(}, getch(), gets()
Unformatted Output Functions _ | Syntax Use
putchar() int putchar(char ch); | Itis used to write a
specified character to
standard output
device(console), must
be passed a character as
argument,
putch(); int puteh(int ch); putch() function prints
a specified character at
standard output
device(console).
ya unr par rvur ensue >see er-eneseeersseeeeennneeeecenenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 33Programming in C Unit-1
Ce ,
puts() int puts(char{] str); itis string library
function it writes a
string character on
output screen. If
successful, no
negative value Is
returned. On error, the
function returns EOF.
Unformatted Input ‘Syntax Use
Functions
getchar() char getehar(); The getchar() function
reads a character type
data form the input. The
getchar() function reads
one character ata time
till the user presses the
enter key,
geteh(); int geteh(); The getch() function
reads the alphanumeric
character input from
the user. But, that the
entered character will
not be displayed.
gets() char * gets(char *str); gets() standard library
string input function is
used to read string data
at runtime from
standard input device.it
reads even white space
character also.
19. What are escape characters in C?
Escape characters are characters having a special meaning to the compiler. And it
starts with \.
\n-Newline
\t-Tab
\a- beep
\v- Vertical tab
\r- carriage return ete.
KK
Prof. Prabhu Kichadi, yee, (9880437187) BCA-ISem 34Programming in C U
Ce ,
20. List format serra in
%d Integer format specifier
%f and %e or %E Floating point specifier
%C | Character format specifier
%s String format specifier
%o | Octal number for Integer
x Hexadecimal number for Integer
“op | Address pointed by a pointer
21 Give the syntax of printf() and scanf()
printf() : Syntax
int printf(“Formatted String+Format Specifiers’, List of variables);
OR
int printf(" String , Format Specifiers”, var, var2, var3,
scanf() : Syntax
int scanf("FormatSpecifiers”, &var1, &var2, ..)5
22, Give the syntax of getchar() and putchar( ).
getchar(): Syntax => char getchar();
putchar() : Syntax => int putchar(int char);
23. Give the syntax of gets() and puts().
gets() : Syntax => char * gets(char str{));
puts(): Syntax => int puts(char{] str);
24, Explain different types of constants in C.
25, What is Constant? Classify and explain constants in C.
Constant: A constant is a value or variable that cannot be changed in the program, for
example: 10, 20,
‘irae
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 35Programming in C
Ce ,
List of Constants in ©
26, What are keywords and tokens? Mention them.
Keywords: These are reserved words in G, represents some meaning & functionality”.
Keywords are building blocks /units of c programming languages.
Keywords in C : int, float, double, char, long, if, else, do, while, for, break, switch, enum,
struct, union, void, signed, goto, const, etc,
Tokens: Tokens are smallest unit/building block of a c program statements, Tokens are
the smallest elements of a program, which are meaningful to the compiler.
Types/Classification of tokens in C.
Keywords, Identifiers, Constant, Strings, Operators, etc.
27. What is Computer Program?
is a collection of good instructions that can be executed by a computer to perform a
specific task, It is a building unit of software.
28, What are the advantages of C Programming?
+ Development of video games
+ Applications using graphical user interfaces
+ Databases and computer operating systems
+ Browsers on the internet
+ Computationaland graphical methods
+ Banking
+ Cloud computing and distributed systems
29, Explain print{Q and scanf() with syntax and example.
printf): printf() is Formatted Output function used to print any string with format
specifiers like %d, %s, %c, %f corresponds list of variables on the standard output
Screen.
syntax:
int print{(“Formatted String+Format Specifiers”, List of variables)
Exampl
Ex:
printf(" Hello World ");
int
pr
10, y=20;
nti("x = %d \ty = Yd" xy);
ya unr par rvur eevee >see ereeneseeersseseeeeenereeeeecennl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 36Programming in C Unit-1
Ce ,
scanf() : scanf{ ) is a predefined formatted input function. it is used to read/scan
character data from standard input device(keyboard) at run time.The output screen will
wait for user input, unless& until user doesn’t provide input at run time; the rest of the
program won't be executed.
Syntax: int scanf("FormatSpecifiers”, &var1, &var:
Exampl
printf("\nEnter x & y Values :");
scanf("%d %d", &x, &y);
printf("\nx = %d\ty=%d"x,y);
Output
Enter x & y Values : 12 24
x=i2 yeaa
30. What is symbolic constant? How to declare it?
Constant: A constant is a value or variable that cannot be changed in the program, for
example; 10, 20,'a', 3-4, "e programming" ete,
Ways to define constant in C:
‘There are two ways to define constant in C programming.
1. const keyword
2, #define preprocessor
1, Using const keyword:
syntax:
const datatype variablename = value;
Ex.
const float Pi = 3.14:
2. Using #define preprocessor:
The #define preprocessor is also used to define constant,
Ex:
#include
define PI 3.142
int main()
{
print(("The value of PI is: %f",PI);
return 0;
yar unr par rvur eevee osenepsrerer-enmeseseeersseseeeeeneeeeeeenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 37Programming in C
Ce ,
Note: Practice all Lab programs, 4 to 5 programs will be asked for main theory
exams also. Kindly refer text book and previous year question papers for exams,
Use Below link to find Previous Year Question Papers:
CP Question Papers:
https://drive.google.com /drive/folders/1ugmW OwmGYI76vuEn2vWXigaDvEt ul
aO?usp=sharing
AL BCA Question Papers:
hittps://drive.google.com/drive/folders/1FOCEAtoFmil9Gx9snSGZYqEKsw4VkiS
w
ya unr par rvar eee vunenneny>sepepsereser-eeseseeersseseeesenenereeeeeeenl
Prof. Prabhu Kichadi, wree,(9880437187) — BCA-ISem. 38