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

Programming with C

The document provides an overview of programming with C, detailing the types of programming languages, the history of C, and its characteristics as a middle-level language. It explains the role of translators like compilers and interpreters, lists the C character set, and defines key concepts such as tokens, variables, constants, and data types. Additionally, it outlines the structure of a C program, including sections for documentation, linking, definitions, and the main function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Programming with C

The document provides an overview of programming with C, detailing the types of programming languages, the history of C, and its characteristics as a middle-level language. It explains the role of translators like compilers and interpreters, lists the C character set, and defines key concepts such as tokens, variables, constants, and data types. Additionally, it outlines the structure of a C program, including sections for documentation, linking, definitions, and the main function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Programming with C

PROGRAMMING WITH C

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. Even though it is High level language, it is called as Machine level language because of
following reasons.
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

Page 1
Programming with C

solved.
Year Language Developed by
1960 ALGOL 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.
***** 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?


C is the most popular programming language. C has many advantages, which are listed below.
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.
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..
Portability: C program is compatible with majority of operating systems. Hence it is portable to other
systems even if the operating system differs.
Flexibility: C allows a lot of flexibility in data conversion from one data type to another i.e. converting

Page 2
Programming with C

from integer to character and character to integer.


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.
General purpose programming language: C can be used to implement any kind of applications such as
Business applications and Scientific oriented applications.
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?
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.
Alphabets : A, B, C … Z
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(or less then sign)
“ quotation mark ! exclamation mark
| vertical bar > closing angle bracket(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
Page 3
Programming with C

operation. C has 6 types of tokens. They are:

Page 4
Programming with C

C tokens

Identifiers Keywords Variables Constants Special Operators


Characters

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 of 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: rollno=25; (wrong)
✓ 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.

Page 5
Programming with C

Constants

Numeric constants Alphanumeric constants

Integer Floating point Single String Boolean


Constants (or) Real Character Constants Constants
Constants 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(“ ”).
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?
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.

Page 6
Programming with C

Escape Sequence 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

Q: 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.
Data types

System defined/ User defined Derived Data Empty Data


primitive Data Data types types types
types

Structures
Arrays Void
Numeric Alpha
numeric Unions
Enumerations Pointers
Integer char
float, double string

1. 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.

Page 7
Programming with C

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 3.440000
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 int 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
Floating point type 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
Character type char 1 byte -128 to +127
unsigned char 1 byte 0 to 255

2. User defined data types: These data types are defined and used by the programmer.
Ex: structures, unions, enumerations.
3. Derived Data types: These data types are derived from primitive data types.
Ex: Arrays and pointers.

Page 8
Programming with C

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 variable is a data 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
i. It tells the compiler what the variable name is
ii. It specifies what type of data the variable will hold.

Syntax: datatype variable_name; (Or) datatype var1, var2, var3,……;


Ex: int rno;
float fee, amount;
Q: 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


Function n
(User defined functions)

Page 9
Programming with C

i. 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*/
ii.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>
iii. The definition section: It defines all symbolic constants.
iv.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.
v.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 (;).
vi.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>
void main( )
{ Output:
welcome to c-language
printf(“ welcome to c-language”); This is my first C program
printf(“ This is my first C program”);
}

Page 10
Programming with C

Q: Explain the procedure for creating, compiling, linking and executing a C program.
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.
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: 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:

Page 11
Programming with C

Conversioncharacter 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;
Output:
char symbol=’&’; Value of n=10
clrscr(); Value of salary=1000.000000
printf(“\n value of n is=%d”,n); Value of symbol is=&
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).
➢ 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 andthey 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: 1)#include<filename> 2) #include“filename”
Ex: #include<stdio.h> #include“abc.c”

Page 12
Programming with C

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:1) #defineCOUNT 100
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.

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 is50*/
}
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.


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:
Page 13
Programming with C

• 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.
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 avariable.
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

1.auto:If a variable is declared as “auto” then it is called as “automatic variable”.


➢ Automatic variables are also known as Local variables.

Page 14
Programming with C

➢ 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
2.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”.
Ex:#include<stdio.h>
extern int x=30;
void show( );
void main()
{
printf(“\n x=%d”, x);
show( );
}

Page 15
Programming with C

void show( ) Output:X=30


{ X=30
printf(“\n x=%d”, x);
}

3.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( );
}
void increment(void)
{
static int i = 0;
printf(“%d”, i);
i++;
}
Output:
0123

Page 16
Programming with C

4.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.
➢ Registervariablewillbeaccessedveryfasterthanthenormalvariablessincetheyare 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
64bits)
Ex: #include<stdio.h>
void 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

Q. Explain I/O functions in C? (Or) Discuss the elementary functions of Input and Output in C?
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
i).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( )

