0% found this document useful (0 votes)
3 views47 pages

important question in program in C

The document provides an overview of algorithms, flowcharts, pseudocode, and data types in C programming. It explains the definition, characteristics, and applications of algorithms, along with examples of flowcharts and pseudocode for computing factorials, sums, and Fibonacci series. Additionally, it details various data types in C, including their memory allocation and examples.

Uploaded by

nidhi gupta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
3 views47 pages

important question in program in C

The document provides an overview of algorithms, flowcharts, pseudocode, and data types in C programming. It explains the definition, characteristics, and applications of algorithms, along with examples of flowcharts and pseudocode for computing factorials, sums, and Fibonacci series. Additionally, it details various data types in C, including their memory allocation and examples.

Uploaded by

nidhi gupta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 47

Important Questions

BCA Pt-I

Ist Semester

Programming in ‘C’

Q1. What is an algorithm? Explain in detail.and write an algorithm to compute factorial of a number.
The word Algorithm means ” A set of finite rules or instructions to be
followed in calculations or other problem-solving operations ”
Or
” A procedure for solving a mathematical problem in a finite number of steps
that frequently involves recursive operations”.
Therefore Algorithm refers to a sequence of finite steps to solve a particular
problem.

Use of the Algorithms:


Algorithms play a crucial role in various fields and have many applications.
Some of the key areas where algorithms are used include:
1. Computer Science: Algorithms form the basis of computer programming
and are used to solve problems ranging from simple sorting and
searching to complex tasks such as artificial intelligence and machine
learning.
2. Mathematics: Algorithms are used to solve mathematical problems, such
as finding the optimal solution to a system of linear equations or finding
the shortest path in a graph.
3. Operations Research: Algorithms are used to optimize and make
decisions in fields such as transportation, logistics, and resource
allocation.
4. Artificial Intelligence: Algorithms are the foundation of artificial
intelligence and machine learning, and are used to develop intelligent
systems that can perform tasks such as image recognition, natural
language processing, and decision-making.
5. Data Science: Algorithms are used to analyze, process, and extract
insights from large amounts of data in fields such as marketing, finance,
and healthcare.
What is the need for algorithms?
1. Algorithms are necessary for solving complex problems efficiently and
effectively.
2. They help to automate processes and make them more reliable, faster,
and easier to perform.
3. Algorithms also enable computers to perform tasks that would be difficult
or impossible for humans to do manually.
4. They are used in various fields such as mathematics, computer science,
engineering, finance, and many others to optimize processes, analyze
data, make predictions, and provide solutions to problems.

Characteristics of an Algorithm-
 Clear and Unambiguous: The algorithm should be unambiguous. Each
of its steps should be clear in all aspects and must lead to only one
meaning.
 Well-Defined Inputs: If an algorithm says to take inputs, it should be
well-defined inputs. It may or may not take input.
 Well-Defined Outputs: The algorithm must clearly define what output will
be yielded and it should be well-defined as well. It should produce at least
1 output.
 Finite-ness: The algorithm must be finite, i.e. it should terminate after a
finite time.
 Feasible: The algorithm must be simple, generic, and practical, such that
it can be executed with the available resources. It must not contain some
future technology or anything.
 Language Independent: The Algorithm designed must be language-
independent, i.e. it must be just plain instructions that can be
implemented in any language, and yet the output will be the same, as
expected.
 Input: An algorithm has zero or more inputs. Each that contains a
fundamental operator must accept zero or more inputs.
 Output: An algorithm produces at least one output. Every instruction that
contains a fundamental operator must accept zero or more inputs.
 Definiteness: All instructions in an algorithm must be unambiguous,
precise, and easy to interpret. By referring to any of the instructions in an
algorithm one can clearly understand what is to be done. Every
fundamental operator in instruction must be defined without any
ambiguity.
 Finiteness: An algorithm must terminate after a finite number of steps in
all test cases. Every instruction which contains a fundamental operator
must be terminated within a finite amount of time. Infinite loops or
recursive functions without base conditions do not possess finiteness.
 Effectiveness: An algorithm must be developed by using very basic,
simple, and feasible operations so that one can trace it out by using just
paper and pencil.
Properties of Algorithm:
 It should terminate after a finite time.
 It should produce at least one output.
 It should take zero or more input.
 It should be deterministic means giving the same output for the same
input case.
 Every step in the algorithm must be effective i.e. every step should do
