0% found this document useful (0 votes)
12 views45 pages

Sri Manakula Vinayagar Engineering College Unit - 2: U23CSTC01 - Programming in C

This document provides an overview of Unit II of the Programming in C course at Sri Manakula Vinayagar Engineering College. It covers fundamental concepts such as the structure of a C program, data types, operators, expressions, and input/output operations. Additionally, it includes various questions and answers related to C programming, emphasizing key topics like control structures, operators, and functions.

Uploaded by

amalamargret.cse
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)
12 views45 pages

Sri Manakula Vinayagar Engineering College Unit - 2: U23CSTC01 - Programming in C

This document provides an overview of Unit II of the Programming in C course at Sri Manakula Vinayagar Engineering College. It covers fundamental concepts such as the structure of a C program, data types, operators, expressions, and input/output operations. Additionally, it includes various questions and answers related to C programming, emphasizing key topics like control structures, operators, and functions.

Uploaded by

amalamargret.cse
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/ 45

Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

Unit II

Introduction to ‗C‘ Programming – Basic structure of a ‗C‘ program – compilation and


linking processes – Constants, Variables – Data Types – Expressions using operators in
‗C‘ – Managing Input and Output operations – Decision Making and Branching – Looping
statements

1
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

Two mark questions with answer


1. Write the basic structure of C program. (MAY-2014)
Documentation Section
Header File Section / Link Section
Definition Section
Global (Variable) Declaration Section
main()
{
Declaration(local variable) part
Executable part
}
sub program section
function 1
function 2


Function n
Example : if (x == 1) { statement }

2. Give any two programming languages ? (Nov 2011)

(1) C Language:
C is a popular general purpose programming language. We can write the codes for operating
system, application programs and assembly language programs in C language
(2) PASCAL:
Pascal is an influential imperative and procedural programming language, designed in 1968–
1969 and published in 1970 by Niklaus Wirth as a small and efficient language intended to
encourage good programming practices using structured programming and data structuring.

3. List out the various stages in evolution of C by a Table form?

Language year Founder


ALGOL 1960 International group
BCPL 1967 Martin Richards
B 1970 Ken Thompson
C 1972 Dennis Ritchie
K & RC 1978 Kernighan and Ritchie
ANSI C 1989 ANSI committee
ANSI / ISO C 1990 ISO Committee

4. What is the purpose of main ( ) in C?


Main ( ) is a special function used by the c system to tell the computer where the program
starts. Every program must have exactly one main function. The empty parenthesis immediately
following main indicates that the function main has no arguments.

5.What is importance of keywords in C? ( APR/MAY 2015)


Certain reserved words are called as keyword. It has standard and predefined meaning in
‘C’ language. Some of them are
 auto
 double
 float
 void

6. Is ‘main’ a keyword in C language? Justify your answer. ( MAY 2011)


 Yes main is a keyword.
 It is used to mention main function of C program.
Example
main()

2
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

{
----
----
}

7. Distinguish between Logical and bitwise operators. (JAN-2016)

Logical Operators
These operators are used to perform logical operations on the given expressions.
 There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and
logical NOT (!).

S.no Operators Name Example Description

1 && logical (x>5)&&(y<5) It returns true when both conditions


AND are true

2 || logical (x>=10)||(y>=10) It returns true when at-least one of


OR the condition is true

3 ! logical !((x>5)&&(y<5)) If “((x>5) && (y<5))” is true, logical


NOT NOT operator makes it false

Bit wise Operators

 These operators are used to perform bit operations. Decimal values are converted into binary
values which are the sequence of bits and bit wise operators work on these bits.
 Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR),
<< (left shift) and >> (right shift).

OPERATOR MEANING DESCRIPTION


& Bitwise AND Binary AND Operator copies a bit to the result if it exists in
both operands.
| Bitwise OR Binary OR Operator copies a bit if it exists in either
operand.
^ Bitwise XOR Binary XOR Operator copies the bit if it is set in one
operand but not both.
<< Shift left Binary Left Shift Operator. The left operands value is moved
left by the number of bits specified by the right operand.
>> Shift right Binary Right Shift Operator. The left operands value is
moved right by the number of bits specified by the right
operand.
~ One’s Binary Ones Complement Operator is unary and has the
complement effect of 'flipping' bits.

8. What is meant by operator precedence?( NOV 2016, MAY 2014)

 Outermost parenthesis is evaluated first.


 Then innermost parenthesis.
 If there is two or more parenthesis, then the order of execution is from left to right.
 Next multiplication and division are performed.
 Finally addition and subtraction.

9. What is expression?
An expression represents a combination of variables, constants, and operators arranged as per
the syntax of the language.
Expressions are evaluated using an assignment statement of the form

3
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

variable = expression;
Example : 3.14 * r * r
s * (s - a) * (s - b) * (s - c)

10. What do you mean by structural programming? (JAN 2011)


 C is a structured language.
 A structured language allows variety of programs in small modules.
 It is easy for debugging, testing and maintenance if a language is a structured one.

11. What is the difference between the two operators = and ==? (APRIL 2010)
The Assignment Operator evaluates an expression on the right of the expression and
substitutes it to the value or variable on the left of the expression. The general form is
Syntax: identifier = expression
Eg: x = a + b;

Equality operator ( == ) is used together with condition. The value of the expression is one or
zero. If the expression is true the result is one, if false result is zero.

Syntax: if ( identifier == expression)

12. Write about increment and decrement operators? (APRIL 2010)

Increment Operators
It is used to increase the value of the Operand by 1. There are two types of Increment Operators
in C Language. They are pre Increment operator and post Increment operator.
Eg: ++g -> pre increment
g++ -> post increment

Decrement Operators
It is used to decrease the value of the Operand by 1. There are two types of Decrement Operators
in C Language. They are pre decrement operator and post decrement operator.
Eg: --g ----> pre decrement
g-- ----> post Decrement

13. What is difference between a constant and a variable? (Jan - 2010)


The constants are data items, the value of a constant cannot be changed during execution
of the program. But we can assign different values to a variable when every necessary in our
program.

14. Write any four escape sequences in C. ( JAN 2013)


(i) \n - new line
(ii) \t - tab
(iii) \a - alert
(iv) \0 - null

15. What is type casting?


C allows programmer to convert the type of an expression from one form to another by
placing the desired type in parentheses is before the expression. This is known as type casting.

Syntax :
(type-name) expression;

16. What are the features of C program?


‘C’ programs are fast and efficient.
‘C’ is highly portable
‘C’ is powerful, efficient, compact, and flexible.

4
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

‘ C’ has got rich set of operators.


It is a middle level language.
17. List out the rules to be followed in forming in identifier?( MAY 2017, JAN 2013 –
JUNE 2010)
Rules:
 First letter should be alphabets.
 Both numeric and alphabets are permitted.
 Both lower case and upper case are allowed.
 No special symbols are permitted except underscore (_).
 Keywords are not permitted.
 Blank space is not allowed.

Eg: STDNAME, sub , TOT_MARKS.

18. What is identifier? Give any two examples for an identifier. ( JAN 2009)
Or
What is a Variable ? illustrate with an example ( NOV/DEC 2014)
Identifiers are names given to various program elements such as variables, functions and
arrays etc.
Eg: STDNAME, sub , TOT_MARKS.

19. How to declare the variables?


