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

PPA Notes

The document outlines the syllabus for a BCA first semester course on Programming Principles and Algorithms, detailing five units covering topics such as programming fundamentals, operators, problem-solving techniques, complexity analysis, and functions. Each unit includes key concepts, definitions, and examples relevant to computer programming. The document serves as a comprehensive guide for students to understand the foundational principles of programming and algorithm development.

Uploaded by

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

PPA Notes

The document outlines the syllabus for a BCA first semester course on Programming Principles and Algorithms, detailing five units covering topics such as programming fundamentals, operators, problem-solving techniques, complexity analysis, and functions. Each unit includes key concepts, definitions, and examples relevant to computer programming. The document serves as a comprehensive guide for students to understand the foundational principles of programming and algorithm development.

Uploaded by

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

Study Material

BCA
First Semester
Programming Principles and
Algorithm

1
INDEX
Contents Page Number
Course Contents/ 3
Syllabus
Unit 1 4
Unit 2 12
Unit 3 20
Unit 4 26

Unit 5 31

2
BCA-113 PROGRAMMING PRINCIPLES AND ALGORITHMS
Course Contents

UNIT I
Introduction to Programming: Language Fundamentals History, Structures of Programming,
Function as building blocks, Character set, Keywords, Identifiers, Variables, Constant, Data
Types, Comments.
UNIT II
Operators: Build in Operators and function, Types of operators, Precedence and Associativity,
Expression, Statement and types of statements.
UNIT III
Introduction to Problem - solving: Introduction, techniques (trial and error, brainstorming, divide
and conquer).Steps in problem - solving (define problem, analyse problem and explore solution),
Flowcharts, Algorithms, Pseudo code (definition, symbols, characteristics).
UNIT IV
Time and Space complexity: Time Complexity: Big-O Notation, Omega notation, Theta notation,
Efficiency, Introduction to space complexity.

Simple Arithmetic Problems: Addition / Multiplication of integers, Determining if a number is +ve


/ -ve / even / odd, Maximum of 2 numbers, 3 numbers, Sum of first n numbers, given n numbers,
Integer division, Factorial , Prime number, GCD numbers , Swapping, Recursion (Write algorithms
and draw flowchart).

UNIT V

Functions Basic types of function, Declaration and definition, Function call,


Types of function, Parameter passing, Call by value, Call by reference, Scope of variable , Stroage
classes, Recursion.

3
UNIT I
Introduction to Programming
The history of programming languages spans from documentation of early mechanical computers
to modern tools for software development. Early programming languages were highly specialized,
relying on mathematical notation and similarly obscure syntax. Throughout the 20th century,
research in compiler theory led to the creation of high-level programming languages, which use a
more accessible syntax to communicate instructions.
The first high-level programming language was Plankalkül (Plancalculus - relating to or being
mathematical prerequisites for the study of calculus), created by Konrad Zuse between 1942 and
1945. The first high-level language to have an associated compiler was created by Corrado Böhm
in 1951, for his PhD thesis. The first commercially available language was FORTRAN (FORmula
TRANslation), developed in 1956 (first manual appeared in 1956, but first developed in 1954) by a
team led by John Backus at IBM.
Computer Programming
Computer Programming is the process of writing instructions that direct the computer to perform a
set of tasks. All software programs adhere to certain programming principles and concepts.
Fundamental programming concepts include a set of basic principles and related terminologies that
programmers follow to write code that is simple to understand, modular, and efficient. The basic
programming concepts include variables, basic control structures, data structures, object-oriented
programming, troubleshooting and debugging, and various programming tools. These concepts are
similar across various programming languages, such as Python, C++, C, and Java.
There are 6 basic programming concepts:

1. Variable declaration:
Variables are containers for storing values. The variable declaration indicates that the operating
system is going to reserve a piece of memory with that variable name. You can define a
variable with alphabets, digits, and underscores. Variable names can start with an alphabet or
an underscore but cannot start with a digit. Some variable types across several programming
languages are:
 Constant variable: You can use constant variables to store data whose value doesn't change
throughout the program.
 Global variable: You can declare global variables outside a function. These variables are
accessible throughout the program.
 Class variable: You can access class variables within a specified class. These variables are
accessible by specifying their class names.
 Instance variable: You can declare instance variables inside a class but outside a method.
These variables are accessible throughout the class in which you've declared them.
 Local variable: You can declare local variables in classes, methods, or instances. You can
access these variables only within the specified class or method.

2. Control Structures:
A control structure specifies the flow of control in a program. Analyzing certain parameters and
conditions determines the flow direction of a program. Control structures make it easier to
understand a flow of logic when developing algorithms or writing programs. There are three basic
types of control structures:
Sequential logic: The flow of a program executes in a specific order without skipping, jumping, or
switching to another block of code.
Selection logic: A condition determines whether a block of code gets executed or skipped.
Common examples include if and else-if.
Iteration logic: A block of code repeats a fixed number of times to achieve the desired result.
Common examples include for and while loop.
4
3. Data Structure: A data structure provides an effective way to store and retrieve data. There are
various data structures that computer programmers can use to complete tasks and run applications.
These are some common data structures used in software development:
Arrays: Arrays organize data by storing similar elements together and using contiguous memory
allocation. You can use arrays to store an ordered list of items.
Stacks: Stacks are linear structures that follow a last-in, first-out (LIFO) order for executing
operations. You can use stacks to implement backtracking algorithms.
Queues: The queue is a linear structure that follows a first-in, first-out (FIFO) order for executing
operations. You can use them in mail queues, CPU scheduling, and first-come, first-serve (FCFS)
scheduling.
Linked lists: Linked lists are linear data structures that use pointers to link elements as opposed to
contiguous memory locations. You can use them to implement stacks, queues, and graphs.
Binary trees: Binary trees are non-linear structures that contain nodes that have two possible
values or directions. You can use binary trees to represent hierarchy and determine structural
relationships in data.
Graphs: Graphs contain nodes and edges connected to one another. You can use these data
structures to study maps, resource allocation in operating systems, and social media networks.