Page 17
Programming with C

ii).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()
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 string 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 Datatypes:
int num;
float fee;
char gender;
char name[20];
scanf(“%d%f%c%s”, &num, &fee, &gender, name);

Page 18
Programming with C

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);
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 Integern umbers:
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?
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:
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( );
Page 19
Programming with C

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 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);
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: ASZ

Page 20
Programming with C

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.

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 int unsigned int long int

long double double float 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;
x= 3.2; /* causes error */
x= (int) 3.2; /* x will be 3 */

Page 21
Programming with C

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.
Based on Nature Operators can be classified into two types based on the following.
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.

i) Arithmetic operators: These operators are used to develop arithmetic operations.

Operator Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division (quotient)
% Modulo division (remainder)

Ex: #include<stdio.h>
void main()
{
int a, b, c, d, e, f, g;
clrscr( );
printf(“\n Enter two numbers”);
scanf(“%d%d”, &a, &b);
c=a+b;
d=a-b;

Page 22
Programming with C

e=a*b;
f=a/b; Output:
Enter two numbers
g=a%b;
20
printf(“\n Addition=%d”, c); 10
printf(“\n Subtraction=%d”, d); Addition=30
Subtraction=10
printf(“\n Multiplication=%d”, e);
Multiplication=200
printf(“\n Division=%d”, f); Division=2
printf(“\n Remainder=%d”, g); Remainder=0
}
ii) Relational operators: Relational operators are used to make comparisons between operands. These
operators require two operands so these are also called as binary operators.

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

iii) Logical operators: These operators are used to form compound conditions by combining two or more
relations.
Operator Meaning
&& Logical AND

|| Logical OR

! Logical NOT

Page 23
Programming with C

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

iv) 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.
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 Statement with simple assignment operator

a+ =1 a=a+1
a - =1 a=a–1
a* =1 a=a*1
a/ =b a=a/b
a% =b a = a% b

v) 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.
vi) 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.
Ex: res = (x=10, y=5, x+y);

Page 24
Programming with C

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);

printf(“\n a=%d”, a); Output:


printf(“\n b=%d”, b); 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

vii) 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.

Page 25
Programming with C

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.

viii) 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

Page 26
Programming with C

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 left side and 0’s are added from right.
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:

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

Page 27
Programming with C

Q: Explain control structures in C.


Normally statements in C program are executed sequentially i.e. in the order in which they are written.
This is called Sequential execution. Transferring control to a desired location in a program is possible through
control structure. C allows many kinds of control structures, which include:

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

Page 28
Programming with C

the following form:

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)


{ test true
expressi
Statement-block; on
?
}
Statement-x; Statement-block

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 “false- block” statements will be
executed.

Page 29
Programming with C

Syntax: Flow chart: entry

if (test expression)
{ True false
test
True-block statements; expression
} ?
else False block
{ True block statements
False-block statements; statements
} Statement-x
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: Flowchart:

if(condition1) false true


{ Condition1
if(condition2)
{ Statement-1; }
else false true
Statement-3 Condition2
{ statement-2; }
}
else Statement-1
Statement-2
{
Statement-3;
}
Statement-x;

Statement-x

Page 30
Programming with C

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 False
Statement-1 Condition2

True False
Statement-2 Condition3

Statement-3 True False


Condition n

Statement-n default-statement

Statement-x

Page 31
Programming with C

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)
if(a>b && a>c)
statement-1;
else if(condition2) printf(“a is big”);

statement-2; else if(b>c)

else if(condition3) printf(“b is big”);

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;

Page 32
Programming with C

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

Page 33
Programming with C

Example: program to display the name of the day depending on the number entered from keyboard.
#include<stdio.h>
Void main( )
{
int day;
clrscr( );
printf(“\n Enter a number between (1-7)”); scanf(“%d”,
&day);
switch (day)
{
case 1: printf(“\n Monday”);
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;
Output:
case 6: printf(“\n Saturday”);
break; Enter a number between (1-7)
case 7: printf(“\n Sunday”); 2
break; Tuesday
default: printf(“\ U entered a wrong number”);
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.

Page 34
Programming with C

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>
# 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++;
if (i<=10)

Page 35
Programming with C

goto START;
getch( ); Output: 1 2 3 4 5 6 7 8 9 10
}

Q: Explain Looping control structures (Iterative control structures).


The process of repeatedly executing a block of statements is known as looping. In looping, sequences 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 Entry

Test False
Condition Body of the
Loop

True

Body of the Test True


Loop Condition

False

a) Entry controlled loop b) Exit controlled loop


Ex: while, for Ex: do-while