Variables should be declaring inside the main function. It tells the compiler what is the
name of the variable, and type of the data that variable hold.
Syntax :
data_type v1 . v2. vn;

20. List out the rules for constructing a variable?


 A variable name can be any combinations of 1 to 8 alphabets, digits
 No commas or blank spaces are allowed.
 First character must be alphabet.

21. What is meant by constants?


The items whose values cannot be changed during the execution of program
Eg:
marks=90;
Discount = 15;

22. What is operator? What are the different types of operators in C? (Jan-2014)
An operator is a symbol that specifies an operations to the performed on operands
operators are used in programs to manipulate data and variables.
 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operators
 Increment and decrement operators
 Conditional operators
 Bitwise operators
 Special operators

23. What is an Operator and Operand?


An operator is a symbol that specifies an operation to be performed with the help of
operands.
E.g:
a+b here a, b  operands; (+) indicates operator

24. What is Ternary operator? (Jan-2010,Jan-2013 – APR/MAY 2011,NOV/DEC 2014)


It is also known s conditional operators. It checks the conditions and executes the
statement.
Syntax : condition? exp1: exp2;

5
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

Description: “?: ” operator acts as a ternary operator


o It first evaluates the condition
o If it is True then ‘exp1’ is evaluated
o If it is False then ‘exp2’ is evaluated
25. Give two examples for logical and relational expressions. ( JAN 2011)
Relational Expressions:
(i) (a>b)
(ii) (a==b)
Logical Expressions:
(i) if((a>b)&&(a>c))
(ii) if((a>b)||(a>c))

26. What are the Bitwise operators available in C ? ( JAN 2011)

It is used to manipulate the data at bit level .It operates only integers
Operator Meaning
& Bitwise AND
! Bitwise OR
^ Bitwise XOR
<< Shift Left
>> Shift Right
~ One’s complement

27. What is meant by unary operator?


“ C “ language has two useful operators generally not found in any other programming
languages.They are

 Increment ( ++ )
 Decrement ( -- )
These operators are generally known as unary operators.
Operator Meaning
++a Pre increment
--a Pre decrement
a++ Post increment
a-- Post decrement

28. What you mean by C tokens? ( MAY/JUNE 2012,May-2019)


‘C’ language contains the individual units called C tokens . They are:
 Identifiers
 Keywords
 Constants
 Strings
 Operators
 Special symbols

29. What is the purpose of assignment operator?


Assignment operator are mainly used to assign a value or expression or value of a variable
to another variable.
Syntax :
variable = expression;
E.g :
x = 10;
X= a+b;

6
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

30. List different data types available in C? ( MAY/JUNE 2014 )


Data types is a name refer to the kind of data in a program. C++ data types can be
classified as.
Four fundamental data types are
 Primary data types
 User defined data types
 Derived data types
 Empty
31. What are expressions?
An expression represents data item such as variables, constants, which are interconnected
with operators as per the syntax. An expression is evaluated using assignment operator
Syntax : variable = expression;
Example : x=a*b-c;

32. What is meant by control string? Give some examples?


It is the type of data that the user going to accept via input statements.
Examples:
% c  single character
% s  Strings
% f  float values
% d  decimal integer
33. Give a note about scanf() function?
Input data can be entered into the computer using standard input ‘C’ library function called
scanf( ). This function is used to enter any combinations of input.
scanf( ) function is mainly used to read information from the standard input device
keyboard.

Syntax :
scanf( control string” , &var1, &var2,….&varn) ;

E.g: int n;
scanf(“%d”,&n);
34. Give a note about printf() function?
Output data can be displayed from the computer using standard output ‘C’ library function
called printf( ). This function is used to display any combinations of data.
printf( ) function is mainly used to display information from the standard output device
Monitor.

Syntax:
printf( “control string “ , &var1,&var2,…&varn);
E.g:
int n;
printf(“%d”,&n);

35. Write the rules to be followed in ‘C’ language ?


 All the statements should be written in lower case.
 White spaces are not allowed while declaring variables ,keyword, function.
 All the statement should be ended with semi-colon ( ;)
 Upper case letters are used only for Symbolic statements.
 User can write one or more statements in a single line by separating them with a semicolon
(;).

36. What are all the characteristics of a ‘C’ program ?


 Clarity
 Integrity
 Simplicity
 Efficiency
 Modularity
 Generality ( overview)

7
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

37. How to initialize a variable? Give example?


Initialisation of a variable can be done using assignment operator( = )
Syntax :
variable = constant;
E.g:
i= 29; j=50;
int i=25;float k = 45;

38. List the Various input and output statements in C ( APR/MAY 2015)

Unformatted Input and output statement


 getc()
 getchar()
 gets()
Output:
 putc()
 putchar()
 puts()
Formatted input/output statements
 scanf()
 fscanf()
Output
 printf()
 fprintf()

39. Difference between scanf() and printf() functions with examples?

Scanf() Printf()
It is standard input ‘C’ library function. It is standard output’C’ library function.
It is a function used to read information It is a function used to display the
from the keyboard. information through monitor.
Scanf() function starts with string Printf() function starts with string
arguments and may contains additional arguments and may contains additional
arguments. arguments
E.g: int n ; E.g: int n ;
Scanf(“%d”,&n); printf(“Result is……%d”,&n);

40. Compare Global variable and local variable with examples ?


Global variable Local variable
Variables that are declared before the Variables that are declared after the
main ( ) function is known as global main( ) function is known as local
variables. variables.
The scopes of the variables are The scopes of the variables are
throughout the program. representing only in one block ( main
block )
E.g: int a,b; E.g: main ( )
main( ) {
{ int a, b;
……… ………
} }

41. Difference between high level language and low level language ?
Low Level High level
It is representing in 0’s and 1’s at bit It is represent in terms of normal
level. English.
Programmers can carry out operations at Programmers are design in such a way
bit level for better efficiency.

8
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

42. Give the steps for executing a ‘C’ program?


Execution is the process of running the program to execute a program. There are four
steps to be followed;
 Creating the program
 Compiling the program
 Linking the program with system library
 Executing the program

43. What are delimiters? List out the delimiters?


These are the special symbols which have syntactic meaning and have got significance.
It will not specify any operations.
Symbol Name Meaning
# Hash Pre-processor directive
: Colon Label Delimiters
; Semicolon Statement Delimiters
() Paranthesis Used in functions
{} Curly braces Used for ‘c’ block structure

44. Write a ‘C’ program to implement the expression ((m+n)/(p-m)*m), where


m=4,n=6,p=8. [Jan-2012 ]
main()
{
int m=4,n=6,p=8;
float e;
e=(m+n)/(p-m)*m;
printf(“%f”,e);
}
45. Write the following conditions using “?” operator. [ Jan 2009]

4x + 100 for x<40


Salary =
300 for x=40

4.5x + 150 for >40


Salary = x<40?4*x+100:x>40?4.5*x+150:300;

46. Write the limitations of using getchar() and scanf() functions for reading strings.
[Jan-2009 ]
getchar(): It is written in standard I/O library. It reads a single character only from a
standard input device. This function is not use for reading strings.

scanf(): It is use for reading single string at a time. When there is a blank was typed, the
scanf() assumes that it is an end.
47. What is compilation Process?(Nov/Dec 2015)

Compilation translates the source program into assembly instructions, which are then
converted to machine instructions. Finally, the linking process establishes a connection to the
operating system for primitive