3. Object-oriented Programming:
Object-oriented programming is based on the concept of objects and classes where an object may
contain data in the form of attributes and methods. Classes are user-defined blueprints or
prototypes from which you can create objects. For example, consider a class that represents a
person. The person class contains attributes such as name, date of birth, blood group, nationality,
gender, and height.
You can then use this class as a blueprint to create objects where each object would represent a
different person with a unique set of attributes. Some important concepts in object-oriented
programming include:
Encapsulation: Encapsulation is the binding of data elements, such as variables and properties and
member methods, into one unit.
Abstraction: This enables you to hide specific details about a class and provide only essential
information to the outside world. For example, the working mechanism of a web server is unknown
to the end-user, who clicks on a button and receives the required information.
Inheritance: This is the ability to create a new class from an existing class. For example, you can
create a child class which inherits all the properties of its parent class and has its own set of
additional properties and methods.
Polymorphism: Using polymorphism, you can access objects of different types using the same
interface where each object provides its own implementation.
5. Debugging: Debugging is the process of removing errors from computer programs that allow
software development and engineering teams to produce functioning software. Through debugging,
they can examine individual sections of code to ensure that the program works as intended. Below
is a list of possible programming errors:
Syntax error - A syntax error occurs when there is an erroneous sequence of characters or tokens
in the code that doesn't follow the syntax of a programming language. These may include
indentation errors, missing brackets, extra commas, and misspelt commands. Programming tools
detect these errors at compile time and display the line number and type of error, along with the
error description. You can review the error description and modify the code so that it follows the
right syntax.
Logical error - A logical error occurs when there is a flaw in the algorithm or logic of the code,
which either halts the execution of a program or produces a wrong output. You encounter logical
errors only during run-time since there are no errors in the code's syntax. For example, wrongly
initializing a variable can cause a logical error in the code.
5
Latent error - Latent errors, also known as hidden errors, arise when you use a specific set of data
as input to the program. When you forget to account for an outlier or edge case, a program can fail
or produce incorrect results. For example, you may have created a program that accepts users' dates
of birth but does not account for characters or negative numbers an end-user may enter incorrectly.
Here, the program may either halt its execution or crash.
6. Programming tools
Integrated development environments (IDEs) are applications that allow programmers to write,
compile, and execute code. IDEs provide a central interface that contains tools which facilitate
code completion, code compilation, debugging, and syntax highlighting. Some IDEs also allow
you to add plugins, enabling you to navigate the framework codebase and add your custom classes
and features. You can use IDEs for:

Writing code: You can use IDEs to write and edit program code to complete a set of tasks.
Compiling code: IDEs compile code by translating human-readable code to a format that is
understandable by the computer.
Debugging code: IDEs help you detect errors in a code and make fixes.
Monitoring resources: You can monitor various parameters such as disk space, resource
consumption, memory usage, free space on the disk, and cache memory, which help you optimize
your code to run faster and more efficiently.
Building automation tools: Some IDEs also provide automated tools for development tasks.

Syntax in Computer Programming


Syntax refers to the rules that define the structure of a language. Syntax in computer programming
means the rules that control the structure of the symbols, punctuation, and words of a programming
language. Without syntax, the meaning or semantics of a language is nearly impossible to
understand. If the syntax of a language is not followed, the code will not be understood by a
compiler or interpreter.
Compilers convert programming languages like Java or C++ into binary code that computers can
understand. If the syntax is incorrect, the code will not compile.
Interpreters execute programming languages such as JavaScript or Python at runtime. The
incorrect syntax will cause the code to fail. That’s why it is crucial that a programmer pays close
attention to a language’s syntax. No programmer likes to get a syntax error.

Basic Syntax
Basic syntax represents the fundamental rules of a programming language. Without these rules, it
is impossible to write functioning code. Every language has its own set of rules that make up its
basic syntax. Naming conventions are a primary component of basic syntax conventions and vary
by language.
• Case Sensitive: Java, C++, and Python are examples of languages that are case-sensitive.
Identifiers such as world and World have different meanings in these languages. Languages such as
Basic and SQL are insensitive, meaning world and World have the same meaning.
• Class Names: Java requires the first letter of each word in class names be upper case. For
example, class FirstJavaClass. Languages such as C or C++ use an underscore to separate words.
In C, the class name would be first_java_class.
• Program Filenames: The name of a Java program file must match the class name with the
extension ‘*.java” added to the name. For example, FirstJavaClass.java would be the name of the
program file for the class FirstJavaClass. C and C++ files require a “*.c” or “*.cpp” extension but
have no other stipulations.

Functions are the basic building blocks of any programming language. A function is a set of
statements enclosed within curly brackets ({}) that take inputs, do the computation, and provide the
resultant output. You can call a function multiple times, thereby allowing reusability and
modularity in programming language. It means that instead of writing the same code again and
again for different arguments, you can simply enclose the code and make it a function and then call
it multiple times by merely passing the various arguments.

Why Do We Need Functions in Programming Language?


6
We need functions in programming languages due to the numerous advantages they provide to the
developer. Some of the key benefits of using functions are:
• Enables reusability and reduces redundancy
• Makes a code modular
• Provides abstraction functionality
• The program becomes easy to understand and manage
• Breaks an extensive program into smaller and simpler pieces.

Basic Syntax of Functions


The basic syntax of functions in programming is:
return_type function_name (arg1, arg2… argn)
{
Body of the function //Statements to be processed
}
In the above syntax:
return_type: Here, we declare the data type of the value returned by functions. However, not all
functions return a value. In such cases, the keyword void indicates to the compiler that the function
will not return any value.
function_name: This is the function’s name that helps the compiler identify it whenever we call it.
arg1, arg2 ...argn: It is the argument or parameter list that contains all the parameters to be passed
into the function. The list defines the data type, sequence, and the number of parameters to be
passed to the function. A function may or may not require parameters. Hence, the parameter list is
optional.
Body: The function’s body contains all the statements to be processed and executed whenever the
function is called.

Character set
A "character set" is a mapping of characters to their identifying code values. The character set most
commonly used in computers today is Unicode, a global standard for character encoding.
Internally, Windows applications use the UTF-16 implementation of Unicode. In UTF-16, most
characters are identified by two-byte codes. The less commonly used supplementary characters are
each represented by a surrogate pair, which is a pair of two-byte codes.
Use of Character Set in programming language
Just like we use a set of various words, numbers, statements, etc., in any language for
communication, the programming language also consists of a set of various different types of
characters. They include digits, alphabets, special symbols, etc. The C language provides support
for about 256 characters.
Types of Characters
The programming language provides support for the following types of characters. In other words,
these are the valid characters that we can use in the programming language:
1.) Digits
2.) Alphabets
3.) Special Characters
Alphabets
The programming language provides support for all the alphabets that we use in the English
language. Thus, in simpler words, a program would easily support a total of 52 different
characters- 26 uppercase and 26 lowercase.
Digits
The programming language provides the support for all the digits that help in constructing/
supporting the numeric values or expressions in a program. These range from 0 to 9, and also help
7
in defining an identifier. Thus, the language supports a total of 10 digits for constructing the
numeric values or expressions in any program.
Special Characters
We use some special characters in the language for some special purposes, such as logical
operations, mathematical operations, checking of conditions, backspaces, white spaces, etc.
We can also use these characters for defining the identifiers in a much better way. For instance, we
use underscores for constructing a longer name for a variable, etc.

