You are on page 1of 53

What is a flow chart?

• A flowchart in computer algorithm is a graphical representation of the steps involved in solving a


computational problem.
• It uses different shapes to represent different types of steps, such as input, output, processing,
decision, and termination. Flowcharts are connected by arrows to show the flow of data and control
between the steps.
• Flowcharts are a useful tool for designing and analyzing algorithms because they provide a clear
and concise way to visualize the logic of the algorithm.
• They can also be used to communicate the algorithm to others, such as other programmers or non-
technical stakeholders.
Basic Symbols used in Flowchart Designs

• Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic
flow. A pause/halt is generally used in a program logic under some error
conditions. Terminal is the first and last symbols in the flowchart.
• Input/Output: A parallelogram denotes any function of
input/output type. Program instructions that take input from
input devices and display output on output devices are indicated
with parallelogram in a flowchart.
• Processing: A box represents arithmetic instructions. All
arithmetic processes such as adding, subtracting, multiplication
and division are indicated by action or process symbol.
• Decision Diamond symbol represents a decision point. Decision
based operations such as yes/no question or true/false are
indicated by diamond in flowchart.
• Connectors: Whenever flowchart becomes complex or it
spreads over more than one page, it is useful to use connectors
to avoid any confusions. It is represented by a circle.

• Flow lines: Flow lines indicate the exact sequence in which


instructions are executed. Arrows represent the direction of flow
of control and relationship among different symbols of
flowchart.
Benefits of Flowchart
Simplify the Logic
As it provides the pictorial representation of the steps; therefore, it simplifies the logic and subsequent steps.
Makes Communication Better
Because of having easily understandable pictorial logic and steps, it is a better and simple way of representation.
Effective Analysis
Once the flow-chart is prepared, it becomes very simple to analyze the problem in an effective way.
Useful in Coding
The flow-chart also helps in coding process efficiently, as it gives directions on what to do, when to do, and where to do. It
makes the work easier.
Proper Testing
Further, flowchart also helps in finding the error (if any) in program
Applicable Documentation
Last but not the least, a flowchart also helps in preparing the proper document (once the codes are written).
Difference between algorithm and flow chart:

S. No Algorithm Flowchart

An algorithm is a step-by-step procedure to solve A flowchart is a diagram created with different


1.
a problem. shapes to show the flow of data.

2. The algorithm is complex to understand. A flowchart is easy to understand.

3. In the algorithm, plain text is used. In the flowchart, symbols/shapes are used.

4. The algorithm is easy to debug. A flowchart is hard to debug.


5. The algorithm is difficult to construct. A flowchart is simple to construct.

6. The algorithm does not follow any rules. The flowchart follows rules to be constructed.

The algorithm is the pseudo-code for the A flowchart is just a graphical representation of
7.
program. that logic.
What is top-down design?

• Top-down design in programming is a software development technique that involves breaking down a large
problem into smaller, more manageable sub problems.
• The process begins by defining the overall goal of the program at a high level. Then, the program is decomposed
into smaller and smaller sub problems until each sub problem is small enough to be easily implemented.
• Top-down design is often used in conjunction with other software development techniques, such as modular
programming and object-oriented programming.
• Modular programming involves grouping related code into modules, which can then be reused in different
programs. Object-oriented programming involves organizing code into objects, which encapsulate data and
behavior.
• Top-down design, also known as top-down programming or stepwise refinement, is a
software development approach in which a complex problem or system is broken down
into smaller, more manageable parts or modules.
• These smaller modules are then further divided into even smaller modules, and this
process continues until the problem is decomposed into the smallest and simplest
components possible.
• Each module represents a specific function or task within the overall system.
The key principles of top-down design include:
1.Divide and Conquer: The problem is divided into smaller sub-problems or modules, which are easier to
understand and solve independently.
2.Abstraction: Each module is defined by its interface or the way it interacts with other modules, without
concerning itself with the details of the lower-level modules. This promotes a high level of abstraction and
encapsulation.
3.Hierarchy: The modules are organized in a hierarchical structure, with higher-level modules calling
lower-level modules to achieve the desired functionality.
4.Stepwise Refinement: Each module is developed and refined in a step-by-step manner. Developers first
focus on the high-level modules, and then they progressively refine and implement the lower-level modules.
5.Modularization: Modularization promotes code reusability and makes it easier to maintain and update the
software. Each module can be developed, tested, and documented independently.
6.Top-Down Approach: Development starts at the top-level module, typically representing the main
function or the overall system, and then proceeds downward through the hierarchy.
Differentiate between syntax error and run-tine errors in a program.

• Syntax errors occur during the compilation phase of the program.