48. Discuss the working modulo operator. (Nov/Dec 2015)

The modulo operation finds the remainder after division of one number by another
(sometimes called modulus).
Example
15%2=1;

9
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

49.What are variables? Give examples. (May/June 2016)

A variable is the reference of the memory location. A variable may change in value at the
time of program execution. Depending on conditions or on information passed to the program.
Example

int m1,m2,tot;
float avg;

50. Define implicit type conversion. (May/June 2016)

The ability of some compilers to automatically insert type conversion functions where an
expression of one type is used in a context where another type is expected.

51. What is the control statement? Give examples?


‘C’ language provides all the standard control structure that is available in programming
languages. These structures are capable of processing any information.
These are all the following conditions statements
 if statement
 if _else statement
 nested if_ else statement
 if_ else ladder

52. What is if statement?


The simplest form of the control statements is the if statement. It is very frequently used
in decision making and allowing the flow of program execution.
Syntax
if ( condition)
{
Statements;
}
In this if statement, its test a condition. If the condition is true, the statement associated
with if is executed, otherwise the statements are not executed.

53. List out the rules for writing switch statement?


 No real numbers are used in expression
 The switch can be nested
 The case keyword must be terminate with colon (:)

54. Compare switch and nested if statement?

Switch case Nested if


Switch can only test constant values. If can evaluate relational and logical
expressions.
In switch case statement nested if can be In nested if statement , switch 0 case
used. can be used.
Characters constants are automatically Character constants are automatically
converts to integers. converts to integer.

55. What are enumerated data types?


It is a user defined data types .It is provided by “c” language.

Syntax :
enum identifier { value 1,value 2, …value n } ;
enumday w_st, w_end;
w_st = mon ;
w_ end = sun;

10
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

The identifier follows with keyword enum is used to declare the variable.

56. Difference between break and continue statement? MAY 2015


Break Continue
Break statement takes the control to the Continue statement takes the control to
outside of the loop. the beginning of the loop.
It is also used in switch statement. It is used only in loop statement
It is always associated with if condition It is always associated with if condition
loops. loops.

57. Difference between nested if and switch case?

Switch ( ) case Nested if


It can test only constant values. It can evaluate relational or logical
expression
Character constant are automatically Character constant are automatically
converted to integers converted to integers.
Switch ( ) case statement nested if can In nested if statement, switch ( ) case
be used statement can be used.

58.What are global and local variables? (MAY-15)

A local variable is a variable whose existence is known only to a certain function or


program. Its scope is limited to a specific program block. For example, a variable declared in the
main program does not known to the function that is called in the main program.
Syntax:
void value(int a,int b)
{
int c,d; //local variables
}
A global variable is one whose existence is known throughout a c program. Such
variables are declared outside the main() and other functions of c. Typically, global declaration
takes place after the pre-processor statements in c.
Syntax:
int m=5,n=10; //global variables
void main()
{
int x,y; //local variables
}

59. Write short notes on goto statement?


Goto statement is mainly used to transfer the control unconditionally from one place to
another place in the program
It requires a label to identify the place to move the execution.
A label is a valid variable name and it must be ended with colon ( : )
Syntax:
goto label;
………..
……......
Label;

Label ;
…………
…………
11
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

Goto label;

Part-B
1. PROGRAM

A program consists of a series of instructions that a computer processes to

perform the requiredoperation. In addition, it also contains some fixed data,

required to perform the instructions, and the process of defining those instructions and

data.

A programmer must determine three basic requirements:

1. The instructions to be performed


2. The order in which those instructions are to be performed.
3. The data required to perform those instructions.
To perform a task using a program, a programmer has to consider various inputs of the
program along with the process, which is required to convert the input into desired output.
Suppose we want to calculate the sum of two numbers, A and B, and store the sum in C, here A
and B are the inputs, addition is the process, and C is the output of the program.

CHARACTERISTICS OF A PROGRAM

Any computer program should have the following characteristics

 Accuracy of calculations: Any calculation made in the program should be correct and
accurate.
 Clarity: It refers to the overall readability of the program which helps the user to
understand the underlying program logic easily without much difficulty.
 Modularity: When developing any program, the task is sub divided into several modules
or subtasks. These modules are developed independently (i.e.) each task does not depend
on the other task.
 Portability: Portability is defined as the ability to run the application program on different
platforms.

 Flexibility: Any program written should be flexible (i.e.) the program should be developed
in such a way that it can handle the most of the changes without rewriting the entire
program.

12
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

 Efficiency: Any program needs certain memory and processing time to process the data.
This memory and processing unit should be of least amount. This is the efficiency of the
program.
 Generality: The program should be in general. If a program is developed for a specific
task then it can be used for all the similar tasks in the same domain.
 Documentation: any application program developed should be well documented such that
even in the absence of the developer and the author, the programmers could be able to
understand the concept behind it.

2. Program Development Life Cycle [Univ. Ques.May-2016,Jan-2016, May 2015, Jan 2015, Jan
2014 ]

When we want to develop a program using any programming language, we follow a


sequence of steps. These steps are called phases in program development. The program
development life cycle is a set of steps or phases that are used to develop a program in any
programming language.
Generally, program development life cycle contains 6 phases, they are as follows….

 Problem Definition
 Problem Analysis
 Algorithm Development
 Coding & Documentation
 Testing & Debugging
 Maintenance

1. Problem Definition

13
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

In this phase, we define the problem statement and we decide the boundaries of the problem. In
this phase we need to understand the problem statement, what is our requirment, what should be
the output of the problem solution. These are defined in this first phase of the program
development life cycle.

2. Problem Analysis

In phase 2, we determine the requirements like variables, functions, etc. to solve the problem.
That means we gather the required resources to solve the problem defined in the problem
definition phase. We also determine the bounds of the solution.

3. Algorithm Development

During this phase, we develop a step by step procedure to solve the problem using the
specification given in the previous phase. This phase is very important for program development.
That means we write the solution in step by step statements.

4. Coding & Documentation

This phase uses a programming language to write or implement actual programming instructions
for the steps defined in the previous phase. In this phase, we construct actual program. That
means we write the program to solve the given problem using programming languages like C,
C++, Java etc.,

5. Testing & Debugging

During this phase, we check whether the code written in previous step is solving the specified
problem or not. That means we test the program whether it is solving the problem for various
input data values or not. We also test that whether it is providing the desired output or not.

6. Maintenance

During this phase, the program is actively used by the users. If any enhancements found in this
phase, all the phases are to be repeated again to make the enhancements. That means in this
phase, the solution (program) is used by the end user. If the user encounters any problem or
wants any enhancement,then we need to repeat all the phases from the starting, so that the
encountered problem is solved or enhancement is added.

3) INTRODUCTION TO C
C is a general-purpose high level language that was originally developed by Dennis
Ritchie at AT & T’s Bell Laboratories in 1972. Many of the important ideas of C stem from the
language BCPL(Basic Combined Programming Language), developed by Martin Richards.

C is a general-purpose high level language that was originally developed by Dennis


Ritchie for the UNIX operating system. It was first implemented on the Digital Equipments
Corporation PDP-11 computer in 1972.
C has now become a widely used professional language for various reasons.
 Easy to learn
 Structured language
 It produces efficient programs.
 It can handle low-level activities.
 It can be compiled on a variety of computers.
History of C language
C is one of the most popular programming language, it was developed by Dennis
Ritchie at AT & T’s Bell Laboratories of USA in 1972.
14
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

Programming Year Founder


Language
ALGOL 1960 International Group
BCPL 1967 Martin Richards
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie
K&R C 1978 Brain Kernighan and Dennis Ritchie
ANSI C 1989 ANSI Committee
ANSI/ISO C 1990 ISO Committee
‘C’ is a middle language
 Low level language-0 and 1’s.
 High level language: eg FORTRAN, PASCAL, COBOL, BASIC, C, C++……etc.
 C stands in between these two categories. It is neither a low level language nor a high
level language. It is a middle level language.
Features and applications of ‘C’ language
 C is a general purpose, structured programming language.
 It is powerful, efficient, compact and flexible.
 It is highly portable.
 It is a robust language.
 C is a middle level language, i.e. it supports both the low level language and high level
language features.
 C language allows dynamic memory allocation.
 ‘C’ programs are fast and efficient.
 ‘C’ has got rich set of operators.
 It can be applied in systems programming areas like compilers, interpreters and
assemblers, etc…

4) What is the basic structure of C program? Discuss briefly. ( May 2015)

STRUCTURE OF A C PROGRAM

Every C program contains a no. of building blocks. These building blocks should be written in a
correct order and procedure, to execute without any errors. The structure of C is given below.

DOCUMENTATION SECTION

PREPROCESSOR SECTION

DEFINITION SECTION & GLOBAL DECLERATION


SECTION

main()

{
DECLARATION PART

EXECUTEABLE PART

}
SUB PROGRAM SECTION

{
BODY OF THE SUB
PROGRAM
15
}
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

i) Documentation Section
 The general comments are included in this section.
 The comments are not a part of executable programs.
 The comments are placed between delimiters (/* and */).
Example:
/* Factorial of a given number */

ii) Preprocessor Section


 It provides preprocessor statements which direct the compiler to link functions from the
system library.
Example:
#include <stdio.h>
#include <math.h>
#include <string.h>
#include<conio.h>

iii) Definition Section


 This section defines all symbolic constants.
 It refers to assigning macros of a name to a constant.

Example:
#define PI 3.14
#define TRUE 1
#define FALSE 0

iv) Global Declaration Section


 It contains variable declarations, which can be accessed anywhere within the program.
 The variables that are used in more than one function throughout the program are called
global variable.
 It should declare before the main() function.
 Global variable otherwise known as External variable or Public variable
Example:
int a;
main()
{
------
------
}

v) main() function
 Each and every C program should have only one main() function.
 Without main() function, the program cannot be executed.
 The main function should be written in lowercase only.
 It should not be terminated with semicolon.

vi) Declaration Part


 Each and every variable should be declared before going to use those variables in
execution part.

vii) Execution part


 Here, the logic of the program can be implemented.
 These statements are known as program statements or building blocks of a program. They
provide instructions to the computer to perform a specific task.

viii) Subprogram section


 The subprogram section contains all the user-defined functions that are called in
the main () function.
 User-defined functions are generally placed immediately after the main () function,
although they may appear in any order.

16
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

Example Program

/*Documentation Section: program to find the area of circle*/

#include <stdio.h> /*Preprocessor section*/


#include <conio.h> /* Preprocessor section*/

#define PI 3.14 /*definition section*/

float area; /*global declaration section*/

void main()
{
float r; /*declaration part*/

printf("Enter the radius of the circle\n"); /*executable part


starts here*/
scanf("%f",&r);
area=PI*r*r;
printf("Area of the circle=%f",area);
getch();
}

5 EXECUTING THE PROGRAM:

4. COMPILATION & LINKING PROCESSES

Execution is the process of running the program, to execute a ‘c’ program, we need to
follow the steps given below.
1. Creating the program
2. Compiling the program
3. Linking the program with system library.
4. Executing the program.

6) Write about Character Set in ‘C’.

‘C’ CHARACTER SET


The character set is the fundamental raw material of any language and they are
used to represent information.

‘C’ program are basically of two types, namely


 Source character set
 Execution character set

17
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

C CHARACTER SET

SOURCE CHARCTER SET EXECUTION CHARACTER SET

Alphabets digits special Char. White space Character spaces Escape sequence

SOURCE CHARACTER SET


These are used to construct the statements in the source program.
These are of four types.

SOURCE CHARACTER SET NOTATION


Alphabets A to Z and a to z.
Decimal Digits 0 to 9
White spaces Blank space
Horizontal tabs
Vertical tab
New line
Form feed.
Special characters + plus
* asterisk
, comma
; Semicolon
? Question mark
^ Caret
$ Dollar
~ tilde
< Less than

EXECUTION CHARACTER SET


Certain ASCII characters are unprintable, which means they are not displayed on the
screen or printer. Those characters perform other functions aside from displaying text.
“Examples are backspacing, moving to a new line or ringing a bell”

ESCAPE
CHARACTER RESULT
SEQUENCE

Backspace \b Moves previous position

Horizontal tab \t Moves next horizontal tab

Vertical tab \v Moves next Vertical tab

New line \n Move next line

Form feed \f Moves initial position of next page

Back slash \l Present back slash

Null \0 Null. (end of the string)

18
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

7) Discuss about C – Tokens with relevant examples. (or) Lexical Elements[Apr/May-


2018]

C TOKENS
 C-Tokens otherwise known as ‘lexical elements’
 The smallest individual units of a C program are known as tokens.
 In C program, tokens are categorized into six, they are given below.

C Tokens

Keywords Identifiers Constants String Special Symbols Operators

i) Keywords
Keywords are reserved words whose meaning cannot be changed. They are used to
construct the program. They are written in lower case. There are 32 keywords are available.

auto double int struct const float short unsigned

break else long switch continue for signed void

case enum register typedef default goto sizeof volatile

char extern return union do if static while

ii) Identifiers

 It is used to refer the name of the variables, functions and arrays.


Rules

 An identifier must begin with a letter.


 Both upper case and lower cases are permitted.
 Keywords are not permitted.
 No special symbols are permitted except underscore (_).
 Some C compiler accept under score may appear in first letter.
 Maximum length of an identifier is 31.
 Blank spaces are not allowed in between an identifier.

Example

Valid Identifier Invalid Identifier


fact fact# -> Special symbols are not allowed
Fact 3fact -> first letter should be alphabet
FACT fac t -> No balnk space allowed
FACT3 int -> keywords not allowed

iii) Constants (7. Write about Constants and its types with example.)
(AU-APR/MAY 2015
 The items whose values cannot be changed during the execution of program are called
constants. ’C’ constants can be classified as follows.
19
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

‘C’ constants

Numeric constants Character constants

Integer Real constants Single Character String constants


constants constants
a) Numeric constants
There are two types of numeric constants,

1. Integer constants
2. Real or floating-point constants
1. Integer constants.
 An integer constant refers to a sequence of digits without a decimal point.

Example: marks 90, per 75

There are three types of integer constants namely,


a) Decimal integer constant (0 to 9) (Eg:10,-321)
b) Octal integer constant (0 to 7) (Eg.: 037,052)
c) Hexadecimal (0 to 9,A,B,C,D,D,E,F) (Eg : 0x4,0xBCF)

Rules for constructing Integer constants

* An integer constant must have at least one digit.