Type of Description Characters


Character
Lowercase a to z a, b, c, d, e, f, g, h, i, j, k, l, m, n,
Alphabets o, p, q, r, s, t, u, v, w, x, y, z
Uppercase A to Z A, B, C, D, E, F, G, H, I, J, K, L,
Alphabets M, N, O, P, Q, R, S, T, U, V, W,
X, Y, Z
Digits 0 to 9 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special – `~@!$#^*%&()[]{}<>
Characters +=_–|/\;:‘“,.?
White Spaces – Blank Spaces, Carriage Return,
Tab, New Line

ASCII Values
All the character sets used in the C language have their equivalent ASCII value. The ASCII value
stands for American Standard Code for Information Interchange value. It consists of less than
256 characters, and we can represent these in 8 bits or even less.

65 A 97 a
66 B 98 b
67 C 99 c
68 D 100 d
69 E 101 e
70 F 102 f
Keywords
Keywords are predefined; reserved words used in programming that have special meanings to the
compiler. Keywords are part of the syntax and they cannot be used as an identifier. For example:

int money;
Here, int is a keyword that indicates money is a variable of type int (integer).
# As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of all
keywords allowed in ANSI C.
case enum char void continue for return union do if static while
Identifiers

Identifier refers to name given to entities such as variables, functions, structures etc.
Identifiers must be unique. They are created to give a unique name to an entity to identify it during
the execution of the program.

For example:
8
int money;
double accountBalance;
Here, money and accountBalance are identifiers.
#Also remember, identifier names must be different from keywords. You cannot use int as an
identifier because int is a keyword.

Variables and Constant


A constant is a named data item with a predefined value, while a variable is a named data item
whose value can change during the course of program execution. Variables can be either global or
local. All data is represented as one of three basic data types:
Int - Integer data type (+ - followed by 1 or more digits 0–9).
Real - Floating point (+- followed by zero or more digits 0–9). Decimal point followed by 1 or
more digits 0–9. Note that all numbers are stored internally as Float.
String - Any valid Unicode string enclosed within quotes.
Constants
A constant is a named data item with a predefined value. You cannot change the value assigned to
a predefined constant. The predefined constants are:
NULL An empty reference, similar to an empty pointer. Note that this is not the same as a null
string "".
TRUE Equivalent to the number 1.
FALSE Equivalent to the number 0.
Variable definition
A variable is a named data item whose value can change during the course of program execution.
A variable name must follow the naming convention of an Identifier (alphabetic character, numeric
character, and the underscore.) When more than one variable is defined on a single declaration, the
name must be separated by commas. Each variable declaration must be terminated with a semi-
colon. Variable names cannot be the same as a reserved word.
Global and local variables
Variables can be either global or local. A variable is global unless it is declared within a function
definition. Global variables are visible and available to all statements in a script. Local variables
are only visible and available within the function where they were defined. Although variable
names and identifiers must be unique, it is valid to declare a local variable that has the same name
as global, or the same name as a local variable defined in another function. Parameter names in a
function definition are considered to be local variables. Data passed to a function is by value. A
global variable passed to a function will not be changed by the function.
Data Types
In software programming, data type refers to the type of value a variable has and what type of
mathematical, relational or logical operations can be applied without causing an error.

9
Data Type Represents Examples
Integer whole numbers -5, 0, 123
floating point fractional numbers -87.5, 0.0, 3.14159
(real)
String A sequence of characters "Hello world!"

Boolean logical true or false true, false


Nothing no data null

Comments
In computer programming, a comment is a programmer-readable explanation or annotation in the
source code of a computer program. They are added with the purpose of making the source code
easier for humans to understand, and are generally ignored by compilers and interpreters.
Comments are generally formatted as either block comments (also called prologue comments or
stream comments) or line comments (also called inline comments).
Block comments delimit a region of source code which may span multiple lines or a part of a
single line. This region is specified with a start delimiter and an end delimiter.
Line comments start with a comment delimiter and continue until the end of the line, or in some
cases, start at a specific column (character line offset) in the source code, and continue until the end
of the line.
Some programming languages employ both block and line comments with different comment
delimiters. For example, C++ has block comments delimited by /* and */ that can span multiple
lines and line comments delimited by //.

C Single Line Comment Example

The Single Line comments start with two forward slashes (//).
#include<stdio.h>
int main ()
{
// Printing Hello World Message as Output
printf (" Hello World! \n");
return 0;
}

Multi-Line Comments Example


10
The Multi-Line Comments placed in between /*……… */. Use this Slash and asterisk to write a
multi-line.
#include<stdio.h>
int main ()
{
/* Print
Message
as an Output */

printf (" Welcome to Tutorial Gateway \n");


return 0;
}

UNIT II
11
Operators
Operators can be defined as the symbols that help us to perform specific mathematical, relational,
bitwise, conditional, or logical computations on operands. In other words, we can say that an
operator operates the operands. For example, ‘+’ is an operator used for addition, as shown below:
c = a + b;
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are operands. The addition
operator tells the compiler to add both of the operands ‘a’ and ‘b’. The functionality of the
programming language is incomplete without the use of operators.
Types of Operators
As per the programming language, there are many built-in operators and can be classified into 6
types:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators
The above operators have been discussed in detail:
1. Arithmetic Operators

These operators are used to perform arithmetic/mathematical operations on operands. Examples:


(+, -, *, /, %,++,–). Arithmetic operators are of two types:
a) Unary Operators:
Operators that operate or work with a single operand are unary operators. For example: Increment
(++) and Decrement (–) Operators.
int val = 5;
cout<<++val; // 6

b) Binary Operators:
Operators that operate or work with two operands are binary operators. For example: Addition (+),
Subtraction (-), Multiplication (*), Division (/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9

2. Relational Operators

These are used for the comparison of the values of two operands. For example, checking if one
operand is equal to the other operand or not, whether an operand is greater than the other operand
or not, etc. Some of the relational operators are (==, >=, <=).
int a = 3;
int b = 5;
cout<< (a < b); // operator to check if a is smaller than b
3. Logical Operator
Logical Operators are used to combining two or more conditions/constraints or to complement the
evaluation of the original condition in consideration. The result of the operation of a logical
operator is a Boolean value either true or false.

For example, the logical AND represented as the ‘&&’ operator, returns true when both the
conditions under consideration are satisfied. Otherwise, it returns false. Therefore, a && b returns
12
true when both a and b are true (i.e. non-zero).

Logical AND (&&)


cout<< ((4! = 5) && (4 < 5)); // true
Logical OR (||)
The result of Logical OR will be true if any one operand is true.
E.g. if (10 > 15 || 5 < 10) Result will be 1 (True)
Logical NOT (!)
Logical NOT (!) is used to reverse the value of the expression.
E.g. if (! (5 > 10)) Result will be 1 (TRUE)

4. Assignment Operator
Assignment operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment operator is a value.
The value on the right side must be of the same data type as the variable on the left side otherwise
the compiler will raise an error.
Different types of assignment operators are shown below:

a) “=”
This is the simplest assignment operator. This operator is used to assign the value on the right to
the variable on the left.
Example:
a = 10;
b = 20;
ch = 'y';

b) “+=”
This operator is the combination of the ‘+’ and ‘=’ operators. This operator first adds the current
value of the variable on left to the value on the right and then assigns the result to the variable on
the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.

c) “-=”
This operator is a combination of ‘-‘and ‘=’ operators. This operator first subtracts the value on the right
from the current value of the variable on left and then assigns the result to the variable on the left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.

d) “*=”
This operator is a combination of the ‘*’ and ‘=’ operators. This operator first multiplies the current value
of the variable on left to the value on the right and then assigns the result to the variable on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30.

e) “/=”
This operator is a combination of the ‘/’ and ‘=’ operators. This operator first divides the current value of
the variable on left by the value on the right and then assigns the result to the variable on the left.
13
Example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.

5. Conditional or Ternary Operator


A ternary operator is one which contains three operands. The only ternary operator available in C
language is conditional operator pair “? “. It is of the form
exp1? exp2: exp3;
This operator works as follows. Exp1 is evaluated first. If the result is true then exp2 is
executed otherwise exp3 is executed.

Example 1:
a = 10;
b = 15;
x = (a > b ? a : b);
In this expression value of b will be assigned to x.

6. Bitwise operators
Bitwise operators are used to manipulate of data at bit level. These operators are used for
testing the bits, or shifting them right or left. Bitwise operators may not be applied to float
or double data type.

Operator Meaning
& Bitwise Logical AND
| Bitwise Logical OR
^ Bitwise Logical XOR
>> Right Shift
<< Left Shift
~ One’s Complement

14
Output:N=14

15
16
Operator Precedence and Associativity

The concept of operator precedence and associativity in programming languages helps in


determining which operators will be given priority when there are multiple operators in the
expression. It is very common to have multiple operators in programming language and the
compiler first evaluates the operator with higher precedence. It helps to maintain the ambiguity of
the expression and helps us in avoiding unnecessary use of parenthesis.
The following tables list the C operator precedence from highest to lowest and the associativity for
each of the operator:

17
Example of Operator Precedence

Let’s try to evaluate the following expression,


10 + 20 * 30
The expression contains two operators, + (plus), and * (multiply). According to the given table, the
* has higher precedence than + so, the first evaluation will be
10 + (20 * 30)
After evaluating the higher precedence operator, the expression is
10 + 600
Now, the + operator will be evaluated.
610

Operator Associativity
Operator associativity is used when two operators of the same precedence appear in an expression.
Associativity can be either from Left to Right or Right to Left.

Example of Operator Associativity

Let’s evaluate the following expression,


100 / 5 % 2
Both / (division) and % (Modulus) operators have the same precedence, so the order of evaluation
will be decided by associativity.
According to the given table, the associativity of the multiplicative operators is from Left to Right.
So,
(100 / 5) % 2
After evaluation, the expression will be
20 % 2
Now, the % operator will be evaluated=0

Expressions

An expression is a combination of variables, constants, and operators arranged according


to syntax of the language. Some examples of expressions are:
e.g. c = (m + n) * (a - b);
Expression is evaluated by using assignment statement.
Such a statement is of the form
Variable = expression;
The expression is evaluated first, and then the value is assigned to the variable left hand side.
But all the relevant variables must be assigned the values before evaluation of the expression.
18
Statements and its types
C programs are collection of Statements, statements is an executable part of the program it will do
some action. In general all arithmetic actions and logical actions are falls under Statements. Types
of statements:
1. Expression Statement
2. Compound Statement.
3. Selection Statement.
4. Iterative Statement.
5. Jump Statement.
Expression Statement:
It is combination of variables, constants, operators, Function Calls and followed by a semicolon.
Expression can be any operation like Arithmetic operation or Logical Operation.
Few Examples for expression Statements
X = Y + 10;
a = 10 + 20 * 30;

Compound Statement:
Compound statement is combination of several expression statements. Compound Statement is
enclosed within the Braces { }.
Compound statement is also called as Block Statement.
Example for Compound Statement
{
int a=10, b=20, c;
c = a + b;
printf (“value of C is: %d n”, c);
}

Selection Statement:
Selection Statements are used in decisions making situations. Here are the few examples of
Selection statements:
• if
• if…else
• switch...case

Iterative Statement:
These are also called as Loops. If we want to execute a part of program many times we will use
loops. Basic loops in C language.
• for loop
• while loop
• do-while loop

Jump Statement:
These are Unconditional statements. Jump statements are useful for transfer the control one part of
program to other part of program. Few Jump Statements in C:
• goto
• continue
• break
• return

19
UNIT III
Introduction to Problem-Solving

Computer programming
Designing and writing computer programs, or sequences of instructions to be executed by a
computer. A computer is able to perform useful tasks only by executing computer programs. A
programming language or a computer language is a specialized language for expressing the
instructions in a computer program.
Problem Definition

It is the first and most important step in determining the information needs.
Information needs of software can be determined by-
1) Studying the existing System
2) Using questionnaires
3) Suggesting interpretation of information needs with users
This phase in the product life cycle encompasses two different activities: Concept Development
and Requirements Identification. In Concept Development, we gather and refine ideas and set
cohesive product goals. Requirements Identification then further clarifies the goals by specifying
the needs and functionality of the product.
Problem solving

In this stage, the programmer gains a full understanding of the problem that the computer program
under development is supposed to solve, and devises a step-by step procedure (an algorithm) that,
when followed, will solve the problem.
Problems are the undesirable situations that prevent any software from fully achieving its
objectives. Problem dearly defined in terms of goals and objectives helps largely in problem
solving. Steps involved in problem solving methodology are shown in the figure.
Some problem-solving techniques
• Trial-and-error (also called guess and check)
• Brainstorming
• Divide and conquer
1. Trial and Error
Some complex problems can be solved by a technique that is called trial and error.
Trial and error is typically good for problems where you have multiple chances to get the correct
solution. However, this is not a good technique for problems that don’t give you multiple chances
to find a solution.
An example of situations where you wouldn’t want to use trial and error are diffusing a bomb or
performing an operation on a patient. In these situations, making an error can lead to disaster.
Trial and error is used best when it is applied to situations that give your large amounts of time and
safety to come up with a solution.
In addition to this, trial and error is also a great way to gain knowledge. Basically, a person that
uses the trial and error method will try to a method to see if it is a good solution. If it is not a good
solution, they try another option. If the method works, the person using it has acquired the correct
solution to a problem.

2. Brainstorming
Brainstorming as a technique was first introduced by Alex Osborne in the 1930s. It is a method
used in groups in order to support creative problem-solving, the generation of new ideas and
greater acceptance of proposed solutions.
Brainstorming works by focusing on a problem, and then intentionally coming up with as many
solutions as possible and by pushing the ideas as far as possible. One of the reasons it is so
20
effective is that the brainstormers not only come up with new ideas in a session, but also inspire
from associations with other people's ideas by developing and refining them.
Benefits of brainstorming
The benefits of a well-organized brainstorming session are numerous. They include:
(a) Solutions can be found rapidly and economically;
(b) Results and ways of problem-solving those are new and unexpected
(c) A wider picture of the problem or issue can be obtained;
(d) The atmosphere within the team is more open;
(e) The team shares responsibility for the problem;
(f) Responsibility for the outcome is shared;
(g)The implementation process is facilitated by the fact that staff shared in the decision-making
process.
3. Divide-and-conquer
Divide-and-conquer is a top-down technique for designing algorithms that consists of dividing the
problem into smaller sub problems hoping that the solutions of the sub problems are easier to find
and then composing the partial solutions into the solution of the original problem.
A divide and conquer algorithm works by recursively breaking down a problem into two or more
sub-problems of the same or related type, until these become simple enough to be solved directly.
Divide-and-conquer paradigm consists of following major phases:
•Breaking the problem into several sub-problems that are similar to the original problem but
smaller in size, Solve the sub-problem recursively (successively and independently), and then
•Combine these solutions to sub problems to create a solution to the original problem.
Problem Solving Skills in Programming
Solving a question that is related to computers is more complicated than finding the solutions for
other questions. It requires excellent knowledge and much thinking power. Problem solving in
programming skills is much needed for a person and holds a major advantage. For every question,
there are specific steps to be followed to get a perfect solution. By using those steps, it is possible
to find a solution quickly.

Steps Involved in Problem Solving


Before being ready to solve a problem, there are some steps and procedures to be followed to find
the solution. Basically, they are divided into four categories:
•Analyzing the problem
•Developing the algorithm
•Coding
•Testing and debugging
Analysing the Problem
Every problem has a perfect solution; before we are ready to solve a problem, we must look over
the question and understand it. When we know the question, it is easy to find the solution for it. If
we are not ready with what we have to solve, then we end up with the question and cannot find the
answer as expected. By analysing it, we can figure out the outputs and inputs to be carried out.
Thus, when we analyse and are ready with the list, it is easy and helps us find the solution easily.

Developing the Algorithm


It is required to decide a solution before writing a program. The procedure of representing the
solution in a natural language called an algorithm. We must design, develop and decide the final
approach after a number of trials and errors, before actually writing the final code on an algorithm
before we write the code. It captures and refines all the aspects of the desired solution.

Coding
Once we finalise the algorithm, we must convert the decided algorithm into a code or program
using a dedicated programming language that is understandable by the computer to find a desired
solution. In this stage, a wide variety of programming languages are used to convert the algorithm
into code.
21
Testing and Debugging
The designed and developed program undergoes several rigorous tests based on various real-time
parameters and the program undergoes various levels of simulations. It must meet the user's
requirements, which have to respond with the required time. It should generate all expected outputs
to all the possible inputs. The program should also undergo bug fixing and all possible exception
handling. If it fails to show the possible results, it should be checked for logical errors.
Industries follow some testing methods like system testing, component testing and acceptance
testing while developing complex applications. The errors identified while testing are debugged or
rectified and tested again until all errors are removed from the program.

Benefits
•Problem solving in programming skills helps to gain more knowledge over coding and
programming, which is a major benefit.
•These problem solving skills also help to develop more skills in a person and build a promising
career.
•These skills also help to find the solutions for critical and complex problems in a perfect way.
•Learning and developing problem solving in programming helps in building a good foundation.

ALGORITHMS-
A step-by-step procedure to solve the given problem is known as Algorithm.
The essential properties of Algorithm are:
•It should be simple.
•It should be clear with no ambiguity.
•It should lead to a unique solution of the problem.
•It should involve a finite number of steps to arrive at a solution.
•It should have the capability to handle some-unexpected situations.
For example if a student wants to purchase a pen, he has to follow the following steps:

These numbered steps are known as Algorithm.

FLOWCHARTS
• The graphical or visual representation of algorithm is called as flow chart.
• The flow charts are easier to understand the flow of the solution.
• Flow charts are drawn with the standard symbols accepted worldwide.
• Each standard flow chart symbol represents on action to be performed such as Start or Stop, input
operations Read or Write, decision making etc.

22
23
Advantages of Flowchart –

1- Conveys Better Meaning –


Since a flowchart is a pictorial representation of a program, it is easier for a programmer to
understand and explain the logic of the program to other programmers.
2- Analyses the problem effectively –
Flow chart helps the programmers to analyze the problem in detail by breaking the flow chart into
detailed parts.
3- Effective Coding-
It is very easy for the programmers to write the program, because flow chart will give a clear idea
of the steps involved.
4- Systematic Debugging-
Even after taking the full care in program design, some errors may remain in the program because
the programmer might have never thought of a particular case. Using a flow chart can reduce this
type of errors. It also enables easy detection of errors.

Pseudocode
Pseudocode is an informal high-level description of the operating principle of a computer program
or other algorithm. Pseudocode (pronounced SOO-doh-kohd) is a detailed yet readable description
of what a computer program or algorithm must do, expressed in a formally-styled natural language
rather than in a programming language. Pseudocode is sometimes used as a detailed step in the
process of developing a program. It allows designers or lead programmers to express the design in
great detail and provides programmers a detailed template for the next step of writing code in a
specific programming language.
Three basic constructs for flow of control are sufficient to implement any "proper" algorithm.
•SEQUENCE is a linear progression where one task is performed sequentially after another.
•WHILE is a loop (repetition) with a simple conditional test at its beginning.
•IF-THEN-ELSE is a decision (selection) in which a choice is made between two
alternative courses of action.

24
SEQUENCE
Sequential control is indicated by writing one action after another, each action on a line by itself,
and all actions aligned with the same indent. The actions are performed in the sequence (top to
bottom) that they are written.
Example-
READ height of rectangle
READ width of rectangle
COMPUTE area as height times width

IF-THEN-ELSE
Binary choice on a given Boolean condition is indicated by the use of four keywords: IF, THEN,
ELSE, and ENDIF. The general form is:
IF condition THEN
sequence 1
ELSE
sequence 2
ENDIF
The ELSE keyword and "sequence 2" are optional. If the condition is true, sequence 1 is
performed, otherwise sequence 2 is performed.
Example
IF HoursWorked > NormalMax THEN
Display overtime message
ELSE
Display regular time message
ENDIF

WHILE
The WHILE construct is used to specify a loop with a test at the top. The beginning and ending of
the loop are indicated by two keywords WHILE and ENDWHILE.
The general form is:
WHILE condition
sequence
ENDWHILE
The loop is entered only if the condition is true. The "sequence" is performed for each iteration. At
the conclusion of each iteration, the condition is evaluated and the loop continues as long as the
condition is true.
Example -
get a number
set our initial count to 0
while our number is greater than 1
divide the number by 2
increase our count by 1
end

25
Time Complexity

Time complexity is the number of operations an algorithm performs to complete its task
(considering that each operation takes the same amount of time). The algorithm that performs the
task in the smallest number of operations is considered the most efficient one in terms of the time
complexity.

Big O notation
Big O notation is used in Computer Science to describe the performance or complexity of an
algorithm. Big O specifically describes the worst-case scenario, and can be used to describe the
execution time required or the space used (e.g. in memory or on disk) by an algorithm.
Below are some common orders of growth along with descriptions and examples where possible.

O(1)

O(1) describes an algorithm that will always execute in the same time (or space) regardless of the
size of the input data set.
void func()
{
Print “Hello!”
}

O(N)

O(N) describes an algorithm whose performance will grow linearly and in direct proportion to the
size of the input data set.
The example below also demonstrates how Big O favors the worst-case performance scenario; a
matching string could be found during any iteration of the for loop and the function would return
early, but Big O notation will always assume the upper limit where the algorithm will perform the
maximum number of iterations.

bool ContainsValue(char[] elements, string value)


{
foreach (var x in elements)
{
if (x == value) return true;
}
return false;
}

O(N2)

O(N2) represents an algorithm whose performance is directly proportional to the square of the size
of the input data set. This is common with algorithms that involve nested iterations over the
dataset. Deeper nested iterations will result in O(N3), O(N4) etc.

bool ContainsDuplicates(IList<string> elements)


{
for (var outer = 0; outer < elements.Count; outer++)
{
for (var inner = 0; inner < elements.Count; inner++)
{
// Don't compare with self
if (outer == inner) continue;
if (elements[outer] == elements[inner]) return true;
}}
return false;
26
}

O(2N)
O(2N) denotes an algorithm whose growth doubles with each addition to the input data set. The
growth curve of an O(2N) function is exponential - starting off very shallow, and then rising
meteorically. An example of an O(2N) function is the recursive calculation of Fibonacci numbers:

int Fibonacci(int number)


{
if (number <= 1)
return number;
return Fibonacci(number - 2) + Fibonacci(number - 1);
}

Logarithm

The most common attributes of logarithmic running-time function are that:


•the choice of the next element on which to perform some action is one of several possibilities, and
only one will need to be chosen or the elements on which the action is performed are digits of n.

•O(log n): Given a person's name, find the phone number by picking a random point about halfway
through the part of the book you haven't searched yet, then checking to see whether the person's
name is at that point. Then repeat the process about halfway through the part of the book where the
person's name lies. (This is a binary search for a person's name.

•O(n): Find all people whose phone numbers contain the digit "5".

•O(n): Given a phone number, find the person or business with that number.

•O(n log n): There was a mix-up at the printer's office, and our phone book had all its pages
inserted in a random order. Fix the ordering so that it's correct by looking at the first name on each
page and then putting that page in the appropriate spot in a new, empty phone book.
Asymptotic Notations

Asymptotic notations are the mathematical notations used to describe the running time of an
algorithm when the input tends towards a particular value or a limiting value.
For example: In bubble sort, when the input array is already sorted, the time taken by the algorithm
is linear i.e. the best case.
But, when the input array is in reverse condition, the algorithm takes the maximum time
(quadratic) to sort the elements i.e. the worst case.
When the input array is neither sorted nor in reverse order, then it takes the average time. These
durations are denoted using asymptotic notations. There are mainly three asymptotic notations:

• Big-O notation
• Omega notation
• Theta notation

1- Big-O Notation (O-notation)


Big-O notation represents the upper bound of the running time of an algorithm. Thus, it gives the
worst-case complexity of an algorithm.
27
O(g(n)) = { f(n): there exist positive constants c and n0 such that 0 ≤ f(n) ≤ cg(n) for all n ≥ n0 }

The above expression can be described as a function f(n) belongs to the set O(g(n)) if there exists a
positive constant c such that it lies between 0 and cg(n), for sufficiently large n.

For any value of n, the running time of an algorithm does not cross the time provided by O(g(n)).
Since it gives the worst-case running time of an algorithm, it is widely used to analyze an
algorithm as we are always interested in the worst-case scenario.
2- Omega Notation (Ω-notation)

Omega notation represents the lower bound of the running time of an algorithm. Thus, it provides
the best case complexity of an algorithm.

Ω(g(n)) = { f(n): there exist positive constants c and n0 such that 0 ≤ cg(n) ≤ f(n) for all n ≥ n0 }

The above expression can be described as a function f(n) belongs to the set Ω(g(n)) if there exists a
positive constant c such that it lies above cg(n), for sufficiently large n. For any value of n, the
minimum time required by the algorithm is given by Omega Ω(g(n)).
3- Theta Notation (Θ-notation)

Theta notation encloses the function from above and below. Since it represents the upper and the
28
lower bound of the running time of an algorithm, it is used for analyzing the average-case
complexity of an algorithm.

For a function g(n), Θ(g(n)) is given by the relation:


Θ(g(n)) = { f(n): there exist positive constants c1, c2 and n0 such that 0 ≤ c1g(n) ≤ f(n) ≤ c2g(n) for
all n ≥ n0 }

The above expression can be described as a function f (n) belongs to the set Θ(g(n)) if there exist
positive constants c1 and c2 such that it can be sandwiched between c1g(n) and c2g(n), for
sufficiently large n.
If a function f(n) lies anywhere in between c1g(n) and c2g(n) for all n ≥ n0, then f(n) is said to be
asymptotically tight bound.

Definition of Space Complexity

Space complexity is nothing but the amount of memory space that an algorithm or a problem takes
during the execution of that particular problem/algo.
The space complexity is not only calculated by the space used by the variables in the problem/algo
it also includes and considers the space for input values with it.
There is a sort of confusion among people between the space complexity and the auxiliary space.
So let’s be clear about that, so auxiliary space is nothing but the space required by an
algorithm/problem during the execution of that algorithm/problem and it is not equal to the space
complexity because space complexity includes space for input values along with it also.
So we can say that space complexity is the combination or sum up of the auxiliary space and the
space used by input values.

Space Complexity = Auxiliary Space + Space used for input values

Let's take an example:

#Sum of N Natural Number


29
int sum (int n)
{
int i, sum=0;
for (i=n; i>=1; i--)
sum=sum+i
return sum;
}

So in the above example input value is 'n' that is constant which will take the space of O(1). Now
what about auxiliary space, so it is also O(1) because 'i' and 'sum' are also constants.
Hence total space complexity is O(1).

UNIT V

30
SIMPLE ARITHMETIC PROBLEMS

Determine whether the number is Even or Odd –


31
32
33
34
35
36
UNIT 5
Functions
A function in C is a set of statements that when called perform some specific task. It is the basic building block
of a C program that provides modularity and code reusability. The programming statements of a function are
enclosed within { } braces, having certain meanings and performing certain operations. They are also called
subroutines or procedures in other languages.
Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
 Function Declaration- In a function declaration, we must provide the function name, its return type,
and the number and type of its parameters. A function declaration tells the compiler that there is a
function with the given name defined somewhere else in the program.
 Function Definition- The function definition consists of actual statements which are executed when
the function is called (i.e. when the program control comes to the function).
A C function is generally defined and declared in a single step because the function definition always
starts with the function declaration so we do not need to declare it explicitly. The below example
serves as both a function definition and a declaration.
 Function Calls- A function call is a statement that instructs the compiler to execute the function. We
use the function name and parameters in the function call.
In the below example, the first sum function is called and 10,30 are passed to the sum function. After
the function call sum of a and b is returned and control is also returned back to the main function of
the program.
How Does C Function Work?
Working of the C function can be broken into the following steps as mentioned below:

Declaring a function: Declaring a function is a step where we declare a function. Here we define the return
types and parameters of the function.
Defining a function:
Calling the function: Calling the function is a step where we call the function by passing the arguments in the
function.
Executing the function: Executing the function is a step where we can run all the statements inside the
function to get the final result.
Returning a value: Returning a value is the step where the calculated value after the execution of the function
is returned. Exiting the function is the final step where all the allocated memory to the variables, functions,
etc is destroyed before giving full control to the main function.

Types of Functions
There are two types of functions in C:
1. Library Functions- A library function is also referred to as a “built-in function”. A compiler package
already exists that contains these functions, each of which has a specific meaning and is included in
the package. Built-in functions have the advantage of being directly usable without being defined,
whereas user-defined functions must be declared and defined before being used. E.g – pow(), sqrt(),
strcmp(), strcpy().
2. User Defined Functions- Functions that the programmer creates are known as User-Defined
functions or “tailor-made functions”. User-defined functions can be improved and modified according
to the need of the programmer. Whenever we write a function that is case-specific and is not defined
in any header file, we need to declare and define our own functions according to the syntax.
Passing Parameters to functions –
The data passed when the function is being invoked is known as the Actual parameters. In the below
program, 10 and 30 are known as actual parameters. Formal Parameters are the variable and the data type
as mentioned in the function declaration. In the below program, a and b are known as formal parameters.
We can pass arguments to the C function in two ways:

37
 Pass by Value
 Pass by Reference
1. Pass by Value
Parameter passing in this method copies values from actual parameters into formal function parameters.
As a result, any changes made inside the functions do not reflect in the caller’s parameters.
2. Pass by Reference
The caller’s actual parameters and the function’s actual parameters refer to the same locations, so any
changes made inside the function are reflected in the caller’s actual parameters.

Difference between the Call by Value and Call by Reference in C


The following table lists the differences between the call-by-value and call-by-reference methods of
parameter passing.

Call By Value Call By Reference

While calling a function, instead of passing the


While calling a function, we pass the
values of variables, we pass the address of
values of variables to it. Such functions
variables(location of variables) to the function
are known as “Call By Values”.
known as “Call By References.

In this method, the value of each variable


In this method, the address of actual variables
in the calling function is copied into
in the calling function is copied into the
corresponding dummy variables of the
dummy variables of the called function.
called function.

With this method, the changes made to


With this method, using addresses we would
the dummy variables in the called
have access to the actual variables and hence
function have no effect on the values of
we would be able to manipulate them.
actual variables in the calling function.

In call-by-values, we cannot alter the


In call by reference, we can alter the values of
values of actual variables through
variables through function calls.
function calls.

Values of variables are passed by the Pointer variables are necessary to define to
Simple technique. store the address values of variables.

This method is preferred when we have


This method is preferred when we have to pass
to pass some small values that should not
a large amount of data to the function.
change.

Call by value is considered safer as Call by reference is risky as it allows direct


original data is preserved modification in original data

Scope Rules in C -
The scope of a variable in C is the block or the region in the program where a variable is declared, defined,
and used. Outside this region, we cannot access the variable and it is treated as an undeclared identifier.
38
 The scope is the area under which a variable is visible.
 The scope of an identifier is the part of the program where the identifier may directly be accessible.
 We can only refer to a variable in its scope.

Types of Scope Rules in C


C scope rules can be covered under the following two categories:

 Global Scope
 Local Scope
Let’s discuss each scope rule with examples.

1. Global Scope in C
The global scope refers to the region outside any block or function.
The variables declared in the global scope are called global variables.
Global variables are visible in every part of the program.
Global is also called File Scope as the scope of an identifier starts at the beginning of the file and ends at
the end of the file.
2. Local Scope in C
The local scope refers to the region inside a block or a function. It is the space enclosed between the { }
braces.
The variables declared within the local scope are called local variables.
Local variables are visible in the block they declare in and other blocks nested inside it. Local scope is also
called Block scope . Local variables have internal linkage.

Storage Classes in C
Storage classes in C are used to determine the lifetime, visibility, memory location, and initial value
of a variable. There are four types of storage classes in C
1) Automatic-
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they are defined.
o The scope of the automatic variables is limited to the block in which they are defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by defau
2) External-

o The external storage class is used to tell the compiler that the variable defined as extern is declared
with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only declaration and intended to
specify that the variable is declared elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the external variable
within any block or method.
o An external variable can be declared many times but can be initialized at only once.
o If a variable is declared as external then the compiler searches for that variable to be initialized
somewhere in the program which may be extern or static. If it is not, then the compiler will show an
error.
39
3) Static-
o The variables defined as static specifier can hold their value between the multiple function calls.
o Static local variables are visible only to the function or the block in which they are defined.
o A same static variable can be declared many times but can be assigned at only one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has declared.
o The keyword used to define static variable is static.

4) Register-
 The variables defined as the register is allocated the memory into the CPU registers
depending upon the size of the memory remaining in the CPU.
 We can not dereference the register variables, i.e., we can not use &operator for the
register variable.
 The access time of the register variables is faster than the automatic variables.
 The initial default value of the register local variables is 0.
 The register keyword is used for the variable which should be stored in the CPU
register. However, it is compiler?s choice whether or not; the variables can be stored
in the register.
 We can store pointers into the register, i.e., a register can store the address of a
variable.
 Static variables can not be stored into the register since we can not use more than
one storage specifier for the same variable.
Recursion - In C, recursion is used to solve complex problems by breaking them down into simpler sub-
problems. We can solve large numbers of problems using recursion in C. For example, factorial of a number,
generating Fibonacci series, generating subsets, etc.
// C program to find the factorail using tail recursion
#include <stdio.h>
int factorialTail(int n)
{
// Base case
if (n == 1 || n == 0) {
return 1;
}
else {
// Tail recursive call
return n * factorialTail(n - 1);
}
}
int main()
{
int n = 5;
int fact1 = factorialTail(n);
printf("Resursive Factorial of %d: %d \n", n, fact1);
return 0;
}

40
UNIT -1
Very short Questions
1- What is the primary function of a compiler in C?
2- Name a building block of C programming.
3- What is the character set in C?
4- Give an example of a C token.
5- What symbol is used to start a single-line comment in C
Short Questions
1. Briefly describe the history of the C programming language.
2. Explain the structure of a C program.
3. What is a function in C, and why is it considered a building block?
4. What are C tokens, and list the different types?
5. Describe the role of variables in C programming.
Long Questions
1. Discuss the evolution of the C programming language and its impact on modern programming.
2. Explain the importance of functions in C programming with an example.
3. Describe the different data types available in C and their uses.
4. What are keywords in C, and why are they important?
5. How are comments used in C, and what are their benefits?
Unit -2
Very Short Questions
1. What operator is used for addition in C?
2. What is the purpose of the printf() function?
3. Define operator precedence.
4. What does the #include directive do?
5. Name a function used to read a single character from the console.
Short Questions
1. List the different types of operators in C.
2. Explain the concept of operator associativity with an example.
3. What is an expression in C?
4. Describe the use of the scanf() function.
5. What is a header file, and why is it important in C programming?
Long Questions
1. Discuss the various types of operators in C and provide examples of each.
2. Explain operator precedence and associativity and how they affect the evaluation of expressions in C.
3. Describe the different types of statements in C with examples.
4. Explain the role of preprocessor directives in C programming and provide examples.
5. Discuss the console-based I/O functions in C, including printf(), scanf(), getch(), getchar(), and
putchar().
Unit -3
Very Short Questions
1. What is the purpose of the if statement in C?
2. Which loop in C is guaranteed to execute at least once?
3. What keyword is used to exit a loop prematurely?
4. Define an algorithm.
5. What symbol is commonly used to denote the start or end of a flowchart?

41
Short Questions
1. Describe the use of the switch statement in C.
2. Explain the difference between while and do-while loops.
3. What is the role of the continue statement in loops?
4. List and briefly describe the steps in problem solving.
5. What are the main symbols used in flowcharts, and what do they represent?
Long Questions
1. Discuss the different decision-making structures in C with examples.
2. Explain the various loop control structures in C and provide examples of nested loops.
3. Describe the different problem-solving techniques and give an example of each.
4. Explain the characteristics of an algorithm and the importance of Big-Oh notation in evaluating time
complexity.
5. Provide a detailed explanation of how to create an algorithm and flowchart for a simple real-life
problem.
Unit -4
Very Short Questions
1. How do you check if a number is even in C?
2. What is the formula for the sum of the first n natural numbers?
3. What does the function to calculate the factorial of a number return for an input of 0?
4. What is the output of integer division 5 / 2 in C?
5. How can you swap two numbers in C without using a temporary variable?
Short Questions
1. Describe the steps to determine if a number is positive, negative, or zero.
2. Explain the algorithm to find the maximum of two numbers.
3. What is the process to generate the multiplication table for a given number n?
4. Write an algorithm to reverse the digits of an integer.
5. How do you check if a number is prime?
Long Questions
1. Write an algorithm and draw a flowchart to find the sum of the first n numbers.
2. Describe the algorithm to calculate the sine series for a given angle and draw its flowchart.
3. Explain the steps to generate Pascal's Triangle and provide the corresponding flowchart.
4. Discuss the algorithm to compute the greatest common divisor (GCD) of two numbers and illustrate
with a flowchart.
5. Write an algorithm and draw a flowchart to determine if a number is a perfect number.
Unit -5
Very Short Questions
1. What is a function prototype in C?
2. Define a recursive function.
3. What is the difference between call by value and call by reference?
4. Name the storage class that makes a variable accessible only within the file it is declared.
5. What is the default storage class for local variables in C?
Short Questions
1. Explain the difference between function declaration and function definition.
2. What are the basic types of functions in C?
3. Describe the scope of a local variable.
4. Explain parameter passing with an example of call by value.
5. What is the purpose of the static storage class?
42
Long Questions
1. Discuss the various types of functions in C with examples.
2. Explain the concept of recursion with an example and illustrate how it works with a flowchart.
3. Describe the different storage classes in C and their uses.
4. Explain call by reference with an example and discuss its advantages over call by value.
5. Write an algorithm and provide a flowchart for a function that calculates the factorial of a number
using recursion.

43

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy