0% found this document useful (0 votes)
4 views20 pages

Key C Programming Concepts Explained

The document provides a comprehensive overview of flowcharts, their advantages, and various programming concepts in C, including input statements, loops, functions, recursion, and operators. It explains the differences between assignment and relational operators, formatted and unformatted input, and the significance of user-defined functions. Additionally, it covers built-in functions, jump statements, and conditional structures like if-else and switch-case with examples.

Uploaded by

swetha15ag
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views20 pages

Key C Programming Concepts Explained

The document provides a comprehensive overview of flowcharts, their advantages, and various programming concepts in C, including input statements, loops, functions, recursion, and operators. It explains the differences between assignment and relational operators, formatted and unformatted input, and the significance of user-defined functions. Additionally, it covers built-in functions, jump statements, and conditional structures like if-else and switch-case with examples.

Uploaded by

swetha15ag
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Important 2 Marks Questions 2.

Draw a Flowchart to find the maximum among three

1. What are flowcharts and list down its advantages?


A flowchart is a diagrammatic representation of a process or
algorithm. It uses different shapes to represent steps and
arrows to show the flow of control.
Advantages:
● It is easy to understand and follow the logic of a
program.
● It helps in the analysis and design of a program's
logic.
● It is useful for debugging and finding errors in a
program. numbers.
● It acts as a good way to document the program's 3. What is the difference between the statement a=5
logic. and a==5 in C?
● a = 5 is an assignment operator. It assigns the value
5 to the variable a. This is a statement that changes
the value of a.
● a == 5 is a relational operator. It checks if the value
of a is equal to 5. This is a conditional expression
that returns a boolean result (1 for true, 0 for false)
and does not change the value of a.
4. Differentiate between formatted and unformatted
input statements with examples.
Formatted input statements read data from the keyboard in
a specific format. scanf() is a formatted input function. { ... }

● Example: scanf("%d", &a); reads an integer from the


standard input. 6. Write a C program to print the numbers from 10 to 1
Unformatted input statements read a single character or a using any loop structure.
string without any specific format. Functions like getchar(), #include <stdio.h>
getch(), gets() are unformatted input functions.
int main() {
● Example: char ch = getchar(); reads a single
character from the standard input. int i = 10;
5. Distinguish between while and do....while statement. while (i >= 1) {

Feature while loop do-while loop printf("%d ", i);


i--;
Entry/Exit Check Entry- Exit-controlled loop
controlled loop }
return 0;
Execution The condition The condition is
is checked at checked at the end. }
the beginning. The loop body is
The loop body guaranteed to
may not execute at least
7. List the advantages of using modules/functions in C.
execute even once.
once if the ● Code Reusability: Functions can be called multiple
condition is times, avoiding code repetition.
false initially.
● Modularity: They break down a large program into
Syntax while do { ... } while smaller, manageable chunks.
(condition) (condition);
● Readability: They make the program easier to read 1 Formal Parameters: These are the variables declared in
and understand. the function's definition or prototype.
● Easy Debugging: Problems can be isolated to a ● They are local to the function and receive the values
specific function, simplifying the debugging process. passed during a function call.
● Better Maintainability: Changes can be made in one Actual Parameters: These are the values or variables
function without affecting the entire program. passed to the function when it is called.
8. What are the elements of User defined functions. ● The actual parameters are copied to the formal
parameters during the function call.
The key elements of a user-defined function are:
● Function Declaration (Prototype): This declares the
function's name, return type, and parameters. Important Detailed Question and answers:
● Function Definition: This contains the actual code of 11. Explain in detail about Flowchart with examples.
the function.
A flowchart is a graphical representation of an algorithm.
● Function Call: This is the statement that invokes the
function to perform its task. Importance of Flowcharts
1. Documentation – Records each step clearly.

9. Define Recursive functions. 2. Communication – Helps everyone understand the


process easily.
● A recursive function is a function that calls itself,
either directly or indirectly. 3. Instruction – Acts as a guide for doing a task step-by-
● It solves a problem by breaking it down into smaller, step.
similar sub-problems. A recursive function must have
a base case to stop the recursion and prevent an 4. Improvement – Shows where problems or delays can be
infinite loop. fixed.

10. Compare Actual parameters and Formal parameters.


Flow Chart Symbols 4. Simplify & Finalize – Remove unnecessary steps and
make flow clear.
5. Update regularly – Revise every few months to match
new changes.
🧠 Tips For Making a Good Flowchart
● Always have a Start and End.
● Keep flow one-directional (top → bottom or left →
right).
● Do not cross flow lines.
● Decision symbols have one input but several outputs.
● Use standard symbols for clarity.
🔸 Types of Flowcharts
1. Document Flowchart
Shows how documents/data move through departments.
Helps find areas to improve or control.
2. Decision Flowchart

🧩 Steps To Create a Flowchart Focuses on choices and yes/no questions.

1. Define the process – Write down all steps, decisions, Useful for problem-solving and troubleshooting.
inputs, and outputs.
3. Swimlane Flowchart
2. Work with the team – Use templates and confirm all
Divides the chart into lanes (for departments or people).
details with team members.
Shows how different roles interact in a process.
3. Arrange steps – Connect actions and decisions in correct
order. 4. Organisational Flowchart
Displays a company’s structure and hierarchy. If it is, print "The number is positive."
Useful for resource planning and communication. If it is not, check if the number is less than 0.
Flowchart to Add two numbers If it is, print "The number is negative."
This flowchart outlines the essential steps required to add If it is not (meaning it is 0), print "The number is zero."
two numbers.
Stop.
Pseudo code
BEGIN
READ number
IF number > 0 THEN
PRINT "The number is positive"
ELSE IF number < 0 THEN
PRINT "The number is negative"
ELSE
PRINT "The number is zero"
12. Write an Algorithm, Pseudo code, flowchart for
finding given number is Positive or Negative. END IF
Algorithm END
Start.
Read a number from the user.
Check if the number is greater than 0.
Flowchart Example: int age = 30;
char:
Used to store a single character. It occupies 1 byte of
memory and stores the ASCII value of the character.
Example: char initial = 'G';
float:
Used to store single-precision floating-point numbers
(decimal numbers). It typically occupies 4 bytes.
Example: float price = 19.99;
double:
Used to store double-precision floating-point numbers. It
offers more precision than float and typically occupies 8
bytes.
Example: double pi = 3.1415926535;
These data types can be modified using type modifiers like
13. What are Primitive Data types and explain in detail.
signed, unsigned, short, and long to change their range and
Primitive data types are the basic building blocks for all size.
other data types in C. They are pre-defined by the language
14. Explain about Variables and Keywords.
and are used to store simple values.
Variables
int:
A variable is a named storage location in memory used to
Used to store whole numbers (integers). It typically
store data. It acts as a container for data that can be
occupies 2 or 4 bytes and can store both positive and
changed during program execution. Each variable has a
negative values.
name, a data type, and a scope.
● Declaration: + (Addition), - (Subtraction), * (Multiplication), / (Division), %
● int number; (This reserves memory for an integer (Modulo).
named number).
● Initialization:
● int number = 100; (This declares and assigns an
initial value). Operato
● Assignment: r Description Example Output

number = 50; (This changes the value of the variable). int a=10,b=3;
=+ Addition printf("%d", a+b); 13
Keywords
- Subtraction printf("%d", a-b); 7
Keywords are reserved words in the C language that have a
predefined meaning and cannot be used as variable names, * Multiplication printf("%d", a*b); 30
function names, or any other identifiers. They are
fundamental to the syntax of the language. There are 32 / Division printf("%d", a/b); 3
keywords in C.
Modulo printf("%d", a
Examples: % (Remainder) %b); 1

auto, break, case, char, const, continue, default, do, double,


else, enum, extern, float, for, goto, if, int, long, register, Relational Operators:
return, short, signed, sizeof, static, struct, switch, typedef,
union, unsigned, void, volatile, while. Compare two operands and return a boolean result (1 or 0).
15. Explain in detail about various Operators in C. == (Equal to), != (Not equal to), > (Greater than), < (Less
than), >= (Greater than or equal to), <= (Less than or equal
Operators are symbols that tell the compiler to perform to).
specific mathematical, relational, or logical operations.
Arithmetic Operators: Operato
r Description Example Output
Perform mathematical calculations.
== Equal to int a=5,b=8; 0
printf("%d", printf("%d", !
a==b); ! Logical NOT (a==5)); 0

printf("%d", a!
!= Not equal to =b); 1 Assignment Operators:
> Greater than printf("%d", a>b); 0 Assign a value to a variable.
< Less than printf("%d", a<b); 1 = (Simple assignment), += (Add and assign), -= (Subtract
and assign), etc.
Greater than or printf("%d",
>= equal to a>=b); 0

Less than or printf("%d",


Operato
<= equal to a<=b); 1
r Description Example Output

int x=10;
Logical Operators: = Assigns value printf("%d", x); 10
Combine multiple conditions. Add and x+=5;
+= assign printf("%d", x); 15
&& (Logical AND), || (Logical OR), ! (Logical NOT).
Subtract and x-=3; printf("%d",
Operato -= assign x); 7
r Description Example Output
Multiply and x*=2; printf("%d",
int a=5,b=8; *= assign x); 20
printf("%d",
&& Logical AND (a<10 && b>5)); 1 Divide and x/=2; printf("%d",
/= assign x); 5
int a=5,b=8;
printf("%d", Modulus and x%=3;
|| Logical OR (a<10 || b>5)); 1 %= assign printf("%d", x); 1
& (Bitwise AND), | (Bitwise OR), ^ (Bitwise XOR), ~ (Bitwise
NOT), << (Left shift), >> (Right shift).
Increment/Decrement Operators:
Increase or decrease the value of a variable by 1.
++ (Increment), -- (Decrement). Can be used in prefix or Operato
postfix form. r Description Example Output

int a=5,b=3;
Operato printf("%d", a &
r Description Example Output & Bitwise AND b); 1
Pre-increment int a=5,b=3;
(Increase int a=5; printf("%d", a | `printf("%
=++a before use) printf("%d", ++a); 6 | `Bitwise OR b); d", a)
Post-increment printf("%d", a ^
(Increase after int a=5; 5 (then ^ Bitwise XOR b); 6
a++ use) printf("%d", a++); a=6)
~ Bitwise NOT printf("%d", ~a); -6
Pre-decrement
(Decrease int a=5; printf("%d", a <<
--a before use) printf("%d", --a); 4 << Left Shift 1); 10
Post- printf("%d", a >>
decrement >> Right Shift 1); 2
(Decrease int a=5; 5 (then
a-- after use) printf("%d", a--); a=4)
16. Explain in detail about various Built in Functions in
C.
Bitwise Operators:
Built-in functions (or standard library functions) are pre-
Perform operations on individual bits of an integer. defined functions provided by the C compiler, stored in
header files. They perform common tasks, simplifying
programming.
17. What are the different unconditional/Jump
stdio.h (Standard Input/Output): Statements and explain them with examples?
printf(): Prints formatted output to the console. Unconditional jump statements transfer the program control
from one part of the code to another without checking any
scanf(): Reads formatted input from the console. condition.
getchar(), putchar(): For single character I/O. break:
stdlib.h (Standard Library): Terminates the innermost loop ( for, while, do-while) or
switch statement immediately.
malloc(), calloc(), realloc(): Used for dynamic memory
allocation. Control passes to the statement following the loop/switch.
free(): Deallocates memory. Example:
exit(): Terminates the program. for (int i = 0; i < 10; i++) {
string.h (String Handling): if (i == 5) break; // Exits the loop when i is 5
strcpy(): Copies a string. printf("%d ", i);
strcat(): Concatenates two strings. }
strlen(): Returns the length of a string. continue:
strcmp(): Compares two strings. Skips the rest of the current iteration of the loop and
proceeds to the next iteration.
math.h (Mathematical Operations):
Example:
sqrt(): Calculates the square root.
for (int i = 0; i < 5; i++) {
pow(): Calculates a number raised to a power.
sin(), cos(), tan(): Trigonometric functions.
if (i == 2) continue; // Skips the printf() statement when i is 18. Explain in detail about if, if-else, nested if, if-else-if
2 ladder, switch case with suitable examples.
printf("%d ", i); if statement
} The if statement executes a block of code only if a specified
condition is true.
// Output: 0 1 3 4
if (condition) {
goto:
// code to be executed if condition is true
Transfers control to a labelled statement unconditionally. Its
use is generally discouraged as it can lead to complex and }
hard-to-read "spaghetti code."
Example:
Example:
int num = 10;
goto label;
if (num > 0) {
printf("This will not be printed.\n");
printf("Number is positive.\n");
label:
}
printf("This is the jump target.\n");
if-else statement
return:
The if-else statement executes one block of code if the
Terminates the execution of a function and returns control condition is true and another block if it is false.
to the calling function. It can also return a value.
if (condition) {
Example:
// code if condition is true
int add(int a, int b) {
} else {
return a + b; // Returns the sum of a and b
// code if condition is false
}
} if (a > b) {
Example: if (a > c) {
int num = -5; printf("a is the greatest.\n");
if (num > 0) { }
printf("Positive.\n"); } else {
} else { if (b > c) {
printf("Not positive.\n"); printf("b is the greatest.\n");
} } else {
nested if statement printf("c is the greatest.\n");
A nested if is an if statement inside another if or else block. }
It is used to check multiple conditions sequentially.
}
if (condition1) {
if-else-if ladder
// ...
The if-else-if ladder is used to check a series of conditions.
if (condition2) { The code block of the first true condition is executed, and
the rest are skipped.
// code if both conditions are true
if (condition1) {
}
// code
}
} else if (condition2) {
Example:
// code
int a = 10, b = 20, c = 5;
} else if (condition3) {
// code break;
} else { case constant2:
// code // code
} break;
Example: default:
int score = 85; // code
if (score >= 90) { }
printf("Grade A\n");
} else if (score >= 80) { Example:
printf("Grade B\n"); char grade = 'B';
} else { switch (grade) {
printf("Grade C\n"); case 'A':
} printf("Excellent!\n");
switch statement break;
The switch statement allows a variable to be tested for case 'B':
equality against a list of constant values (cases).
printf("Good!\n");
switch (expression) {
break;
case constant1:
default:
// code
printf("Try again.\n");
}

19. Solve Towers of Hanoi problem by using Recursive


function concepts in C.

The Towers of Hanoi is a classic recursion problem.


The objective is to move all disks from a source tower
to a destination tower, using an auxiliary tower, with
three rules:

1. Only one disk can be moved at a time.


2. Each move consists of taking the upper disk
from one stack and placing it on top of another
stack.
3. No disk may be placed on top of a smaller disk.

Moving 3 disks from A to C via B

When n = 3, source = A, destination = C, auxilliary = B, 1. Disk 3 from A to C.


2. Disk 2 from A to B.
3. Disk 3 from C to B → Disk 2 and 3 Placed at B.
4. Disk 1 from A to C → Disk 1 Placed at C.
5. Disk 3 from B to A.
6. Disk 2 from B to C
7. Disk 1 from A to C → Disk 2 and 3 Placed at C.
Algorithm: }

int main() {
1. Move n-1 disks from the source to the auxiliary
tower. int n = 3; // Number of disks
2. Move the nth disk from the source to the
destination tower. towersOfHanoi(n, 'A', 'C', 'B'); // A: Source, C:
3. Move n-1 disks from the auxiliary to the Destination, B: Auxiliary
destination tower.
return 0;

}
C Program:
Output:
#include <stdio.h>
The output for the provided C program will be a series
void towersOfHanoi(int n, char from_rod, char to_rod, of instructions detailing the steps required to move 3
char aux_rod) { disks from Rod 'A' to Rod 'C', using Rod 'B' as an
auxiliary rod:
if (n == 1) {
Move disk 1 from rod A to rod C
printf("Move disk 1 from rod %c to rod %c\n",
from_rod, to_rod); Move disk 2 from rod A to rod B

return; Move disk 1 from rod C to rod B

} Move disk 3 from rod A to rod C

towersOfHanoi(n - 1, from_rod, aux_rod, to_rod); Move disk 1 from rod B to rod A

printf("Move disk %d from rod %c to rod %c\n", n, Move disk 2 from rod B to rod C
from_rod, to_rod);
Move disk 1 from rod A to rod C
towersOfHanoi(n - 1, aux_rod, to_rod, from_rod);
20. Solve Swapping of two numbers by swapByValue(x, y);
Parameters passing methods in C (Call by Value &
Call by Reference). printf("After swap (Call by Value): x = %d, y = %d\
n", x, y); // x and y are unchanged
Call by Value
return 0;
In call by value, a copy of the actual parameters is
passed to the formal parameters of the function. Any }
changes made to the formal parameters inside the
function do not affect the actual parameters. Output

c program Before swap (Call by Value): x = 10, y = 20

#include <stdio.h> Inside function (Call by Value): a = 20, b = 10

void swapByValue(int a, int b) { After swap (Call by Value): x = 10, y = 20

int temp = a;
Call by Reference
a = b;
In call by reference, the address of the actual
b = temp; parameters is passed to the function. This means the
formal parameters are pointers that hold the memory
printf("Inside function (Call by Value): a = %d, b = addresses of the actual parameters. Changes made to
%d\n", a, b); the values at these addresses will affect the original
variables.
}
c program
int main() {
#include <stdio.h>
int x = 10, y = 20;
void swapByReference(int *a, int *b) {
printf("Before swap (Call by Value): x = %d, y = %d\
n", x, y); int temp = *a;
*a = *b;

*b = temp; 21. Explain in detail about Types of Function

printf("Inside function (Call by Reference): *a = %d, In C programming, functions are divided into four
*b = %d\n", *a, *b); types based on:

} Whether they take arguments (inputs), and

int main() { Whether they return a value (output).

int x = 10, y = 20; 1. Function with No Arguments and No Return Value

printf("Before swap (Call by Reference): x = %d, y = 🔹 Explanation:


%d\n", x, y);
This type of function does not take any input.
swapByReference(&x, &y); // Passing addresses of
x and y It also does not return any result.

printf("After swap (Call by Reference): x = %d, y = Used for simple tasks like printing a message.
%d\n", x, y); // x and y are swapped
💻 Example:
return 0;
#include <stdio.h>
}
void printMessage() {
Output
printf("Hello! Welcome to C Programming.\n");
Before swap (Call by Reference): x = 10, y = 20
}
Inside function (Call by Reference): *a = 20, *b = 10
int main() {
After swap (Call by Reference): x = 20, y = 10
printMessage(); // Function call
return 0; return 0;

} }

Output: Output:

Hello! Welcome to C Programming. Sum = 15

2. Function with Arguments but No Return Value 3. Function with No Arguments but With Return Value

🔹 Explanation: 🔹 Explanation:

The function takes input values (arguments). This type of function does not take input.

It does not return any result. It returns a value to the main function.

Used when we only need to display or process something. Used when the result is generated inside the function.

💻 Example: 💻 Example:

#include <stdio.h> #include <stdio.h>

void printSum(int a, int b) { int getNumber() {

printf("Sum = %d\n", a + b); return 100;

} }

int main() { int main() {

printSum(5, 10); int num = getNumber();


printf("The number is %d\n", num); printf("Sum = %d\n", result);

return 0; return 0;

} }

Output: Output:

The number is 100 Sum = 30

4. Function with Arguments and With Return Value

🔹 Explanation: 22. Explain in detail about Scope and Life Time of


Variables.
This function takes input values.
Scope of Variables
It returns a computed value to the main program.
Scope defines the region of a program where a
Most commonly used type of function. variable is accessible. In C, there are four main types
of scope:
💻 Example:

#include <stdio.h> ● Local Scope (Block Scope): Variables


declared inside a function or a block (e.g.,
int add(int a, int b) { inside {} braces of an if statement or a loop)
have local scope. They can only be accessed
return a + b; within that block.
○ Example: int func() { int x = 10; } (x is
}
local to func).
int main() { ● Function Scope: Labels used with the goto
statement have function scope. They are visible
int result = add(10, 20); throughout the entire function, regardless of
where they are declared.
● File Scope (Global Scope): Variables ○ Example: static int count = 0;
declared outside any function have file scope. ● External Lifetime: The lifetime of global
They can be accessed from any function within variables. They are created before the
the same file from the point of their declaration. program's main() function is called and persist
○ Example: int global_var = 10; int main() until the program terminates.
{ ... } ● Dynamic Lifetime: The lifetime of memory
● Function Prototype Scope: Variable names in allocated dynamically using functions like
a function prototype are only visible within the malloc(). This memory persists until it is
prototype itself and are optional. The compiler explicitly freed using free(). It is stored on the
only needs the data types. heap.
○ Example: int add(int a, int b); (a and b
have prototype scope).

Life Time of Variables

Lifetime refers to the period during which a variable


exists in memory.

● Automatic Lifetime: The lifetime of local


variables. They are created when their block is
entered and destroyed when the block is
exited. They are stored on the stack.
● Static Lifetime: The lifetime of a variable with
the static storage class. A static variable is
created only once when the program starts and
is destroyed only when the program terminates.
Its value is preserved across function calls.

You might also like