* It must not have a decimal point.
* It can be either positive or negative.
* If no sign precedes an integer constant, it is assumed to be positive.
* Commas or blanks are not allowed within an integer constant.
* The allowable range of integer constants is -32,768 to +32,767.

2. Real Constant
A Real constant is made up of a sequence of numeric digits with presence of a decimal
point.
Rules for defining real constants
 It must have at least one digit.
 It must have a decimal point which may be positive or negative.
 If it is negative, the sign is must or if it is positive, sign is not necessary.
 Use of blank space and comma is not allowed between real constants.
 Example: distance =126.0; Height = 5.6;
b) Character Constant
There are two types, they are given below.
i) Single Character constants
ii) String constants

i) Single Character constants


A single character constant or character constant is a single alphabet, a single digit or a
single special symbol enclosed within single inverted commas. Both the inverted commas should
point to the left
Example: ‫ۥ‬m‫ۥ‬ ‫ۥ=ۥ‬ ‫ۥ‬A
ii) String constants:
20
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

A string constant is a sequence of characters enclosed in double Quotes, the characters


may be letters, numbers, special characters and blank spaces etc.
Example: ”hi”, “325”.
 Declaring a variable as constant:
Syntax:
const datatype variable = constant
Description:
const -it is the keyword to declare constant.
Variable -it is the name of the variable.
Datatype - it is the type of data.
Constant - it is the constant.
Example:
const int dob = 3977;
 Declaring a variable as a volatile:
Syntax:
volatile datatype variable = constant
Description:
Volatile - it is the keyword to declare volatile
Variable -it is the name of the variable.
Datatype - it is the type of data.
Constant - it is the constant.
Example:
volatile int year=2007;

8) Explain about variables with example and scope of the variables.


In C, a variable is a data name used for storing a data value. Its value may be changed
during program execution. The value of variables keeps on changing during the execution of a
program. In other words, a variable can be assigned different values at different times during the
execution of a program.
The variable can be of different data types. They can be integer, float or character data
types. These data are stored in the memory and at the time of execution different operations are
performed on them.
Rules for naming the variables:
 A variable name can be any combination of alphabets, digits or underscore.
 But first character should be alphabets or an underscore (_).
 The length of the variable cannot exceed up to 8 characters long.
 Some of the c compilers can be recognized up to 31 characters long.
 The variable should not be a C keyword.
 Both lowercase and uppercase are permitted.
 The special symbols are not permitted except underscore.

Variable declaration:
Syntax:
datatype v1,v2,v3,….,vn;

Description:
data_type - It is the type of data.
V1, v2, v3 ,…, vn - list of variables.

Example 1:
int regno;
float cgpa;
char name[10];

Example 2:
Declaration of multiple variables of the same data types can be done in one statement.

int mark1;
int mark2;
int mark3;
int mark4;
21
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

can be written to become

int mark1, mark2, mark3, mark4;

Variables are declared at three basic places:


(i) When the variables are declared inside a function, they are called local variables.
(ii) When the variables are declared in the definition of function parameters, these variables
are called formal parameters.
(iii) When the variables are declared outside all functions, they are called global variables.

“Variables used in expressions are also known as operands”

Initializing variables:
Initialization of variables can be done using the assignment operator(==).

Syntax:
Variable = constant;
Or
Datatype variable = constant;
Example:
A=5;
B=8;
int i =23;
float s=3.14;
Scope of variables
Scope of a variable implies the availability of variables within the program.
Two types:
 Local variables
 Global variables

(i) Local variables:


The variables which are defined inside a function block or inside a compound statement of a
function sub- program are called local variables.

Example:
func()
{
int i=10; /* Local definition */
i++; /* Local variable */
printf( "Value of i = %d -- func() function\n", i );
}

(ii) Global variables:

The variables that are declared before the function main ( )


are called the global/external variables. These are available for all the
functions inside the program.

Example:
int i=4; /* Global definition */
main()
{
i++; /* Global variable */
func();
22
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

printf( "Value of i = %d -- main function\n", i );


}
func()
{
int i=10; /* Local definition */
i++; /* Local variable */
printf( "Value of i = %d -- func() function\n", i );
}
PART – C

1) Explain different data types in ‘C’ with examples. (May 2015, May 2014, Jan 2013]

DATA TYPES
Data type is the type of the data, that are going to access within the program. C
supports different data types, each data may have predefined memory requirement and storage
representation.
‘C’ supports the following 4 classes of data types.

(i) Primary data types:


C has the following basic built-in primary datatypes.
 int
 float
 double
 char

 Int (Integer)
Integer data type is used to store numeric values without any decimal point e.g. 7, -101,
107, etc.
Syntax:
int variable name;
Example:
int roll, marks, age;
 Float

23
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

Float data type is used to store numeric values with decimal point. In other words, float
data type is used to store real values, e.g. 3.14, 7.67 etc. e.g. percentage, price, pi, area etc.
may contain real values.

Syntax:
float variable name;

Example:
float per, area;
 Char (Character)
Char (Character) data type is used to store single character, within single quotes e.g. 'a',
'z','e' etc. e.g. Yes or No Choice requires only 'y' or 'n' as an answer.

Syntax:
char variable name;

Example:
char chi='a', cha;

 Double
Double is used to define BIG floating point numbers. It reserves twice the storage for
the number. It contains 8 bytes.

Syntax:
double variable name;

Example:
double Atoms;

S.No C Data types storage Range


Size
1 char 1 –127 to 127
2 int 2 –32,767 to 32,767
3 float 4 1E–37 to 1E+37 with six digits of precision
4 double 8 1E–37 to 1E+37 with ten digits of precision
5 long double 10 1E–37 to 1E+37 with ten digits of precision
6 long int 4 –2,147,483,647 to 2,147,483,647
7 short int 2 –32,767 to 32,767
8 unsigned short int 2 0 to 65,535
9 signed short int 2 –32,767 to 32,767
10 long long int 8 –(2power(63) –1) to 2(power)63 –1
11 signed long int 4 –2,147,483,647 to 2,147,483,647
12 unsigned long int 4 0 to 4,294,967,295
13 unsigned long long int 8 2(power)64 –1

(ii) User defined data type:


User defined data type is used to create new data types. The new data types
formed are fundamental data types.

Typedef:
The 'typedef' allows the user to define new data-types that are equivalent to existing
data types. Once a user defined data type has been established, then new variables, array,
structures, etc. can be declared in terms of this new data type.

Syntax:

24
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

typedef type new-type;

Type refers to an existing data type.


New-type refers to the new user-defined data type.

Example:
typedef int number;

Declare integer variables as: number roll, age, marks;


It is equivalent to: int roll, age, marks;

(iii) Derived Data type:


Data types that are derived from fundamental data types are called derived data types.
Derived data types don't create a new data type; instead, they add some functionality to the basic
data types. Two derived data type are - Array & Pointer.

 Array
An array is a collection of variables of same type i.e. collection of homogeneous data referred
by a common name. In memory, array elements are stored in a continuous location.

Syntax:
Datatype arrayname[ ];

Example:
int a[10];
char chi [20];

 Pointer
A pointer is a special variable that holds a memory address (location in memory) of
another variable.
Syntax:
datatype *var_name;

* is a pointer variable.
'var_ name' is the name where the variable is to be stored.

Example:
int a,*b;

variable 'b' stores the address of variable 'a'.

 Struct
A struct is a user defined data type that stores multiple values of same or different data
types under a single name. In memory, the entire structure variable is stored in sequence.

Syntax:
struct < structure name>
{
member1;
member2;
-----
-----
};
Structure name is the name of structure e.g. store details of a student as- name, roll, marks.
struct student
{
char name [20];
int roll,
float marks;
};

25
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

 Union
A union is a user defined data type that stores multiple values of same or different data
types under a single name. In memory, union variables are stored in a common memory location.

Syntax:
union < tag name>
{
var1;
var2;
-----
----
};
Tag name is the name of union, e.g, store details of a student as- name, roll, marks.

Union student
{
char name [20];
int roll,
float marks;
};

(iv) Empty data type

Void
Void data type is used to represent an empty value (or) null value. It is used as a return
type if a function does not return any value.

2.) What are the different types of operators available in C? Explain with examples.
[ May 2017, Nov 2016, May 2016, Jan 2015, Jan 2014, May 2013,May-2019 ]

OPERATORS AND EXPRESSIONS


Operator is a symbol that is used to manipulate arithmetic, logical and relational
expressions.
Operator is appearing in between operands.
Eg:
A + B;
TYPES OF OPERATORS:
 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operators
 Increment and Decrement operators
 Conditional operators
 Bitwise operators
 Special operators

a) Arithmetic operators

OPERATOR MEANING 26 EXAMPLES


Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

‘C’ + Addition 2+9=11 allows basic


Arithmetic - Subtraction 9-2=7 operations like
addition, * Multiplication 3*5=15 Subtraction,
Multiplication, and Division.
/ Division 9/3=3
% Modulus 9%2=1

Example:
#include<stdio.h>
#include<conio.h>
main ( )
{
int i,j,k;
clrscr( );
i=10;
j=20;
k=i+j;
printf(“values of k is %d”,k);
getch( );
}
Output:
Value of k is 30

b) Relational operator
A relational operator is mainly used to compare two or more operands.
OPERATOR MEANING EXAMPLE RETURN
< Less than 2<9 VALUE
1
> Greater than 2>9 0
== Equal to 2==2 0
!= Not equal to 2!=3 0
Example:
#include<stdio.h>
#include<coio.h>
main( )
{
clrscr( );
printf(“\n Condition: Return values\n”);
printf(“\n 5!=5 :%5d”,5!=5);
printf(“\n 5==5: %5d”,5==5);
}
Output:
Condition : Return Values
5! =5 0
5==5 1

c) Logical operator:
Logical operators are used to combine the results of two or more conditions.

OPERATOR MEANING EXAMPLE


&& Logical AND (9>2)&&(17>2)
|| Logical OR (9>2)!!17=17)
! Logical NOT 29!=29

Example:

27
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

#include<stdio.h>
main()
{
printf("\n Condition : return values\n");
printf("\n5>3 && 5<10: %5d",5>3 && 5<10);
printf("\n8>5||8<2 : %5d",8>5||8<2):
printf("\n!(8==8) : %5d",!(8==8));
}

Output:
Condition : Return Values
5>3 && 5>10: 1
8>5 II 8<2 : 0
!(8==8) : 0
d) Assignment operator
Assignment operators are mainly used to assign a value or expression or value of a
variable to another variable.
Example:
#include<stdio.h>
#include<Conio.h>
main( )
{
int i,j,k;
clrscr( );
k=(i=4,j=5);
printf(“k=%d”,k);
getch( );
}
Output:
K=5
e) Increment and Decrement operator
‘C’ languages have two useful operators generally not found in any other programming
languages. They are,
1. Increment (++)
2. Decrement (--)
These operators are generally known as Unary operators

OPERATOR MEANING
++a Pre increment
--a Pre decrement
a++ Post increment
a-- Post decrement

Example:
#include<stdio.h>
#include<conio.h>
main( )
{
int a=10;
printf(“a++=%d\n”,a++);
printf(“++a=%d\n”,++a);
printf(“a--=%d\n”,a--);
printf(“--a=%d\n”,--a);
}
Output:

28
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

a++=10
++a=12
a--=11
--a=11
f) Conditional operators
Conditional operators itself check the condition and executes the statement depending upon
the condition.
Syntax:

Condition ? exp1 : exp2;

Description:
“? :” operator acts as a ternary operator.
It first evaluates the condition
If it is true then ‘exp1’ is evaluated.
If it is false yhen’exp2’ is evaluated.
Example:
main( )
{
int a=5,b=3,big;
big=a>b?a:b;
printf(“Big is……%d”,big);
}
Output:
Big is 5
f) Bitwise operator:
It is used to manipulate the data at-bit level. It operates only integers.
OPERATOR MEANING
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift Left
>> Shift Right
~ One’s Complement
Example:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bit Operation of 12 and 25


00001100
& 00011001
________
00001000 = 8 (In decimal)

#include <stdio.h>
main()
{
29
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

int a=12,b=39;
printf("Output=%d",a&b);
}
Output
Output=4
g) Special operator:
‘C’ language supports some of the special operators they are
OPERATORS MEANING
, Comma operators
Size of Size of operators
& and * Pointer operators
. and -> Member section operators
Comma operators:
It is used to operate the statement such as variables, constants,expressin etc.
Example: val= (a=3,b=9,c=77);
Sizeof( ) operator:
IT is Unary operator.It returns the length in bytes of specified variable.It returns the
length in bytes of specified variable. It is very useful to find the bytes occupied by specified
variables in the memory.
Pointer operator:
&-> this symbol is used to specify the ADDRESS of the variables.
*-> this symbol is used to specify the VALUE if a variable.

3) Explain briefly the formatted & unformatted I/O functions in ‘C’. (May- 2014)
MANAGING INPUT AND OUTPUT OPERATIONS

 In C language there are 2 types of I/P & O/P statements are available. They are : several
functions are available for input/output operations in C. These functions are collectively
known as standard I/O library.

Input & Output functions

Unformatted I/O Statements Formatted I/O Statements


Input Output
scanf( ) printf( )
getc() putc()
fscanf() fprintf( )
getchar() putchar()

gets() puts()

a) Unformatted Input/Output statements


b) Formatted Input/Output statements

a) Unformatted Input/Output statements:


 These statements are used to single/group of characters.The user cannot specify the type of data.
 The following are the unformatted input/output statements available in C language.

INPUT OUTPUT
30
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

getchar() putchar()
getc() putc()
gets() puts()

Single character input – getchar() function:


 A single character can be given to the computer using C input library function
getchar().
Syntax:
char variable = getchar();
Eg:
char x;
x = getchar();

 This getchar() function is written in standard I/O library. It reads a single character from a
standard input device.

Program:
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
printf(“Enter any character/digit…”);
ch=getchar();
if(isalpha(ch)>0)
printf(“It is a alphabet”);
else
if(isdigit(ch)>0)
printf(“It is a digit”);
else
printf(“It is alphanumeric”);
}
Output:
1.Enter any character/digit…a
It is alphabet
2.Enter any character/digit…1
It is a digit
3.Enter any character/digit…#
It is alphanumeric

Single character output – putchar() function:


 It is used to display one character at a time on the standard output device.
Syntax:
putchar(character variable);
Eg:
char x;
putchar(x);