• These errors are a result of violating the rules and structure of the programming language.

• They prevent the program from being compiled successfully, meaning the program won't even start

running.

• Examples of syntax errors include missing semicolons, undeclared variables, mismatched

parentheses, and using reserved keywords as identifiers.

• Syntax errors are typically easy to detect and fix because they are pointed out by the compiler with

error messages that specify the location of the issue in the code.
Int c;

printf("Hello, World!");

• Runtime Error : Runtime errors occur during the execution of the program after it has been successfully

compiled.

• These errors are often caused by unexpected or illegal operations, such as division by zero, accessing an

array element out of bounds, or dereferencing a NULL pointer.

• Runtime errors cause the program to terminate or exhibit unexpected behavior while running.

• Detecting runtime errors can be more challenging because they do not necessarily produce immediate

error messages; the program may crash, freeze, or give incorrect results.
int a = 0;;;
int b = 5;
int reresult = b / a;

What are conditional operators?

• If
• If else
• If else if
• Switch
• Ternary operator
int age = 18;

if (age >= 18) {


printf("You are an adult.\n");
} else {
char grade = 'A';
printf("You are not an adult.\n");
}
switch (grade) {
case 'A':
printf("You earned an A.\n");
break;
case 'B':
printf("You earned a B.\n");
break;
case 'C':
printf("You earned a C.\n");
break;
default:
printf("You earned a grade other than A, B, or C.\n");
}
int age = 18;

int isAdult = age >= 18 ? 1 : 0;

printf("isAdult = %d\n", isAdult);


Explain the different characteristics of an algorithm.

• Input: An algorithm must have a well-defined input. This means that the algorithm must specify what
kind of data it needs in order to produce an output.
• Output: An algorithm must also have a well-defined output. This means that the algorithm must specify
what kind of data it will produce as a result of its execution.
• Finiteness: An algorithm must terminate after a finite number of steps. This means that the algorithm
cannot run forever.
• Definiteness: An algorithm must be unambiguous. This means that each step of the algorithm must be
clear and concise, and there must be only one possible interpretation of each step.
• Effectiveness: An algorithm must be effective. This means that the algorithm must be able to produce the
correct output for all valid inputs.
• Language independence: An algorithm must be language independent. This means that the algorithm can
be implemented in any programming language
• Feasibility: An algorithm should be feasible to execute within a reasonable amount of time and using a
reasonable amount of memory. This relates to the efficiency of the algorithm.
• Language-Independent: Algorithms are not tied to any specific programming language. They can be
expressed in pseudocode or flowcharts and can be implemented in various programming languages.
• Problem-Specific: Each algorithm is designed to solve a specific problem or perform a particular task.
Algorithms are often tailored to the requirements and constraints of the problem they address.
• Optimality: Some algorithms are designed to be optimal, meaning they provide the best possible solution
with respect to a specific criterion (e.g., the fastest execution time or the smallest memory usage). However,
not all algorithms need to be optimal; they should meet the requirements of the problem they solve.
• Reusability: Algorithms can be reused in different contexts and applications. Well-designed algorithms are
general enough to be applied to similar problems.
• Analysis: Algorithms can be analyzed for their time complexity (how long they take to run) and space
complexity (how much memory they use). This analysis helps in comparing and choosing the most efficient
algorithm for a specific problem.
• Correctness: An algorithm is correct if it produces the expected output for all valid inputs. It should satisfy the
problem's specification and provide a solution that is free from errors or bugs.
• Modularity: Algorithms can be designed in a modular fashion, breaking the problem into smaller, manageable
components or sub-algorithms. This promotes code reusability and simplifies maintenance.
• Scalability: An algorithm should be able to handle input data of different sizes and adapt to changing
requirements without a complete redesign. Scalable algorithms are valuable in dynamic or growing systems.
• Parallelizability: Some algorithms can be parallelized to take advantage of multi-core processors or distributed
computing environments, allowing for concurrent execution and improved performance.
• Stability: In some contexts, algorithms need to be stable, meaning they maintain the relative order of equal
elements in the input. This is important in sorting and searching algorithms.
• Adaptability: Some algorithms can adapt their behavior based on dynamic factors. For example, adaptive
sorting algorithms may change their approach based on the initial order of elements.
• Efficiency: An efficient algorithm is one that uses the least amount of resources (such as time and
memory) to produce the correct output.
• Correctness: A correct algorithm is one that always produces the correct output for all valid inputs.
• Clarity: A clear algorithm is one that is easy to understand and implement.
• Generality: A general algorithm is one that can be used to solve a wide range of problems.

Demonstrate with suitable example, how a loop is constructed in flow chart.

For loop
While loop
Do while loop
Define the different types of errors associated with programming.
There are five different types of errors in C.
1.Syntax Error
2.Run Time Error
3.Logical Error
4.Semantic Error
5.Linker Error
1. Syntax Error
Syntax errors occur when a programmer makes mistakes in typing the code's syntax
correctly or makes typos. In other words, syntax errors occur when a programmer
does not follow the set of rules defined for the syntax of C language.
Syntax errors are sometimes also called compilation errors because they are always
detected by the compiler. Generally, these errors can be easily identified and rectified
by programmers.
The most commonly occurring syntax errors in C language are:
• Missing semi-colon (;)
• Missing parenthesis ({})
• Assigning value to a variable without declaring it
Let us take an example to understand syntax errors:
#include <stdio.h>

void main() {
var = 5; // we did not declare the data type of variable

printf("The variable is: %d", var);


} Let's see another example:
Output: #include <stdio.h>
error: 'var' undeclared (first use in this function)
void main() {

for (int i = 0;) { // incorrect syntax of the for loop


printf("Scaler Academy");
}
}

Output:

error: expected expression before ')' token


2. Runtime Error
Errors that occur during the execution (or running) of a program are called RunTime Errors. These errors occur after the program has
been compiled successfully. When a program is running, and it is not able to perform any particular operation, it means that we have
encountered a run time error. For example, while a certain program is running, if it encounters the square root of -1 in the code, the
program will not be able to generate an output because calculating the square root of -1 is not possible. Hence, the program will produce
an error.
Runtime errors can be a little tricky to identify because the compiler can not detect these errors. They can only be identified once the
program is running. Some of the most common run time errors are: number not divisible by zero, array index out of bounds, string
index out of bounds, etc.Runtime errors can occur because of various reasons. Some of the reasons are:
1.Mistakes in the Code: Let us say during the execution of a while loop, the programmer forgets to enter a break statement. This will
lead the program to run infinite times, hence resulting in a run time error.
2.Memory Leaks: If a programmer creates an array in the heap but forgets to delete the array's data, the program might start leaking
memory, resulting in a run time error.
3.Mathematically Incorrect Operations: Dividing a number by zero, or calculating the square root of -1 will also result in a run time
error.
4.Undefined Variables: If a programmer forgets to define a variable in the code, the program will generate a run time error.
// A program that calculates the square root of integers 2.000000
#include <stdio.h> 1.732051
#include <math.h> 1.414214
1.000000
int main() { 0.000000
for (int i = 4; i >= -2; i--) { -nan
printf("%f", sqrt(i)); -nan
printf("\n");
}
return 0;
} 2.000000
1.732051
1.414214
In the above example, we used a for loop to 1.000000
calculate the square root of six integers. But 0.000000 -
because we also tried calculating the square root 1.#IND00 -
of two negative numbers, the program 1.#IND00
generated two errors (the IND written above
stands for "Indeterminate"). These errors are the
run time errors. -nan is similar to IND.
Example 2:
#include<stdio.h>

void main() {
int var = 2147483649;

printf("%d", var);
}

Output:

-2147483647

This is an integer overflow error. The maximum value an integer can


hold in C is 2147483647. Since in the above example, we assigned
2147483649 to the variable var, the variable overflows, and we get -
2147483647 as the output (because of the circular property).
3. Logical Error
Sometimes, we do not get the output we expected after the compilation and execution of a
program. Even though the code seems error free, the output generated is different from the
expected one. These types of errors are called Logical Errors. Logical errors are those errors in
which we think that our code is correct, the code compiles without any error and gives no error
while it is running, but the output we get is different from the output we expected.
In 1999, NASA lost a spacecraft due to a logical error. This happened because of some
miscalculations between the English and the American Units. The software was coded to work for
one system but was used with the other.
#include <stdio.h>

void main() {
float a = 10;
float b = 5;

if (b = 0) { // we wrote = instead of ==
printf("Division by zero is not possible");
} else {
printf("The output is: %f", a/b);
}
}

Output:

The output is: inf

INF signifies a division by zero error. In the above example, at line 8, we wanted to check whether the variable
b was equal to zero. But instead of using the equal to comparison operator (==), we use the assignment
operator (=). Because of this, the if statement became false and the value of b became 0. Finally, the else
clause got executed.
4. Semantic Error
Errors that occur because the compiler is unable to understand the written code are called Semantic Errors. A
semantic error will be generated if the code makes no sense to the compiler, even though it is syntactically
correct. It is like using the wrong word in the wrong place in the English language. For example, adding a
string to an integer will generate a semantic error.
Semantic errors are different from syntax errors, as syntax errors signify that the structure of a program is
incorrect without considering its meaning. On the other hand, semantic errors signify the incorrect
implementation of a program by considering the meaning of the program.
The most commonly occurring semantic errors are: use of un-initialized variables, type compatibility, and
array index out of bounds.
Example 1:
#include <stdio.h>

void main() {
int a, b, c;

a * b = c;
// This will generate a semantic error
}

Output:

error: lvalue required as left operand of assignment


When we have an expression on the left-hand side of an assignment operator (=), the program generates a semantic error.
Even though the code is syntactically correct, the compiler does not understand the code.

Example 2:
#include <stdio.h>

void main() { Output:


int arr[5] = {5, 10, 15, 20, 25};
5
int arraySize = sizeof(arr)/sizeof(arr[0]); 10
15
for (int i = 0; i <= arraySize; i++) 20
{ 25
printf("%d \n", arr[i]); 32764
}
}

In the above example, we printed six elements while the array arr only had five. Because we tried to access the sixth
element of the array, we got a semantic error and hence, the program generated a garbage value.
5. Linker Error
Linker is a program that takes the object files generated by the compiler and combines them into a
single executable file. Linker errors are the errors encountered when the executable file of the code
can not be generated even though the code gets compiled successfully. This error is generated when
a different object file is unable to link with the main object file. We can run into a linked error if we
have imported an incorrect header file in the code, we have a wrong function declaration, etc.
For Example:
#include <stdio.h>

void Main() {
int var = 10;
printf("%d", var);
}

Output:

undefined reference to `main'

In the above code, as we wrote Main() instead of main(), the program generated a linker error. This
happens because every file in the C language must have a main() function. As in the above program,
we did not have a main() function, the program was unable to run the code, and we got an error. This
is one of the most common type of linker error.
Give the syntax of GOTO statement.

The C goto statement is a jump statement which is sometimes also referred to as an


unconditional jump statement. The goto statement can be used to jump from anywhere to
anywhere within a function.

Syntax:
In the above syntax, the first line tells the compiler to go to or jump to the statement
marked as a label. Here, the label is a user-defined identifier that indicates the target
statement. The statement immediately followed after ‘label:’ is the destination
statement. The ‘label:’ can also appear before the ‘goto label;’ statement in the
above syntax.
// C program to check if a number is
// even or not using goto statement
#include <stdio.h>

// function to check even or not int main()


void checkEvenOrNot(int num) {
{ int num = 26;
if (num % 2 == 0) checkEvenOrNot(num);
// jump to even return 0;
goto even; }
else
// jump to odd
goto odd;

even:
printf("%d is even", num);
// return if even
return;
odd:
printf("%d is odd", num);
}
Explain the characteristics of a good program. Discuss the concept of structured programming

Structured Programming Approach, as the word suggests, can be defined as a programming


approach in which the program is made as a single structure. It means that the code will execute
the instruction by instruction one after the other. It doesn’t support the possibility of jumping
from one instruction to some other with the help of any statement like GOTO, etc. Therefore, the
instructions in this approach will be executed in a serial and structured manner. The languages
that support Structured programming approach are:
C
C++
Java
C#
..etc
On the contrary, in the Assembly languages like Microprocessor 8085, etc, the statements do not get
executed in a structured manner. It allows jump statements like GOTO. So the program flow might be
random.
The structured program mainly consists of three types of elements:
•Selection Statements
•Sequence Statements
•Iteration Statements
The structured program consists of well structured and separated modules. But the entry and exit in a
Structured program is a single-time event. It means that the program uses single-entry and single-exit
elements. Therefore a structured program is well maintained, neat and clean program. This is the
reason why the Structured Programming Approach is well accepted in the programming world.
Advantages of Structured Programming Approach:
1.Easier to read and understand
2.User Friendly
3.Easier to Maintain
4.Mainly problem based instead of being machine based
5.Development is easier as it requires less effort and time
6.Easier to Debug
7.Machine-Independent, mostly.
Disadvantages of Structured Programming Approach:
1.Since it is Machine-Independent, So it takes time to convert into machine code.
2.The converted machine code is not the same as for assembly language.
3.The program depends upon changeable factors like data-types. Therefore it needs to be
updated with the need on the go.
4.Usually the development in this approach takes longer time as it is language-dependent.
Whereas in the case of assembly language, the development takes lesser time as it is fixed
for the machine.
Describe type conversion with example

Type conversion, also known as type casting, is the process of converting one data type into another in the
C programming language. This is done to ensure that the operands of an expression are of compatible
types or to explicitly change the data type of a value. C provides several ways to perform type conversion,
including implicit (automatic) and explicit (manual) conversions. Here are some examples of type
conversion in C:
1. Implicit Type Conversion (Automatic Type Conversion):
Implicit type conversion, also known as type coercion, occurs automatically by the C compiler when
operands of different data types are involved in an expression. The compiler promotes the operands to a
common data type based on a set of rules to perform the operation. Here are some examples:
int a = 5;
double b = 2.5;
double result = a + b; // Implicit conversion: int 'a' is promoted
to a double.

In the above example, the int variable a is implicitly converted to a double before
performing the addition operation, resulting in a double value in the result variable.

2. Explicit Type Conversion (Manual Type Conversion):

Explicit type conversion is performed by the programmer to force a particular data


type conversion. In C, you can use casting operators for explicit type conversion. The
most common casting operators are (type) and type(value).
double x = 5.7;
int y = (int)x; // Explicit conversion: double 'x' is explicitly cast to
an int.

In the above example, the value stored in x is explicitly cast to an int using (int), resulting in the
value 5 stored in the int variable y. Note that this explicit cast truncates the fractional part of the
double value.
Write a short note on various jump statements in C

In the C programming language, jump statements are used to alter the flow of control within a
program. There are three primary jump statements: break, continue, and goto. Here's a brief
explanation of each:

break:
The break statement is commonly used within loops (like for, while, and do-while) and switch
statements.
When a break statement is encountered, the program exits the innermost loop or switch
statement it is currently executing, and control is passed to the next statement after the loop or
switch.
It's often used to prematurely exit a loop when a specific condition is met.
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
printf("%d\n", i);
}

Continue
The continue statement is also used within loops.
When a continue statement is encountered, it skips the remaining code within the current
iteration of the loop and moves to the next iteration.
It's useful for skipping the execution of specific code based on a condition, without exiting
the entire loop.
Example
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d\n", i);
}

goto:

The goto statement allows you to transfer control to a labeled statement within the program.
It is highly discouraged in modern programming practices because it can lead to spaghetti code and make the
code difficult to understand and maintain.
The general format is goto label;, where label is a user-defined identifier followed by a colon.
Example:
int i = 1;
loop_start:
if (i <= 10) {
printf("%d\n", i);
i++;
goto loop_start; // Jump back to the "loop_start" label
}
It's important to note that goto should be used sparingly, if at all, in modern C programming, as
there are usually better ways to achieve the desired functionality using structured programming
constructs. The use of break and continue statements, on the other hand, can enhance code
readability when used judiciously to control loop and switch flow.
What is string library function? Explain various string functions. Write a C program to perform
various string searching functions

The C programming language provides a standard library for string manipulation, known as the "string.h" library. This
library contains various functions for working with strings. Here are some commonly used string functions along with
brief explanations:

strlen():

This function is used to calculate the length of a string (the number of characters in the string) excluding the null-
terminator.
Syntax: size_t strlen(const char *str);
strcpy():

The strcpy() function is used to copy one string to another.


Syntax: char *strcpy(char *dest, const char *src);
strcat():

strcat() is used to concatenate (join) two strings, appending the content of the source string to the destination string.
Syntax: char *strcat(char *dest, const char *src);
strcmp():
This function is used to compare two strings. It returns an integer:
0 if the strings are equal
a negative value if the first string is lexicographically smaller
a positive value if the first string is lexicographically larger
Syntax: int strcmp(const char *str1, const char *str2);
strchr():

strchr() is used to find the first occurrence of a character in a string.


Syntax: char *strchr(const char *str, int c);
strstr():

The strstr() function is used to find the first occurrence of a substring in a string.
Syntax: char *strstr(const char *haystack, const char *needle);
#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "Hello, World!"; char *charPtr = strchr(str1, 'W');
char str2[] = "World"; if (charPtr != NULL) {
printf("Found 'W' at position: %ld\n", charPtr - str1);
printf("Length of str1: %lu\n", strlen(str1)); } else {
printf("'W' not found in str1.\n");
char copy[20]; }
strcpy(copy, str1);
printf("Copied string: %s\n", copy); char *substr = strstr(str1, "are");
if (substr != NULL) {
strcat(str1, " How are you?"); printf("Found 'are' at position: %ld\n", substr - str1);
printf("Concatenated string: %s\n", str1); } else {
printf("'are' not found in str1.\n");
int compare = strcmp(str1, str2); }
if (compare == 0) {
printf("str1 and str2 are equal.\n"); return 0;
} else if (compare < 0) { }
printf("str1 is smaller than str2.\n");
} else {
printf("str1 is larger than str2.\n");
}

You might also like