Page 36
Programming with C

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)
{ True Body of the loop
condition
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;

}
}
Above program prints “hello” for 10 times.

Page 37
Programming with C

ii) do-while loop: It is an Exit controlled loop statement. The basic form of do-while statement is:
Initialization;
do True

{ Condition
Body of the loop
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:

for (initialization ; condition ; increment/decrement)


{
Body of the loop
}

Page 38
Programming with C

initialization

True
Condition 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++)
{
printf(\n hello”);
}
}
The above program prints “hello” for 10 times.
Q: 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.

Page 39
Programming with C

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)
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>.

Page 40
Programming with C

1 Q: What is a function? Explain its advantages?


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( ) and
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:
a. Mathematical functions
b. String functions
c. Character functions
d. Date functions

Q: Explain mathematical functions in C?

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>

Page 41
Programming with C

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. String functions are declared in the header file “string.h”.

Page 42
Programming with C

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): This function checks whether the passed character is Alphabetic.
3. int 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.

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.

Page 43
Programming with C

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

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

Page 44
Programming with C
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 Function C

B1 B1

Top-down modular programming using functions

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(;),
Page 45
Programming with C
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”);
}

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”.

Page 46
Programming with C

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:
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.
Page 47
Programming with C

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 Non-linear recursive function
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”);
scanf(“%d”, &n);
fact= factorial(n);
printf(“\n factorial of %d is=%d”, n, fact);
}
Page 48
Programming with C

int factorial( int n)


{ Output:
if( n= = 1) Enter a number
return 1;
else
5
Factorial of 5 is 120
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?

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:
message( );
This is sample function
This is sample function
message( );
}
void message( )
{
printf(“\n This is sample function”);
}

Page 49
Programming with C
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); Output:
sum( -5, 25);
Sum=30
}
void sum( int x, int y) Sum= 20
{
int z= x+y;
printf(“\n Sum= %d”, z);
}
3. No Argument, Return: A function, which does not take arguments but returns a value.
Ex: #include<stdio.h>
int sum( );
main()
{
int k;
clrscr( ); Output:
k= sum( );
printf(“\n Sum=%d”, k); Sum=30
}
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);
}
Page 50
Programming with C
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( )
{ Output:
int a=10, b=20;
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;
}

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.

Page 51
Programming with C
Ex: #include<stdio.h>
void swap(int *x, int *y); main( )
{
Output:
int a=10, b=20; a=10, b=20
clrscr( ); 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

Q: 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.

Page 52
Programming with C
• 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];

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:

Syntax: datatype arrayname[size] = {value0, value1, value2,……};


Ex: int a[5]= {10, 20, 30, 40, 50}; 0 1 2 3 4
a 10 20 30 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]);

Page 53
Programming with C

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 represents 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

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]);

Page 54
Programming with C

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.
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.

Page 55
Programming with C
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.

❖ 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?
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.
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.

Page 56
Programming with C
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”.

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

Page 57
Programming with C
The following program explains the usage of string functions.
1) Length of a string:
#include<stdio.h>
#include<string.h>
main( )
{
int L;
char x[10]; Output:
printf(“\n enter a string:”);
Enter a string:
scanf(“%s”, x);
L=strlen(x); Apple
printf(“\n length of given string=%d”,L); Length of given string=5
}

2) To compare two strings:


#include<stdio.h>
#include<string.h>
main( ) Output:
{
char x[10], y[10]; Enter two strings:
int k;
printf(“\n Enter two strings:”); Ramesh
scanf(“%s”, x);
Rajesh
scanf(“%s”, y);
k= strcmp(x,y); Ramesh is big
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( )
{
char x[10], y[10];
Output:
printf(“\n Enter two strings:”);
scanf(“%s”, x); Enter two strings:
scanf(“%s”, y);
Hello
strcat(x,y);
printf(“\n strings after concatenation:%s”, x); Welcome
}
Strings after concatenation: Hello Welcome
4) To copy two strings:
#include<stdio.h>
#include<string.h>
Page 58
Programming with C
main( )
{
char x[10], y[10]; Output:
printf(“\n Enter a string:”); Enter a string:
scanf(“%s”, x);
strcpy(y, x); Hello
printf(“\n String copied in y=%s”, y); String copied in y= Hello
}
5) To convert into lower and uppercase:
#include<stdio.h>
#include<string.h>
main( )
{
char x[10];
Output:
printf(“\n enter a string:”);
scanf(“%s”, x); Enter a string:
strupr(x); Apple
printf(“\n String in uppercase=%s”, x); String in uppercase=APPLE
strlwr(x); String in lowercase=apple
printf(“\n String in lowercase=%s”, x);
}
6) To reverse a string:
#include<stdio.h>
#include<string.h>
main( )
{
char x[10];
Output:
printf(“\n enter a string:”); Enter a string:
scanf(“%s”, x); Apple
strrev(x); String after reversing= elppA
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.

Page 59
Programming with C

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 list of

data-type member1; variables declared in between { and } are known as “structure


members” or “member variables”.
data-type member2;
:
};
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.