Program:
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
printf(“Enter any alphabet either in lower or uppercase..”)

31
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

ch=getchar();
if(islower(ch))
{
putchar(toupper(ch));
}
else
{
putchar(tolower(ch));
}
}
Output:
Enter any alphabet either in lower or uppercase…s
S
Enter any alphabet either in lower or uppercase…M
m
getc() function:
 This is used to accept a single character from the standard input to a character variable.
Syntax:
character variable=getc();
Eg:
char c;
c = getc();

putc() function:
 This is used to display a single character in a character variable to standard output device.This
function is mainly used in file processing.
Syntax:
putc(character variable);
Eg:
char c;
putc(c);

gets() function:
 The gets() function is used to read the string from the standard input device(keyboard).
Syntax:
puts(char type of array variable);
Eg:
puts(s);
Program:
#include<stdio.h>
#include<conio.h>
main()
{
char scientist[40];
puts(“Enter name:”);
gets(scientist);
puts(“print the name”);
puts(scientist);
}

OUTPUT:
Enter name: Risha
print the name: Risha

b) Formatted Input/Output statements:


The following are the input and output statements regarding formatted statements. They
are:

32
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

INPUT OUTPUT
scanf() printf()
fscanf fprintf()

scanf() function:
 Input data can be entered into the computer using standard input C library function called
scanf().This function is used to enter any combinations of input.
 scanf() function is mainly used to read information from the standard input device keyboard.
Syntax:
scanf(“control string”,&var1,&var2,…&varn);
Eg:
int n;
scanf(“%d”,&n);

Program:
#include<stdio.h>
#include<conio.h>
main()
{
int m,n,a;
clrscr();
printf(“Enter the 2 numbers:”);
scanf(“%d%d”,&m,&n);
if(m>n)
{
a=m;
m=n;
n=a;
}
printf(“the interchanged values are: “%d%d”,m,n);
getch();
}

printf() function:
 Output data can be displayed from the computer using standard output C
library function called printf().This function is used to display any combinations of
data.
 prints() function is mainly used to display information from the standard
output device(monitor).

Syntax:
printf(“control string”,&var1,&var2,…&varn);
Eg:
int n;
printf(“%d”,n);

Program:
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf(“Engineering Students \n”);
getch();
}

OUTPUT: Engineering Students

33
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

4) Nested if-else statement

It is otherwise known as Two-way with sub-way decisions. If else statement is


enclosed within another if else structure. An if statement can be followed by an optional else
if...else statement, which is very useful to test various conditions using single if...else if statement

Syntax: Flowchart
if(condition 1)
{
if(condition 2)
{
True statement 2
}
else
{
False statement 2;
}
}
else
{
False statement 1;
}
Next Statement;

Program:
#include<stdio.h>
main()
{
int a b c;
printf(“Enter the value for A, B and C:”);
scanf(“%d%d%d”,&a,&b,&c);
if((a>b)&&(a>c))
{
printf(“A is largest”);
}
else
{
if(b>c)
{
printf(“B is largest”);
}
else
{
printf(“C is largest”);
}
}
}
Output:
Enter the value for A,B and C:12 13 5
B is largest

5. Switch() case statement: (May-2019)


It is an alternative solution for else-if ladder concept. Switch statement is used to execute
a particular group of statements from several groups of statements. It is a multi way decision
statement, test the value of given variable or expression in a list of case values.

Rules of using switch case


 Values for ‘case must’ be integer or character constants.
34
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

 Floating point values are not allowed as case label.


 Switch case should have one default label.(optional)
 Const Variable is allowed in switch Case Statement.
 The order of the ‘case’ statements is unimportant.
 Case Label must be unique
 Case labels must have constants / constant expression
 Case labels must end with (:) colon.
 Empty Switch case is allowed.
 Each compound statement of a switch case should contain break statement to exit from
case.
 Two or more cases may share one break statement
 Comparison operators are not accepted
 Nesting ( switch within switch ) is allowed.

Advantages of Using Switch statement


 Easier to debug
 Faster execution potential
 Easier to read
 Easier to understand
 Easier to maintain

Syntax Flowchart

switch(expression)
{
case label1:
block 1;
break;
case label2:
block 2;
break;
……..
……..
default:
Default
block;
break;
}

Program:

#include<stdio.h>
main()
{
int a=1;

switch(a)
{
case 1:
printf(“I am in case 1 \n”);
break;
case 2:
printf(“I am in case 2 \n”);
break;
35
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

default:
printf(“I am in case default\n”);
break;
}
}

Output:
I am in case 1

3. if – else ladder
It is otherwise known as Multi-way decisions. Each and every else block will have if
statement. Last else block cannot have if block. Last else will have default statement.

Syntax Flowchart

if(condition1)
statement 1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
--------
--------
else
default
statement;

Example:

--------
--------
if(per >= 60)
printf(" You got 1st Class");
else if( per >= 45)
printf(" You got 2nd Class ");
else if(per>=27)
printf("\n You got 3rd Class ");
else
printf("\n NO Class ");
--------
--------

6) Describe the statements for decision making, branching & looping.


(JAN 2012, JAN 2011, JAN 2010, JAN 2009,JAN-2014, (AU – NOV/DEC 2015))

C has some kinds of statements that permit the execution of a single statement, or a block
of statements, based on the value of a conditional expression or selection among several
statements based on the value of a conditional expression or a control variable.

These are all the following conditional statements

36
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

(i) if statement
(ii) if-else statement
(iii) Nested if-else statement
(iv) if-else ladder (else if ladder)
(i)if statement:
It is otherwise known as One-way decisions. It is used to control the flow of execution of
the statements. The decision is based on a ‘test expression or condition’ that evaluates to either
true or false.
 If the test condition is true, the corresponding statement is executed.
 If the test condition is false, control goes to the next executable statement.

Syntax: Flowchart
if(condition is true)
{

Statement 1;
------------
------------
Statement n;
}

Next Statement;

Program:
#include<stdio.h>
#include<conio.h>
main()
{
int m,n,a;
clrscr();
printf(“Enter 2 numbers:”);
scanf(“%d%d”,&m,&n);
if(m>n)
{
a=m;
m=n;
n=a;
}
printf(“The interchanged values are: “%d%d”,m,n);
getch();
}
(ii)if-else statement:
It is otherwise known as Two-way decisions. It is handled with if-else statements. The
decision is based on a ‘test expression or condition’ that evaluates to either true or false.
 If the test condition is true, the true block will be executed then control goes to the next
executable statement.
 If the test condition is false, the false block will be executed control goes to the next
executable statement.

37
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

Syntax: Flowchart

if(condition is true)
{
True block;
}

else
{
false block;
}
Next statement;

Program:
#include<stdio.h>
main()
{
int a,b;
printf(“Enter two numbers:”);
scanf(“%d%d”,&a,&b);
if(a>b)
{
printf(“A is largest”);
}
else
{
printf(“B is largest”);
}
getch();
}
OUTPUT:
Enter two numbers:12 5
A is largest

(iii) Nested if-else statement


It is otherwise known as Two-way with sub-way decisions. If else statement is
enclosed within another if else structure. An if statement can be followed by an optional else
if...else statement, which is very useful to test various conditions using single if...else if statement

Syntax: Flowchart
if(condition 1)
{
if(condition 2)
{
True statement 2
}
else
{
False statement 2;
}
}
else
{
False statement 1;
}
Next Statement;