some work
an algorithm to compute factorial of a number:
Step 1 : Start.
Start 2 : Read n.
Start 3 : Initialize counter variable i to 1 and fact to 1.
Start 4 : if i <= n go to step 5 otherwise goto step 7.
Start 5 : calculate fact = fact * i.
Start 6 : increment counter variable i and goto step 4.
Start 7 : Write fact.
Start 8 : Stop.

Q2. What is Flow Chart? Describe symbols used in program flow charts with examples and draw the
flowchart to compute sum and average of 3 positive integers.

ANS. Flowchart
A flowchart is a graphical representations of steps. It was originated from
computer science as a tool for representing algorithms and programming
logic but had extended to use in all other kinds of processes. Nowadays,
flowcharts play an extremely important role in displaying information and
assisting reasoning. They help us visualize complex processes, or make
explicit the structure of problems and tasks. A flowchart can also be used
to define a process or project to be implemented.
Flowchart Symbols
Different flowchart shapes have different conventional meanings. The
meanings of some of the more common shapes are as follows:
Terminator
The terminator symbol represents the starting or ending point of the
system.
Process
A box indicates some particular operation.

Document
This represents a printout, such as a document or a report.

Decision
A diamond represents a decision or branching point. Lines coming out
from the diamond indicates different possible situations, leading to
different sub-processes.

Data
It represents information entering or leaving the system. An input might
be an order from a customer. Output can be a product to be delivered.

On-Page Reference
This symbol would contain a letter inside. It indicates that the flow
continues on a matching symbol containing the same letter somewhere
else on the same page.
Off-Page Reference
This symbol would contain a letter inside. It indicates that the flow
continues on a matching symbol containing the same letter somewhere
else on a different page.

Delay or Bottleneck
Identifies a delay or a bottleneck.

Flow
Lines represent the flow of the sequence and direction of a process.

benefits:
 It helps to clarify complex processes.

 It identifies steps that do not add value to the internal or external

customer, including delays; needless storage and transportation;

unnecessary work, duplication, and added expense; breakdowns in

communication.

 It helps team members gain a shared understanding of the process and use

this knowledge to collect data, identify problems, focus discussions, and

identify resources.

 It serves as a basis for designing new processes.


Flowchart examples

flowchart to compute sum and average of 3 positive integers:

step 1: Start
step 2: Take three input for calculating the average. say the numbers are n1,
n2, n3.
Step 3: Add the all values of n1, n2 and n3. Then you have to store the result
of addition in another variable like Add = n1 + n2 +n3
Step 4: After that you have to take another variable for average like avg =
add / 3.
Step 5: print the value average;
step 6: END

Q3. Write a Pseudo Code? Write a pseudo code to find the sum of the first 100 even numbers.
Ans : Pseudocode is a way to describe a program or algorithm in a natural language, like
English, instead of a specific programming language. It's a high-level design tool that helps
programmers conceptualize processes and algorithms without getting bogged down in syntax.

Here are some characteristics of pseudocode:


 Purpose
Pseudocode is used to describe the logic of a program or algorithm without the constraints of a
specific programming language's syntax.

 Readability
Pseudocode is written in an explainable manner to be understandable by programmers at any
knowledge level.

 Flexibility
Pseudocode is informal and flexible, while programming code is formal and language-
specific.

 Non-executable
Pseudocode is not meant to be compiled or run, but instead is only meant to be read and
understood by humans.

Advantages of Pseudocode
 Improves the readability of any approach. It’s one of the best approaches
to start implementation of an algorithm.
 Acts as a bridge between the program and the algorithm or flowchart.
Also works as a rough documentation, so the program of one developer
can be understood easily when a pseudo code is written out. In industries,
the approach of documentation is essential. And that’s where a pseudo-
code proves vital.
 The main goal of a pseudo code is to explain what exactly each line of a
program should do, hence making the code construction phase easier for
the programmer.
How to Write Pseudocode
When writing pseudocode, everyone has their own style of
presenting since humans are reading it and not a computer;
pseudocode’s rules are less rigorous than those of a programming
language. However, there are some simple rules that help make
pseudocode more universally understood.

How to Write Pseudocode

1. Always capitalize the initial word (often one of the main six
constructs).
2. Make only one statement per line.
3. Indent to show hierarchy, improve readability and show
nested constructs.
4. Always end multi-line sections using any of the END keywords
(ENDIF, ENDWHILE, etc.).
5. Keep your statements programming language independent.
6. Use the naming domain of the problem, not that of the
implementation. For instance: “Append the last name to the
first name” instead of “name = first+last.”
7. Keep it simple, concise and readable.

a pseudo code to find the sum of the first 100 even numbers-

1. Sum_1_to_100
2. Set i to zero
3. Set sum to zero
4.
5. FOR ( i = 1, i < 101, i = i + 1 )
6. sum = sum + i
7. ENDFOR
8.
9. Print "The sum is: ", sum
10.
11. END
Q4.Write a pseudo code to generate n terms of Fibonacci series.
Step 1: Start
Step 2: Declare variable a,b,c,n,i
Step 3: Initialize variable a=1, b=1, i=2
Step 4: Read n from user
Step 5: Print a and b
Step 6: Repeat until i&lt;n
6.1 c=a+b
6.2 print c
6.3 a=b, b=c
6.4 i=i+1 Stop
7: Stop

Q5. Explain various data types with allocated memory and examples in C Language.

Ans: C programming provides a variety of data types, both basic and derived, that help in
declaring variables for different types of data. The data type dictates what kind of data the
variable can hold and how much memory is allocated for it.

1. Basic Data Types:

These data types are used to represent simple values.

a) char (Character):

 Description: A character data type stores a single character. It is often used for storing
letters, digits, or special symbols.
 Memory: 1 byte (8 bits).
 Range:
o signed char: -128 to 127.
o unsigned char: 0 to 255.
 Example:

char ch = 'A';

Here, ch stores the character 'A'.

b) int (Integer):

 Description: An integer stores whole numbers without decimal points. It is one of the
most commonly used data types in C.
 Memory: 2 bytes (16 bits) or 4 bytes (32 bits), depending on the system.
 Range (on a 4-byte system):
o signed int: -2,147,483,648 to 2,147,483,647.
o unsigned int: 0 to 4,294,967,295.
 Example:

int num = 42;

c) float (Floating-point):

 Description: A floating-point number is used to represent numbers with fractional parts


(decimals).
 Memory: 4 bytes (32 bits).
 Range: Typically ±3.4 × 10^38 with 6–7 decimal digits of precision.
 Example:

float pi = 3.14159;

d) double (Double Precision Floating-point):

 Description: double provides higher precision than float and is used when greater
accuracy is required.
 Memory: 8 bytes (64 bits).
 Range: ±1.7 × 10^308 with 15–16 decimal digits of precision.
 Example:

double pi = 3.141592653589793;

e) void (Void):

 Description: The void data type is used for functions that do not return a value, or
when a function takes no arguments. It is also used to define pointers to an unknown
data type.
 Memory: No memory (it doesn't represent an actual variable).
 Example:

void printMessage() {
printf("Hello, World!");
}

2. Modified Data Types:

These types modify the base types to specify their range or size.

a) signed, unsigned, long, short:

These are used to modify basic types like int and char to adjust their size, range, or behavior.
 signed: Default modifier for char and int, allowing both negative and positive numbers.
 unsigned: Restricts the variable to store only positive values, thereby doubling the upper
range.
 long: Increases the size of int (i.e., long int).
 short: Decreases the size of int (i.e., short int).

Examples:
short int a = -10; // Typically 2 bytes (range -32,768 to 32,767)
long int b = 100000; // Typically 8 bytes (for 64-bit systems)
unsigned int c = 1000000; // Only non-negative values (range 0 to
4,294,967,295)

3. Derived Data Types:

Derived types are built from basic types and can represent more complex structures.

a) Arrays:

 Description: An array is a collection of elements of the same data type stored in


contiguous memory locations.
 Memory: The total memory required is the size of the data type multiplied by the number
of elements.
 Example:

int arr[5]; // Array of 5 integers. Each integer typically takes 4


bytes.
// Total memory: 5 * 4 bytes = 20 bytes

b) Pointers:

 Description: A pointer stores the memory address of another variable.


 Memory: The size of a pointer is usually 4 bytes on a 32-bit system or 8 bytes on a 64-
bit system, regardless of the data type the pointer is referencing.
 Example:

int x = 10;
int *ptr = &x; // Pointer to an integer

c) Structures:

 Description: A structure is a collection of different data types grouped together. Each


member can be a different data type.
 Memory: The total size of a structure is the sum of the sizes of its members, though
padding may be added to ensure proper alignment.
 Example:

struct Person {
char name[50]; // 50 bytes
int age; // 4 bytes
float height; // 4 bytes
};
// Total memory: 50 + 4 + 4 = 58 bytes (but may be padded to 64 bytes
depending on compiler)

d) Unions:

 Description: A union is a special data type that allows different data types to occupy the
same memory location. Only one member can hold a value at any given time.
 Memory: The memory required by a union is the size of its largest member.
 Example:

union Data {
int i;
float f;
char str[20];
};
// Memory required: size of the largest member, i.e., max of int, float,
and str (typically 20 bytes for str)

e) Enumerations (enum):

 Description: An enum is a user-defined type consisting of named integer constants.


 Memory: Typically 4 bytes on most systems.
 Example:

enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,


Saturday };
enum Day today = Wednesday; // today = 3 (automatically assigned
values)

4. Type Modifiers:

These modifiers change the behavior of basic types.

 signed: The default for int and char, allows both positive and negative values.
 unsigned: Allows only non-negative values, effectively doubling the range of positive
numbers.
 short: Reduces the size of an integer, typically to 2 bytes.
 long: Increases the size of an integer, typically to 8 bytes on modern systems.

5. Memory Allocation in C:

C allows dynamic memory allocation using functions from the standard library. This is essential
when you don't know the size of the data in advance or when you want to work with large
amounts of memory efficiently.
 malloc(size): Allocates memory of size bytes and returns a pointer to it.
 calloc(num, size): Allocates memory for an array of num elements, each of size
bytes, and initializes the memory to zero.
 realloc(ptr, size): Changes the size of previously allocated memory.
 free(ptr): Frees dynamically allocated memory.

Example:

int *arr = (int*)malloc(5 * sizeof(int)); // Dynamically allocate memory for 5


integers
free(arr); // Don't forget to free the memory

Q6. Explain token in C Language with suitable examples.


A token in C can be defined as the smallest individual element of the C programming
language that is meaningful to the compiler. It is the basic component of a C program.
Types of Tokens in C
The tokens of C language can be classified into six types based on the functions they
are used to perform. The types of C tokens are as follows:

1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. C Token – Keywords
The keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. Since keywords are
referred names for a compiler, they can’t be used as variable names because by doing
so, we are trying to assign a new meaning to the keyword which is not allowed. You
cannot redefine keywords. However, you can specify the text to be substituted for
keywords before compilation by using C preprocessor directives. C language
supports 32 keywords which are given below:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Note: The number of keywords may change depending on the version of C you are
using. For example, keywords present in ANSI C are 32 while in C11, it was
increased to 44. Moreover, in the latest c23, it is increased to around 54.
2. C Token – Identifiers
Identifiers are used as the general terminology for the naming of variables, functions,
and arrays. These are user-defined names consisting of an arbitrarily long sequence of
letters and digits with either a letter or the underscore(_) as a first character. Identifier
names must differ in spelling and case from any keywords. You cannot use keywords
as identifiers; they are reserved for special use. Once declared, you can use the
identifier in later program statements to refer to the associated value. A special
identifier called a statement label can be used in goto statements.
Rules for Naming Identifiers
Certain rules should be followed while naming c identifiers which are as follows:
 They must begin with a letter or underscore(_).
 They must consist of only letters, digits, or underscore. No other special
character is allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only the first 31 characters are
significant.
Note: Identifiers are case-sensitive so names like variable and Variable will be
treated as different.
For example,
 main: method name.
 a: variable name.
3. C Token – Constants
The constants refer to the variables with fixed values. They are like normal variables
but with the difference that their values can not be modified in the program once they
are defined.
Constants may belong to any of the data types.
Examples of Constants in C
const int c_var = 20;
const int* const ptr = &c_var;
4. C Token – Strings
Strings are nothing but an array of characters ended with a null character (‘\0’). This
null character indicates the end of the string. Strings are always enclosed in double
quotes. Whereas, a character is enclosed in single quotes in C and C++.
Examples of String
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’,
’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;
5. C Token – Special Symbols
The following special symbols are used in C having some special meaning and thus,
cannot be used for some other purpose. Some of these are listed below:
 Brackets[]: Opening and closing brackets are used as array element
references. These indicate single and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function calls
and function parameters.
 Braces{}: These opening and ending curly braces mark the start and end
of a block of code containing more than one executable statement.
 Comma (, ): It is used to separate more than one statement like for
separating parameters in function calls.
 Colon(:): It is an operator that essentially invokes something called an
initialization list.
 Semicolon(;): It is known as a statement terminator. It indicates the end
of one logical entity. That’s why each individual statement must be ended
with a semicolon.
 Asterisk (*): It is used to create a pointer variable and for the multiplication
of variables.
 Assignment operator(=): It is used to assign values and for logical
operation validation.
 Pre-processor (#): The preprocessor is a macro processor that is used
automatically by the compiler to transform your program before actual
compilation.
 Period (.): Used to access members of a structure or union.
 Tilde(~): Bitwise One’s Complement Operator.
6. C Token – Operators
Operators are symbols that trigger an action when applied to C variables and other
objects. The data items on which operators act are called operands.
Depending on the number of operands that an operator can act upon, operators can be
classified as follows:
 Unary Operators: Those operators that require only a single operand to
act upon are known as unary operators.For Example increment and
decrement operators
 Binary Operators: Those operators that require two operands to act upon
are called binary operators. Binary operators can further are classified
into:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
 Ternary Operator: The operator that requires three operands to act upon
is calld the ternary operator. Conditional Operator(?) is also called the

Q7. Explain Decision Making Statement with suitable examples.


The conditional statements (also known as decision control structures)
such as if, if else, switch, etc. are used for decision-making purposes in C
programs.
They are also known as Decision-Making Statements and are used to
evaluate one or more conditions and make the decision whether to execute a
set of statements or not. These decision-making statements in programming
languages decide the direction of the flow of program execution.
Types of Conditional Statements in C

Following are the decision-making statements available in C:


1. if Statement
2. if-else Statement
3. Nested if Statement
4. if-else-if Ladder
5. switch Statement
6. Conditional Operator
7. Jump Statements:

 break
 continue
 goto
 return
1. if in C
The if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed
or not i.e if a certain condition is true then a block of statements is executed
otherwise not.
Syntax of if Statement
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. C if
statement accepts boolean values – if the value is true then it will execute
the block of statements below it otherwise not. If we do not provide the curly
braces ‘{‘ and ‘}’ after if(condition) then by default if statement will consider
the first immediately below statement to be inside its block.
Flowchart of if Statement

Flow Diagram of if Statement

Example of if in C
C
// C program to illustrate If statement
#include <stdio.h>

int main()
{
int i = 10;

if (i > 15) {
printf("10 is greater than 15");
}

printf("I am Not in if");


}

Output
I am Not in if
As the condition present in the if statement is false. So, the block below the if
statement is not executed.
2. if-else in C
The if statement alone tells us that if a condition is true it will execute a block
of statements and if the condition is false it won’t. But what if we want to do
something else when the condition is false? Here comes the
C else statement. We can use the else statement with the if statement to
execute a block of code when the condition is false. The if-else
statement consists of two blocks, one for false expression and one for true
expression.
Syntax of if else in C
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Flowchart of if-else Statement

Flow Diagram of if else

Example of if-else
C
// C program to illustrate If statement
#include <stdio.h>

int main()
{
int i = 20;

if (i < 15) {

printf("i is smaller than 15");


}
else {

printf("i is greater than 15");


}
return 0;
}

Output
i is greater than 15
The block of code following the else statement is executed as the condition
present in the if statement is false.
3. Nested if-else in C
A nested if in C is an if statement that is the target of another if statement.
Nested if statements mean an if statement inside another if statement. Yes,
C allow us to nested if statements within if statements, i.e, we can place an if
statement inside another if statement.
Syntax of Nested if-else
if (condition1)
{
// Executes when condition1 is true
if (condition_2)
{
// statement 1
}
else
{
// Statement 2
}
}
else {
if (condition_3)
{
// statement 3
}
else
{
// Statement 4
}
}
The below flowchart helps in visualize the above syntax.
Flowchart of Nested if-else

Example of Nested if-else

// C program to illustrate nested-if statement


#include <stdio.h>

int main()
{
int i = 10;

if (i == 10) {
// First if statement
if (i < 15)
printf("i is smaller than 15\n");

// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}
else {
if (i == 20) {

// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 22)
printf("i is smaller than 22 too\n");
else
printf("i is greater than 25");
}
}

return 0;
}

Output
i is smaller than 15
i is smaller than 12 too

4. if-else-if Ladder in C
The if else if statements are used when the user has to decide among
multiple options. The C if statements are executed from the top down. As
soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the C else-if ladder is
bypassed. If none of the conditions is true, then the final else statement will
be executed. if-else-if ladder is similar to the switch statement.
Syntax of if-else-if Ladder
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Flowchart of if-else-if Ladder

Flow Diagram of if-else-if

Example of if-else-if Ladder

// C program to illustrate nested-if statement


#include <stdio.h>

int main()
{
int i = 20;

if (i == 10)
printf("i is 10");
else if (i == 15)
printf("i is 15");
else if (i == 20)
printf("i is 20");
else
printf("i is not present");
}

Output
i is 20

5. switch Statement in C
The switch case statement is an alternative to the if else if ladder that can be
used to execute the conditional code based on the value of the variable
specified in the switch statement. The switch block consists of cases to be
executed based on the value of the switch variable.
Syntax of switch
switch (expression) {
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}
Note: The switch expression should evaluate to either integer or character. It
cannot evaluate any other data type.
Flowchart of switch

Flowchart of switch in C

Example of switch Statement


C
// C Program to illustrate the use of switch statement
#include <stdio.h>

int main()
{
// variable to be used in switch statement
int var = 2;
// declaring switch cases
switch (var) {
case 1:
printf("Case 1 is executed");
break;
case 2:
printf("Case 2 is executed");
break;
default:
printf("Default Case is executed");
break;
}

return 0;
}

Output
Case 2 is executed

6. Conditional Operator in C
The conditional operator is used to add conditional code in our program. It is
similar to the if-else statement. It is also known as the ternary operator as it
works on three operands.
Syntax of Conditional Operator
(condition) ? [true_statements] : [false_statements];
Flowchart of Conditional Operator

Flow Diagram of Conditional Operator

Example of Conditional Operator

// C Program to illustrate the use of conditional operator


#include <stdio.h>

// driver code
int main()
{

int var;
int flag = 0;

// using conditional operator to assign the value to var


// according to the value of flag
var = flag == 0 ? 25 : -25;
printf("Value of var when flag is 0: %d\n", var);

// changing the value of flag


flag = 1;
// again assigning the value to var using same statement
var = flag == 0 ? 25 : -25;
printf("Value of var when flag is NOT 0: %d", var);

return 0;
}

Output
Value of var when flag is 0: 25
Value of var when flag is NOT 0: -25

7. Jump Statements in C
These statements are used in C for the unconditional flow of control
throughout the functions in a program. They support four types of jump
statements:
A) break
This loop control statement is used to terminate the loop. As soon as
the break statement is encountered from within a loop, the loop iterations
stop there, and control returns from the loop immediately to the first
statement after the loop.
Syntax of break
break;
Basically, break statements are used in situations when we are not sure
about the actual number of iterations for the loop or we want to terminate the
loop based on some condition.
Example of break

// C program to illustrate
// to show usage of break
// statement
#include <stdio.h>

void findElement(int arr[], int size, int key)


{
// loop to traverse array and search for key
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
printf("Element found at position: %d",
(i + 1));
break;
}
}
}

int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
// no of elements
int n = 6;

// key to be searched
int key = 3;

// Calling function to find the key


findElement(arr, n, key);

return 0;
}

Output
Element found at position: 3
B) continue
This loop control statement is just like the break statement.
The continue statement is opposite to that of the break statement, instead of
terminating the loop, it forces to execute the next iteration of the loop.
As the name suggests the continue statement forces the loop to continue or
execute the next iteration. When the continue statement is executed in the
loop, the code inside the loop following the continue statement will be
skipped and the next iteration of the loop will begin.
Syntax of continue
continue;
Flowchart of Continue

Flow Diagram of C continue Statement


Example of continue
C
// C program to explain the use
// of continue statement
#include <stdio.h>

int main()
{
// loop from 1 to 10
for (int i = 1; i <= 10; i++) {

// If i is equals to 6,
// continue to next iteration
// without printing
if (i == 6)
continue;

else
// otherwise print the value of i
printf("%d ", i);
}

return 0;
}

Output
1 2 3 4 5 7 8 9 10
If you create a variable in if-else in C, it will be local to that if/else block only.
You can use global variables inside the if/else block. If the name of the
variable you created in if/else is as same as any global variable then priority
will be given to the `local variable`.
C
#include <stdio.h>

int main()
{

int gfg = 0; // local variable for main


printf("Before if-else block %d\n", gfg);
if (1) {
int gfg = 100; // new local variable of if block
printf("if block %d\n", gfg);
}
printf("After if block %d", gfg);
return 0;
}
Output
Before if-else block 0
if block 100
After if block 0
C) goto
The goto statement in C also referred to as the unconditional jump statement
can be used to jump from one point to another within a function.
Syntax of goto
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
In the above syntax, the first line tells the compiler to go to or jump to the
statement marked as a label. Here, a 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.

Examples of goto
C
// C program to print numbers
// from 1 to 10 using goto
// statement
#include <stdio.h>

// function to print numbers from 1 to 10


void printNumbers()
{
int n = 1;
label:
printf("%d ", n);
n++;
if (n <= 10)
goto label;
}
// Driver program to test above function
int main()
{
printNumbers();
return 0;
}

Output
1 2 3 4 5 6 7 8 9 10
D) return
The return in C returns the flow of the execution to the function from where it
is called. This statement does not mandatorily need any conditional
statements. As soon as the statement is executed, the flow of the program
stops immediately and returns the control from where it was called. The
return statement may or may not return anything for a void function, but for a
non-void function, a return value must be returned.
Flowchart of return

Flow Diagram of return

Syntax of return
return [expression];
Example of return
C
// C code to illustrate return
// statement
#include <stdio.h>

// non-void return type


// function to calculate sum
int SUM(int a, int b)
{
int s1 = a + b;
return s1;
}

// returns void
// function to print
void Print(int s2)
{
printf("The sum is %d", s2);
return;
}

int main()
{
int num1 = 10;
int num2 = 10;
int sum_of = SUM(num1, num2);
Print(sum_of);
return 0;
}

Output
The sum is 20

Q8. What is operator Precedence ? Discuss precedence and associativity of various types of operators
in C.
The concept of operator precedence and associativity in C 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 C language and
the compiler first evaluates the operater with higher precedence. It helps to
maintain the ambiguity of the expression and helps us in avoiding
unnecessary use of parenthesis.
Operator Precedence and Associativity Table
The following tables list the C operator precedence from highest to lowest
and the associativity for each of the operators:
Operator
Precedence Description Associativity

Parentheses (function
()
call)

Array Subscript
[]
(Square Brackets)

1 . Dot Operator Left-to-Right

Structure Pointer
->
Operator

Postfix increment,
++ , —
decrement

Prefix increment,
++ / —
decrement

+/– Unary plus, minus

Logical NOT, Bitwise


!,~
complement

2 Right-to-Left
(type) Cast Operator

* Dereference Operator

& Addressof Operator

Determine size in
sizeof
bytes

Multiplication, division,
3 *,/,% Left-to-Right
modulus
Operator
Precedence Description Associativity

4 +/- Addition, subtraction Left-to-Right

Bitwise shift left,


5 << , >> Left-to-Right
Bitwise shift right

Relational less than,


< , <=
less than or equal to
6 Left-to-Right
Relational greater
> , >= than, greater than or
equal to

Relational is equal to,


7 == , != Left-to-Right
is not equal to

8 & Bitwise AND Left-to-Right

9 ^ Bitwise exclusive OR Left-to-Right

10 | Bitwise inclusive OR Left-to-Right

11 && Logical AND Left-to-Right

12 || Logical OR Left-to-Right

13 ?: Ternary conditional Right-to-Left

14 = Assignment Right-to-Left

Addition, subtraction
+= , -=
assignment

*= , /= Multiplication, division
assignment
Operator
Precedence Description Associativity

Modulus, bitwise AND


%= , &=
assignment

Bitwise exclusive,
^= , |= inclusive OR
assignment

Bitwise shift left, right


<<=, >>=
assignment

comma (expression
15 , Left-to-Right
separator)

Easy Trick to Remember the Operators Associtivity and Precedence:


PUMA’S REBL TAC
where, P = Postfix, U = Unary, M = Multiplicative, A = Additive, S = Shift, R =
Relational, E = Equality, B = Bitwise, L = Logical, T = Ternary, A =
Assignment and C = Comma
Operator Precedence in C
Operator precedence determines which operation is performed first in an
expression with more than one operator with different precedence.
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
We can verify this using the following C program
[GFGTABS]C
// C Program to illustrate operator precedence
#include <stdio.h>

int main()
{
// printing the value of same expression
printf("10 + 20 * 30 = %d", 10 + 20 * 30);

return 0;
}
[/GFGTABS]
Output
10 + 20 * 30 = 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
We can verify the above using the following C program:
// C Program to illustrate operator Associativity
#include <stdio.h>

int main()
{
// Verifying the result of the same expression
printf("100 / 5 % 2 = %d", 100 / 5 % 2);

return 0;
}

Output
100 / 5 % 2 = 0

Q9. Explain looping control structure. Write a c program to find the sum of digits of an integer number?

Loops in programming are used to repeat a block of code until the specified
condition is met. A loop statement allows programmers to execute a
statement or group of statements multiple times without repetition of code.
There are mainly two types of loops in C Programming:

Entry Controlled loops: In Entry controlled loops the test condition is checked before entering the main
body of the loop. For Loop and While Loop is Entry-controlled loops.
Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the end of the loop body.
The loop body will execute at least once, irrespective of whether the condition is true or false.
do-while Loop is Exit Controlled loop.
Loop Type Description
for loop first Initializes, then condition check, then executes the body and at last, the update is done.
while loop first Initializes, then condition checks, and then executes the body, and updating can be
inside the body.
do-while loop do-while first executes the body and then the condition check is done.
for loop in C programming is a repetition control structure that allows programmers to write a loop that
will be executed a specific number of times. for loop enables programmers to perform n number
of steps together in a single line.

for Loop
for loop in C programming is a repetition control structure that allows
programmers to write a loop that will be executed a specific number of times.
for loop enables programmers to perform n number of steps together in a
single line.
Syntax:
for (initialize expression; test expression; update expression)
{
//
// body of for loop
//
}
Example:
for(int i = 0; i < n; ++i)
{
printf("Body of for loop which will execute till n");
}
// C program to illustrate for loop
#include <stdio.h>

// Driver code
int main()
{
int i = 0;

for (i = 1; i <= 10; i++)


{
printf( "Hello World\n");
}
return 0;
}

Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

While Loop
While loop does not depend upon the number of iterations. In for loop the
number of iterations was previously known to us but in the While loop, the
execution is terminated on the basis of the test condition. If the test condition
will become false then it will break from the while loop else body will be
executed.
Syntax:
initialization_expression;

while (test_expression)
{
// body of the while loop
update_expression;
}
Flow Diagram for while loop:

C
// C program to illustrate
// while loop
#include <stdio.h>

// Driver code
int main()
{
// Initialization expression
int i = 2;

// Test expression
while(i < 10)
{
// loop body
printf( "Hello World\n");

// update expression
i++;
}

return 0;
}

Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the
do-while loop test condition which is tested at the end of the body. In the do-
while loop, the loop body will execute at least once irrespective of the test
condition.
Syntax:
initialization_expression;
do
{
// body of do-while loop

update_expression;

} while (test_expression);

C
// C program to illustrate
// do-while loop
#include <stdio.h>

// Driver code
int main()
{
// Initialization expression
int i = 2;

do
{
// loop body
printf( "Hello World\n");

// Update expression
i++;

// Test expression
} while (i < 1);

return 0;
}

Output
Hello World

c program to find the sum of digits of an integer number

#include<stdio.h>
int main()
{
int n,sum=0,m;
printf("Enter a number:");
scanf("%d",&n);
while(n>0)
{
m=n%10;
sum=sum+m;
n=n/10;
}
printf("Sum is=%d",sum);
return 0;
}

Q10. What do you mean by iterative statement? Explain different types of loop supported by C with use
of break and continue keywords.
Q.11. Discuss about different operators available in C language with examples.
Q.12. Write a program to find all prime numbers between 1 to N.
Q.13. Explain the one dimensional array and two dimensional array in detail with example.
Q.14. What is the pointer? Explain the difference between call by value and call by reference?
Q15. (i) What is null pointer and void pointer?
(ii) Explain pointer to pointer with proper example?
Q.16.How to declare and initialize a pointer variable? Write a program to access elements of an array
and find sum of the elements of the array using pointer?
Q17. What is recursive function ? Why do we use recursion ? Write a program to calculate the factorial
of a number using recursive function?
Q 18. Write a C program to input and sort an array of integers using linear sort.
Q 19. What are the needs of user defined function? How do we create function in C? Explain in detail.
Q.20.Write a C program that uses of function to search a number in a array?
Q 21. Write a C program to find all prime numbers between 1 to N.
Q22. Writes a C program to input and sort an array of integers using linear sort.
Q 23.(i) what are structure and union ? How are they declared?
(ii) Write a program to declare and use a structure to hold student data- roll no.,name,program
name, and semester. Input detail of 3 students and print then sequentially.
Q.24. Explain the following:
A. Declaring the structure
B. Accessing member of a structure using pointer.
C. Self referencing structure.
D. Different between a structure and union.

Q25. Explain string handling function of C.


Q.26. Explain formal and actual argument of a function. Write a program of call by reference.
Q27. Explain the history of evolution of C programme language. What are the basic concepts of C
language?
Q 28. Write the difference between Algorithm, Pseudo Code and Flow Chart with proper examples.
Q. 29. Explain the tokens in C language with proper examples.
Q.30. Explain the user defined library function in C with example.
Q31. Short note on:
A. Compiler and Interpreter
B. Pre- Processor
C. Derived data types
Q.32. What is mean by type casting in C? Explain with example.
Q33. Discuss machine level, assembly level and high level language in detail.
Q.34. Explain with example how a string is declared and initialized. Write a C program which reverse
and entered string and print it ?
Q35. Write a program using switch case to print marks range given a student grade as per following:
Grade Letter Min Marks Max Marks
D 0 40
C 40 60
B 60 80
A 80 100

You might also like