Syntax: struct tag-name var1, var2, var3, ……;

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.
Page 60
Programming with C

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>
Memory
main( )
{
struct student
{
char name[15];
int rno;
int marks;
} S1

struct student s1;


clrscr( );
strcpy(s1.name, “Ravi”);
Output:
s1.rno=35;
Ravi 35 98
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};
Memory
Example program: b1
#include<stdio.h> name Ramesh
main( ) acno 120
{
amount 15000
struct bank
{
char name[20];

Page 61
Programming with C
int acno;
int amount;
};
struct bank b1={“ramesh”, 120,15000}; /* structure initialization */
clrscr( ); Output:
printf(“\n Name=%s”, b1.name); Name= Ramesh
printf(“\n AccountNo=%d”, b1.acno); AccountNo=120
printf(“\n Amount=%d”, b1.amount); Amount=15000
}
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> Memory


struct student 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( )
{
struct student s1={"chandu",24,95};
Page 62
Programming with C
clrscr( );
Output:
display(s1);
} Name=chandu
void display(struct student s) Roll No= 24
{ Marks=95
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 1 2

int i; sri nivas shiva


s name name name

struct student
15 25 35
rno rno rno
{
marks 98 marks 85 marks 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

Page 63
Programming with C
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:
c1=red; 10 30
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:

Syntax: union tag-name


{
data-type member-variable1;
data-type member-variable2;
:
};
Example:
#include<stdio.h> main( )
{
union alpha

Page 64
Programming with C
{
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: 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;
};
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.

Structures Unions

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. All the variables in the union are allocated with
3. Each variable in the structure is allocated with common memory.
separate memory. 4. The size of the union is equal to the largest
4. The size of the structure is equal to the sum of variable inside the union.
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 accessed 6. All the members of the union are
accessed with dot (.).
with dot (.).

Page 65
Programming with C

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.
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

Page 66
Programming with C
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.

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: datatype *pointervariable_name;

Ex: int *p; float


*iptr;
Example program using pointers:

Page 67
Programming with C
#include<stdio.h> 101 102

main( ) 10
n
{ 201 202
int n=10, *p; p 101

p= &n;
printf(“%d”, n); /* prints 10 */
printf(“%d”, *p); /* prints 10 */
printf(“%d”, *(&n)); /* prints 10 */
printf(“%u”, p); /* prints the address*/
}

Page 68
Programming with C
Q. Programming Rules:
i) All lines of C- statements must end with a semicolon.
ii) C is case-sensitive.
iii) A C-program statement can be split into many lines or can be written in one line.
iv) Braces {} must always match upon pairs.
v) All C-programs starts with main() function
vi) Comments cannot be nested.
/*first program ,
welcome to C*/
Q. ALGORITHM:
Definition: An algorithm is a finite sequence of well-defined steps for solving a problem in a systematic
manner. It is written in natural languages like English.
Advantages: i) Easy to write
ii) Human readable techniques to “understand logic”.
Disadvantages: i) Difficult to debug.
ii) Difficult to show branching and looping
Example: Print 1 to 20 numbers
Algorithm:
Step1: Initialize x as 0
Step2: Increment x by 1
Step3: Print x
Step4: If x is less than 20 then go back to step 2.
Q. Flowchart:
A flowchart is a pictorial or graphical representation of a process/Algorithm. Each step in the algorithm is
represented by a different symbol and contains a short description of the algorithm steps.
Advantages: i) Easy to draw
ii) Easy to understand the logic
iii) Easy to identify mistake by the non-computer person.
iv) Easy to show branching and looping
Disadvantages: i) Time consuming ii) Difficult to modify
iii) Very difficult to draw a flowchart for big or complex problems.

Page 69
Programming with C
Example: print 1 to 20
Start

Initialize x=0

Increment x by 1

Print x

x<20

stop

Difference between Flowchart and Algorithm:

Flowchart Algorithm
1. It is a pictorial representation. 1. Step-by-step process
2. Solution is shown in graphical format. 2. Solution is shown in non-computer
3. Easy to understand language.
4. Easy to show branching and looping 3. Difficult to understand
5. Difficult to debug the errors 4. Difficult to show branching and looping
6. Flowchart for big problem is impractical. 5. Algorithm can be written for any problem
6. It is difficult to write algorithm as
compared to flowchart.

Page 70

You might also like