38
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

Program:
#include<stdio.h>
main()
{
int a b c;
printf(“Enter the value for A, B and C:”);
scanf(“%d%d%d”,&a,&b,&c);
if((a>b)&&(a>c))
{
printf(“A is largest”);
}
else
{
if(b>c)
{
printf(“B is largest”);
}
else
{
printf(“C is largest”);
}
}
}
Output:
Enter the value for A,B and C:12 13 5
B is largest

(iv) if – else ladder


It is otherwise known as Multi-way decisions. Each and every else block will have if
statement. Last else block cannot have if block. Last else will have default statement.

Syntax Flowchart

if(condition1)
statement 1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
--------
--------
else
default
statement;

Example:

--------
--------
if(per >= 60)
printf(" You got 1st Class");
else if( per >= 45)
39
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

printf(" You got 2nd Class ");


else if(per>=27)
printf("\n You got 3rd Class ");
else
printf("\n NO Class ");
--------
--------

(v) switch() case statement: (May-2019)


It is an alternative solution for else-if ladder concept. Switch statement is used to execute
a particular group of statements from several groups of statements. It is a multi way decision
statement, test the value of given variable or expression in a list of case values.

Rules of using switch case


 Values for ‘case must’ be integer or character constants.
 Floating point values are not allowed as case label.
 Switch case should have one default label.(optional)
 Const Variable is allowed in switch Case Statement.
 The order of the ‘case’ statements is unimportant.
 Case Label must be unique
 Case labels must have constants / constant expression
 Case labels must end with (:) colon.
 Empty Switch case is allowed.
 Each compound statement of a switch case should contain break statement to exit from
case.
 Two or more cases may share one break statement
 Comparison operators are not accepted
 Nesting ( switch within switch ) is allowed.

Advantages of Using Switch statement


 Easier to debug
 Faster execution potential
 Easier to read
 Easier to understand
 Easier to maintain

Syntax Flowchart

switch(expression)
{
case label1:
block 1;
break;
case label2:
block 2;
break;
……..
……..
default:
Default
block;
break;
}

40
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

Program:

#include<stdio.h>
main()
{
int a=1;

switch(a)
{
case 1:
printf(“I am in case 1 \n”);
break;
case 2:
printf(“I am in case 2 \n”);
break;
default:
printf(“I am in case default\n”);
break;
}
}

Output:
I am in case 1

7. JUMPS IN LOOPS [Jan-2016, Jan-2014]


UNCONDITIONAL LOOP
(i) Break
(ii) Continue
(iii) Goto

break statement:
1.It is used to terminate the loop. When the keyword break is used inside any ‘C’
loop,control automatically transferred to first statement after the loop.
2. A break is usually associated with an if statement.
Syntax:
break;
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int i;
for(i=1;i<=10;i++)
{
if(i==6)
break;
printf(“%d”,i);
}
}

Output:
12345

41
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

Continue statement
It is mainly used to take the control to the beginning of the loop, for these purposes
continue statement is used.
When the statements continue is used inside any ‘C’ loop, control automatically passes to
the beginning of the loop.
It is also associated with if statement.
Syntax:
continue;

Program:
#include<stdio.h>
#include<conio.h>
main()
{
int i,n,sum==0;
for(i=1;i<=5;i++)
{
print(“Enter any number…\n”);
scanf(“%d”,&n);
if(n<0)
continue;
else
sum=sum+n;
}
printf(“sum is…%d”,sum);
}
Output:
Enter any number…10
Enter any number…15
Enter any number…25
Enter any number…10
Enter any number…50
Sum is …100

Goto statement
 It is used to transfer control unconditionally from one place to another place.
 A goto statement can cause program control almost anywhere in the program
unconditionally.
 It requires a label to identify the place to move the execution.
 A label is a valid variable name and must be ended with colon (:).

42
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

Syntax:
goto label;
………
………
label:

label:
…….
…….
goto label;

Program:
#include<stdio.h>
main()
{
int a,b;
printf(“Enter the numbers”);
scanf(“%%d”,&a,&b);
if(a==b)
goto equal;
else
{
printf(“\n A and B are not equal”);
exit(0);
}
equal:
printf(“A and B are equal”);
}

Output:
1. Enter the numbers 3 3
A and B are equal
2. Enter the numbers 3 4
A and B are not equal

Important programs –University Questions

UNIVERSITY QUESTIONS – PART A

1.Define Recursion. (MAY-13, JAN-14, JAN-15, JAN-16, JAN 2010,apr/May-2018)


2.What is a null character? What is its use in string? (JAN-16)
3.What are global and local variables? (MAY-15)
4.What is meant by looping and explain its types? (JAN-13, MAY-14, MAY-15)
5.State the advantages of the use of functions. (MAY-2012, JAN 2010)
6.Differentiate do-while and while statements? (MAY 2017, JAN-2013)
7.What is the difference between functions declaration and function definitions?
8.State the difference between break and continue statement. (MAY 2015)
9.How the actual arguments match with formal arguments? (JAN 2013)

10.Explain parameter passing by reference? (May 2017,May-2014)

43
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

11. How does an array definition differ from an ordinary variable? (MAY-2012)
12. Define array and write its type. (MAY-2015)
13. Write any four features of arrays. (MAY 2016)

14. How strings are represented in C language? (MAY 2016)

15. Explain any two string functions with example. (NOV 2016,JAN 2011)
16. List any five built in string functions. (MAY 2017)
17.Write the syntax of else-if statements.[Apr/May-2018]
Part-B
1. Write a C Program to count the letter in sequence of characters.(May-2017)
2. Explain recursion by finding factorial of 5 using recursion.(May-2017,Apr/May-2016)

3. Write a Fibonacci numbers program(Nov-2016)


4. Write a Program to concatenate two strings and output the resulting string(Nov-2016,Apr/May-
2016)
5. Write a Program to sort a given set of numbers in ascending orders(Apr/May-2016,Jan-2013)

6. Write a C Program to find the addition and subtraction of two matrix (Apr/May-2016)
7. Discuss about the different looping statement used in C.(Jan-2016)
8. Write a Program to find the sum of n numbers using recursion(Jan-2016,May-2015)
9. Explain in detail about the break, continue and goto statements with an example program(Jan-2016)
10. Write a C Program to find whether a given number is odd or even.(May-2015)
11. Write a C program to print the sum of digits of the given numbers(May-2015)

12. Write a C Program to check whether the given string is palindrome or not(May-2015)
13. Discuss the different storage classes by identifying its scope and life time of variables(Jan-
2015,Jan-2013)
14. Explain about passing an array to function (Apr/may-2014 )

15. Write a C Program to determine whether a given numbers is Prime number or not(Apr/May-
2014)
16. Explain the string library functions with an example.(Apr/May-2014,2018,Jan-2014)
17. Write in detail about jumps in loops with neat example.(Jan-2014)

18. Write in short about multidimensional Array.(jan-2014)


19. Define array .explain the types of array in C with example Program.(May-2013)
20. Write C Program to join two strings directly (May-2013)
21. Elucidate the two dimensional arrays with an example.[Apr.May-2018]

44
Sri Manakula Vinayagar Engineering College Unit -2 U23CSTC01 –Programming in C

All the Best

“SUCCESS ALL DEPENDS ON THE SECOND LETTER”

45

You might also like