Question bank
Question Bank - IA1
| SL. No | Question |
|---|---|
| 1 | Explain System development model. |
| 2 | Difference between compiler and interpreter. |
| 3 | Explain structure of C program. |
| 4 |
Explain storage class specifier: a) extern b) static c) register d) auto |
| 5 | Explain any 5 operators in C. |
| 6 | Describe data types and variables along with rules. |
| 7 | Discuss local and global declaration. |
| 8 | Explain four scopes of C. |
| 9 | Explain input and output functions. |
| 10 | Distinguish between while and do-while with syntax. |
| 11 | Write a C program to simulate a calculator using switch statement. |
| 12 | Distinguish between break and continue. |
| 13 | Write a C program for quadratic equation. |
| 14 | Explain Jump statements. |
| 15 | Write a C program to find greatest of 3 numbers. |
| 16 | Explain for loop with syntax and flowchart. |
| 17 | With syntax of array, explain 3 types of array initialization. |
| 18 | Write a C program for transpose of matrix. |
Tip: Review these questions before exams — they cover key concepts from Module 1, including syntax, logic building, and core programming fundamentals in C.
1. System Development Life Cycle (SDLC)
The System Development Life Cycle (SDLC) is a step-by-step process used to design, develop, test, and maintain high-quality software systems. It ensures that software is created in a structured, organized, and efficient way.
Why SDLC is Important:
- Provides a systematic approach to software development.
- Reduces the chances of project failure.
- Improves planning, documentation, and testing.
- Ensures that user requirements are clearly defined and met.
- Allows for better communication among teams and stakeholders.
The Waterfall Model
One of the earliest and most popular SDLC models is the Waterfall Model. It follows a linear and sequential flow — meaning each phase must be completed before the next one begins.
(Waterfall Model Diagram)
Phases of the Waterfall Model:
-
1. System Requirements:
- Define what the system should do.
- Gather input from users and stakeholders.
- Output: A clear list of system goals and user requirements.
-
2. System Analysis:
- Analyze the system requirements in detail.
- Identify possible solutions and select the best one.
- Focus on “what” the system must achieve, not “how.”
-
3. System Design:
- Plan “how” the system will be built.
- Design data flow, architecture, user interfaces, and databases.
- Decide on hardware, software, and communication needs.
-
4. Coding (Implementation):
- Actual programs are written using a programming language (like C).
- Each module is coded, compiled, and tested individually.
- This is the phase explained in this book!
-
5. Testing:
- All modules are combined and tested as a complete system.
- Ensures the software works correctly and meets requirements.
- Defects and bugs are identified and corrected.
-
6. Deployment:
- The finished system is installed and delivered to the users.
- Training and documentation are provided for smooth usage.
-
7. Maintenance:
- Continuous support after deployment.
- Fix bugs, add updates, and improve performance over time.
- Keeps the system reliable and up to date.
Iteration in the Waterfall Model:
- Although it seems linear, phases often overlap in real life.
- Developers may need to go back to a previous phase if errors are found.
- This backflow is shown as “feedback arrows” in the waterfall diagram.
Important Note:
- If major issues are discovered late (during testing or coding), the project can fail.
- In large projects, this can mean millions of dollars and years of effort lost.
- That's why proper planning, analysis, and design are critical.
2. Compilers vs. Interpreters
Understanding the difference between compilation and interpretation is crucial in programming. Both processes translate human-readable source code into a form that a computer can execute, but they differ significantly in how and when this translation occurs. The C language, being a compiled language, relies heavily on the efficiency of the compiler.
Comparison Table:
| Aspect | Compiler | Interpreter |
|---|---|---|
| Execution Method | Translates the entire program into machine code before execution. | Translates and executes code line by line at runtime. |
| Performance | Faster execution since the entire code is pre-compiled to machine code. | Slower execution due to line-by-line translation and execution. |
| Development Cycle | Edit → Compile → Run |
Edit → Run |
| Error Detection | Reports all syntax and semantic errors at compile-time before running the program. | Stops execution when an error occurs, reporting one error at a time. |
| Portability | Produces machine-specific executables (platform-dependent). | Same source code can often run on multiple platforms (platform-independent). |
| Memory Usage | More efficient — optimized binary code uses less memory during execution. | Less efficient — interpreter must remain in memory while executing. |
| Output Type |
Generates an independent executable file (e.g.,
.exe).
|
No separate executable; runs directly from source. |
| Examples | C, C++, Rust, Go, Java (JIT hybrid) | Python, JavaScript, PHP, Ruby |
Note: Modern programming languages like Java and Python often use a hybrid approach — code is first compiled into an intermediate form (bytecode) and then interpreted or just-in-time (JIT) compiled during execution.
3. Structure of a C Program or Basic Concepts of a C Program
All C programs consist of one or more functions, with
main() being the essential starting point.
General Form of a C Program:
[Comments]
[Preprocessor Directives]
[Global Declarations]
[Function Declarations]
[Function Definitions]
main()
{
[Declaration Section]
[Executable Section]
}
-
Comments
- At the beginning of each program is a comment with a short description of the problem to be solved.
- We can use the comments anywhere in the program.
-
The comments section is optional.
Ex: 1. /* Program1: To find the sum of two numbers*/
2. // Program2: To calculate the area and perimeter of circle - The symbol /* and ends with */ represents the multiline comment.
- The symbol // can also be used for representing single line comment.
-
Preprocessor directives
- The preprocessor statements start with # symbol.
-
These statements instruct the compiler to include some of the
files in the beginning of the program.
Ex: #include<stdio.h>
#include<math.h>
are the files that the compiler includes in the beginning of the program. - The line containing #include<stdio.h> tells the compiler to allow our program to perform standard input and output 'stdio' operations.
- The '#include' directive tells the compiler that we will be using parts of the standard function library.
- Information about these functions is contained in a series of 'header files' (stdio.h). .h says this file is a header file.
- The pointed brackets < and > tell the compiler the exact location of this header file.
-
Using the preprocessor directives the user can define the
constants also.
Ex: #define PI 3.142
-
Global Declarations
- The variables that are declared above (before) the main program are called global variables.
- The global variables can be accessed anywhere in the main program and in all the other functions.
-
Function declarations and Definitions
- In this section the functions are declared.
- Immediately after the functions are declared, the functions can be defined.
-
The program header: main()
- Every program must have a main function.
- Always the C program begins its execution from main.
-
Body of the program
-
After the header or top lines is a set of braces ({ and })
containing a series of 'C' statements which comprise the 'body'-
this is called the action portion of the program.
#include <stdio.h>
main(void) {
/* action portion of the program*/
}
- The global variables can be accessed anywhere in the main program and in all the other functions.
-
After the header or top lines is a set of braces ({ and })
containing a series of 'C' statements which comprise the 'body'-
this is called the action portion of the program.
-
Declaration section
- The variables that are used inside the function should be declared in the declaration section.
-
For example, consider the declaration shown below:
int sum=0;
int a;
float b;
Here, the variable sum is declared as an integer variable and it is initialized to zero.
The variable a is declared as an integer variable whereas the variable b is declared as a floating point variable.
-
Executable section
- They represent the instructions given to the computer to perform a specific task.
- The instructions can be input/output statements, expressions to be evaluated, simple assignment statements, control statements such as if statement, for statement etc.
-
Each executable statement ends with “;”. Example: Write a C
program to display “Hello World”.
#include <stdio.h>
void main(void) {
printf(“Hello World”);
}
- The block is super important
- first list the items, comments, Preprocessor Directives and all the other
- then write 2 line description of each
4. Storage Class Specifiers in C
Storage classes define how and where a variable is stored, its scope (where it can be used), and its lifetime (how long it exists).
- There are four main storage classes in C:
autoregisterstaticextern
1. auto
- Default for local variables inside functions.
- Created when function starts, destroyed when it ends.
- Stored in memory (RAM).
- No need to write
autoexplicitly.
auto int a = 10; // same as int a = 10;
printf("%d", a);
}
2. register
- Stored in CPU register for faster access.
- Used for frequently used variables like loop counters.
- You cannot use
&to get its address.
for(i=0; i<10; i++) printf("%d ", i);
3. static
- Remembers its value between function calls.
- Local static → keeps value across calls.
- Global static → visible only inside the file.
static int count = 0;
count++;
printf("%d ", count);
}
4. extern
- Used to declare a variable defined in another file.
- Does not create new memory.
- Used for sharing global variables between files.
int num = 10;
// file2.c
extern int num;
printf("%d", num);
Summary
| Keyword | Scope | Lifetime | Stored In | Use |
|---|---|---|---|---|
| auto | Local | Function runs | Memory | Default local variable |
| register | Local | Function runs | CPU Register | Fast access |
| static | Local/File | Entire program | Memory | Retain value / Hide variable |
| extern | Global | Entire program | Memory | Share variable across files |
5. Explain Any 5 Operators in C
Operators in C are special symbols that perform specific operations on operands (variables or values). They are fundamental for performing calculations, making decisions, and controlling program flow. Below are five important types of operators with detailed explanations and examples.
-
Arithmetic Operator (
+,-,*,/,%)- Used to perform basic mathematical operations on numerical values.
- Common arithmetic operators are:
Operator Meaning Example +Addition a + b→ Addsaandb-Subtraction a - b→ Subtractsbfroma*Multiplication a * b→ Multipliesaandb/Division a / b→ Dividesabyb(integer division if both are integers)%Modulus a % b→ Gives the remainder after divisionint a = 10, b = 3;
printf("%d \n", a + b); // 13
printf("%d \n", a % b); // 1 -
Relational Operator (
>,<,>=,<=,==,!=)-
Used to compare two values. The result is either
true (1)orfalse (0).
Operator Meaning Example >Greater than a > b<Less than a < b>=Greater than or equal to a >= b<=Less than or equal to a <= b==Equal to a == b!=Not equal to a != bint x = 5, y = 8;
printf("%d \n", x < y); // 1 (true)
printf("%d \n", x == y); // 0 (false) -
Used to compare two values. The result is either
-
Logical Operator (
&&,||,!)- Used to combine multiple conditions or invert logical results.
- In C, nonzero values are considered true and zero as false.
Operator Meaning Example &&Logical AND (a < b) && (b < 20)||Logical OR (a > b) || (b < 20)!Logical NOT !(a == b)int a = 5, b = 10;
printf("%d \n", (a < b) && (b < 20)); // 1
printf("%d \n", !(a == 5)); // 0 -
Assignment Operator (
=,+=,-=,*=,/=,%=)- Used to assign or modify the value of a variable.
- Compound assignment operators combine an operation with assignment for brevity.
Operator Meaning Example =Assigns value a = 10;+=Add and assign a += 5;→a = a + 5;-=Subtract and assign a -= 3;→a = a - 3;*=Multiply and assign a *= 2;→a = a * 2;/=Divide and assign a /= 2;→a = a / 2;%=Modulus and assign a %= 3;→a = a % 3;int x = 10;
x += 5; // x = 15
x *= 2; // x = 30 -
Increment/Decrement Operator (
++,--)- Used to increase or decrease the value of a variable by 1.
-
Can be used in:
-
Prefix form (
++x,--x): changes value before use -
Postfix form (
x++,x--): changes value after use
-
Prefix form (
Operator Meaning Example ++Increment by 1 x++or++x--Decrement by 1 x--or--xint x = 5;
printf("%d ", ++x); // 6
printf("%d", x--); // 6, then x = 5
Summary: C provides a wide range of operators that make programs concise and efficient. They enable developers to perform calculations, make comparisons, control logic, and manipulate data with ease.
6. Identifiers and Variables in C
Identifiers
Definition: Identifiers are names given to variables, functions, labels, and other user-defined elements.
Variables
A variable is a named memory location that stores a value which may change during program execution. Every variable must be declared before use.
Rules:- Must begin with a letter (a-z, A-Z) or an underscore (_).
- Subsequent characters may include letters, digits (0-9), or underscores.
-
Cannot include special symbols like
!,@, or spaces. -
Identifiers are case-sensitive, so
count,Count, andCOUNTare all distinct. -
Keywords such as
int,while,forcannot be used as identifiers. -
Correct Examples:
count,test23,high_balance -
Incorrect Examples:
1count,hi!there,high...balance
Examples of Variable Declarations:
int i, j, l;
short int si;
unsigned int ui;
double balance, profit, loss;
7. Discuss Local and Global Declaration
In C programming, variables can be declared either locally inside a function or globally outside all functions. The place of declaration decides where the variable can be accessed.
1. Local Variables
- Declared inside a function or block.
- Can be used only within that function.
- Memory is allocated when the function is called and freed when it ends.
- Not known to other functions.
#include <stdio.h>
int main() {
int localVar = 20; // Local variable declaration
printf("Inside main() - localVar = %d \n", localVar);
return 0;
}
Output:
Inside main() - localVar = 20
2. Global Variables
- Declared outside all functions (usually at the top of the program).
- Can be accessed by any function within the same program file.
- Memory remains allocated throughout program execution.
- Useful for sharing data between multiple functions.
int num = 20; // Global variable
void show() {
printf("%d", num); // Accessible here
}
int main() {
show();
printf("%d", num); // Also accessible here
return 0;
}
Example Program:
- Local variables — exist only within a function.
- Global variables — accessible from all functions.
8. The Four Scopes in C
In C programming, every variable or constant has a scope — which defines where in the program it can be accessed or modified. There are four types of scopes in C:
| Scope | Meaning |
|---|---|
| File Scope | Variables declared outside all functions. Visible throughout the file — commonly known as global variables. |
| Block Scope |
Variables declared inside a block (within { }). They
are accessible only inside that block or nested blocks.
|
| Function Prototype Scope | Applies to variables declared in function prototypes. Visibility is limited only to that prototype. |
| Function Scope |
Applies only to goto labels. Labels are visible
throughout the function where they are defined.
|
File Scope
-
A variable declared using
staticoutside all functions has file scope. - Such a variable is accessible anywhere within the same file but not visible to other files.
- Commonly used to restrict global variable usage within a single file.
static int count = 0; // File scope variable
void increment() {
count++;
printf("Count = %d \n", count);
}
int main() {
increment();
increment();
return 0;
}
Block Scope
- Declared inside a block of code enclosed by
{ }. - Exists only until the block is active; destroyed once the control exits.
- Also known as local variables.
- Variables in inner blocks can mask variables of the same name in outer blocks.
- Variables declared in an outer block are accessible in nested blocks (if not re-declared).
#include <stdio.h>
int main() {
int x = 10; // outer block variable
{
int y = 20; // inner block variable
printf("x = %d, y = %d \n", x, y);
}
// printf("%d", y); ❌ Error: y not accessible here
return 0;
}
Function Scope
-
Applies only to labels used with the
gotostatement. - A label is visible from the beginning to the end of the function in which it appears.
- Two labels with the same name cannot exist within one function.
void main() {
int i = 1;
loop: // label with function scope
printf("%d \n", i);
i++;
if (i <= 3)
goto loop; // jump to label
}
Program Scope (Global Scope)
- Variables declared outside all functions have program or global scope.
- Accessible from any function within the program file.
- Memory is allocated at the start of the program and released only after it ends.
- If a local variable has the same name, it hides (masks) the global one inside that function.
#include <stdio.h>
int x = 10; // Global variable
void print();
void main() {
printf("Global x in main() = %d \n", x);
int x = 2; // Local variable shadows global x
printf("Local x in main() = %d \n", x);
print();
}
void print() {
printf("Global x in print() = %d \n", x);
}
Output:
Global x in main() = 10
Local x in main() = 2
Global x in print() = 10
Summary:
- Block Scope: Inside { } — exists only while in that block.
-
Function Scope: For
gotolabels — visible throughout the function. - Program Scope: Global variables — visible to all functions.
-
File Scope:
staticglobal variables — visible only within the same file.
9. Explain Input and Output Functions in C
Input and Output functions in C are used to take data from the user
and display results on the screen. These are available in the
stdio.h library and handle character, string, and
formatted data efficiently.
Common Input Functions:
-
scanf()- Reads formatted input (numbers, characters, strings). -
gets()- Reads a line of text including spaces (deprecated in modern C). -
getchar(),getch(),getche()- Read single characters.
Common Output Functions:
-
printf()- Displays formatted output on the screen. -
puts()- Displays a string followed by a newline. -
putchar()- Prints a single character on the screen.
Reading Strings
If we declare a string as char str[100];, we can read it
in three ways:
1. Using scanf()
- Syntax:
scanf("%s", str); - No
&symbol needed for strings. - Stops reading when it encounters a space.
- Cannot read full sentences with spaces.
printf("Enter a word: ");
scanf("%s", str);
printf("You entered: %s", str);
2. Using gets()
- Syntax:
gets(str); - Reads an entire line including spaces.
-
Automatically adds a null character (
'\0') at the end. - Overcomes the limitation of
scanf().
printf("Enter a sentence: ");
gets(str);
printf("You entered: %s", str);
3. Using getchar() Repeatedly
- Reads one character at a time until a terminating character is found.
- Each character is stored in an array.
int i = 0;
char ch;
printf("Enter text (end with *): ");
ch = getchar();
while(ch != '*') {
str[i] = ch;
i++;
ch = getchar();
}
str[i] = '\0';
printf("You entered: %s", str);
Writing Strings
Strings can be displayed using three main methods:
1. Using printf()
- Syntax:
printf("%s", str); - Used to print formatted strings.
-
Supports width and precision (e.g.
printf("%5.3s", str);prints first 3 characters). -
Left justify using a minus sign (e.g.
printf("%-5.3s", str);).
printf("%s\n", str);
printf("%5.3s\n", str);
printf("%-10.4s", str);
2. Using puts()
- Syntax:
puts(str); - Automatically adds a newline after the string.
- Simpler than
printf()for plain string output.
puts(str);
3. Using putchar() Repeatedly
-
Prints each character one by one until null character
(
'\0') is reached.
int i = 0;
while(str[i] != '\0') {
putchar(str[i]);
i++;
}
Summary:
Input and output functions are essential for user interaction in C.
Functions like scanf(), printf(),
gets(), puts(), getchar(),
and putchar() make data exchange between user and
program easy and flexible.
10. Distinguish Between while and
do-while Loop
Both while and do-while loops are used for
repetitive execution of statements based on a condition. However, they
differ in how and when the condition is tested.
while Loop
- Executes a set of statements repeatedly as long as a specified condition is true.
- Condition is checked before entering the loop → called an Entry-Controlled Loop.
- If the condition is false initially, the loop body is skipped.
- Control moves to the statement immediately after the loop once the condition becomes false.
(while-Loop)
while Loop - Syntax
Statement(s);
}
do-while Loop
- Executes a set of statements repeatedly at least once.
- The condition is tested after executing the loop body → called an Exit-Controlled Loop.
-
Unlike
forandwhileloops, which test the condition at the beginning, thedo-whileloop tests it at the end. - The loop continues as long as the test expression is true.
(Flowchart-while-Loop)
do-while Loop - Syntax
Statement(s);
} while (condition);
Comparison Between while and do-while
| Aspect | while Loop |
do-while Loop |
|---|---|---|
| 1. Type of Loop | Entry-controlled (condition tested first). | Exit-controlled (condition tested last). |
| 2. Execution Guarantee | May execute zero times if the condition is false initially. | Executes at least once even if the condition is false. |
| 3. Syntax Difference |
while(condition) {
Statements; } |
do {
Statements; } while(condition); |
| 4. Control Flow | Checks condition first → executes body only if true. | Executes body first → then checks condition for repetition. |
| 5. Semicolon Usage | No semicolon after the while block. |
Ends with a semicolon (;). |
| 6. Example |
int i = 1;
while(i <= 5) { printf("%d ", i); i++; } |
int i = 1;
do { printf("%d ", i); i++; } while(i <= 5); |
| 7. Use Case | When the number of iterations is uncertain and depends on a condition checked first. | When the loop body must execute at least once regardless of the condition. |
Summary:
while is a pre-test loop (checks
condition before execution), while do-while is a
post-test loop (checks condition after execution).
11. Calculator Using switch Statement
int main() {
int num1, num2;
char option;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
printf("Choose operation (+, -, *, /): ");
scanf(" %c", &option);
switch(option) {
case '+':
printf("Sum = %d", num1 + num2);
break;
case '-':
printf("Difference = %d", num1 - num2);
break;
case '*':
printf("Product = %d", num1 * num2);
break;
case '/':
if(num2 != 0)
printf("Result = %d", num1 / num2);
else
printf("Division by zero not allowed");
break;
default:
printf("Invalid operation");
}
return 0;
}
12. Difference Between break and continue
Both break and continue are used to control
loop execution, but they behave differently:
| Aspect | break |
continue |
|---|---|---|
| Purpose | Terminates the loop completely and exits it. | Skips the current iteration and continues with the next iteration of the loop. |
| Scope |
Can be used in for, while,
do-while, and switch statements.
|
Can be used only in loops (for, while,
do-while).
|
| Effect | Exits the loop immediately. | Skips remaining statements in the current iteration, then continues with the next iteration. |
| Example |
for(int i=1; i<=5; i++) {
if(i==3) break; printf("%d ", i); } // Output: 1 2 |
for(int i=1; i<=5; i++) {
if(i==3) continue; printf("%d ", i); } // Output: 1 2 4 5 |
Summary: Use break to exit a loop
entirely, and continue to skip the current iteration
but keep the loop running.
13. C Program to Find Roots of a Quadratic Equation
This program calculates the roots of a quadratic equation of the form
ax² + bx + c = 0 using the discriminant method.
Code:
#include <math.h>
int main() {
double a, b, c;
double discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
if(a == 0) {
printf("Not a quadratic equation. \n");
return 0;
}
discriminant = b*b - 4*a*c;
if(discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2*a);
root2 = (-b - sqrt(discriminant)) / (2*a);
printf("Roots are real and distinct: \n");
printf("Root 1 = %.4lf \n", root1);
printf("Root 2 = %.4lf \n", root2);
} else if(discriminant == 0) {
root1 = -b / (2*a);
printf("Roots are real and equal: \n");
printf("Root = %.4lf \n", root1);
} else {
realPart = -b / (2*a);
imagPart = sqrt(-discriminant) / (2*a);
printf("Roots are complex and imaginary: \n");
printf("Root 1 = %.4lf + %.4lfi \n", realPart, imagPart);
printf("Root 2 = %.4lf - %.4lfi \n", realPart, imagPart);
}
return 0;
}
Compile and Run:
Sample Output:
Roots are real and distinct:
Root 1 = 2.0000
Root 2 = 1.0000
Explanation: - Discriminant = b² - 4ac
- >0 → Two distinct real roots
- =0 → Two equal real roots
- <0 → Two complex roots
14. Jump Statements in C
Jump statements are used to alter the flow of control in a program by jumping to another part of the code.
Types of Jump Statements:
-
break:
-
Used to exit from a loop (
for,while,do-while) orswitchstatement immediately. - Control passes to the statement immediately after the loop or switch.
- Example:
for(int i=1; i <=10; i++) {
if(i==5) break;
printf("%d ", i);
} -
Used to exit from a loop (
-
continue:
- Skips the current iteration of a loop and moves to the next iteration.
- Useful to skip some part of loop when a condition is met.
- Example:
for(int i=1; i <=10; i++) {
if(i%2==0) continue;
printf("%d ", i);
} -
goto:
- Transfers control unconditionally to a labeled statement within the same function.
- Generally discouraged, but can be used for error handling or exiting nested loops.
- Example:
int i=1;
loop:
printf("%d ", i);
i++;
if(i<=5) goto loop; -
return:
- Exits from a function and optionally returns a value to the calling function.
- Example:
int sum(int a, int b) {
return a+b;
}
Summary: Jump statements control the flow of a program by allowing early exit, skipping iterations, transferring control, or returning values.
15. Find Greatest of 3 Numbers
This program finds the largest of three numbers entered by the user
using if-else statements.
Program:
int main() {
int num1, num2, num3;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
if(num1 >= num2 && num1 >= num3)
printf("Greatest number is %d", num1);
else if(num2 >= num1 && num2 >= num3)
printf("Greatest number is %d", num2);
else
printf("Greatest number is %d", num3);
return 0;
}
Sample Output:
Greatest number is 25
if-else to determine the largest.
16. for Loop (Counter-Controlled Loop)
- Executes a set of statements repeatedly for a specific number of times.
- Also called an entry-controlled loop or pretest loop.
-
Syntax:
for(initialization; test expression; increment/decrement) {
statement1;
statement2;
statement3;
}
statement x; -
Working Principle:
- Initialization: Set the starting value of loop variable.
- Test expression: Evaluated before each iteration; if true, loop executes, else control moves out.
- Increment/Decrement: Updates loop variable after each iteration.
-
Infinite Loop: Omitting the test expression creates
an infinite loop.
Example:for(i=0;;i++)
{
...
}
(flowchart-for-Loop-Flow-Diagram)
Examples:
-
Print natural numbers 1 to 10:
for(int i=1;i<=10;i++) {
printf("%d \n", i);
} -
Factorial of a number:
int fact=1,n; scanf("%d",&n);
for(int i=1;i<=n;i++) {
fact*=i;
}
printf("Factorial=%d", fact);
17. Explain 3 types of array initialization
Introduction
An array is a collection of similar data elements stored under a single name. These elements all have the same data type and are stored in consecutive memory locations. Each element is identified by a unique index (subscript), which represents its position in the array.
(Arrays-in-C)
When an array is declared or memory is allocated, its elements may contain garbage values. Therefore, it is important to initialize the array with meaningful values.
There 3 ways Storing Values in Arrays
- When initializing, provide a value for every element in the array.
- Inputting Values from the Keyboard
- Assigning Values to Individual Elements
1. Initializing Arrays during Declaration
- The elements of an array can be initialized at the time of declaration, just like any other variable.
- When initializing, provide a value for every element in the array.
-
Syntax:
type array_name[size] = {list of values}; - The values are enclosed in curly brackets and separated by commas.
- It is an error to specify more values than the declared size of the array.
Examples:
int marks[5] = {90, 82, 78, 95, 88}; // 5 elements initialized
int marks[] = {98, 97, 90}; // Size automatically inferred
If fewer values are provided than the declared size, remaining elements are automatically filled with 0.
2. Inputting Values from the Keyboard
- Arrays can also be initialized by taking input from the keyboard.
-
A
for,while, ordo-whileloop is used to input values for each element.
Example:
int marks[10];
for(int i = 0; i < 10; i++) {
printf("Enter mark %d: ", i + 1);
scanf("%d", &marks[i]);
}
3. Assigning Values to Individual Elements
- You can assign or modify individual array elements using the assignment operator.
-
Example:
marks[3] = 100;assigns 100 to the fourth element. - To copy one array to another, copy each element individually using a loop.
- You can also use the loop index to assign calculated values to each element.
Examples:
// Copying one array into another
for(int i = 0; i < 5; i++) {
arr2[i] = arr1[i];
}
// Filling array with even numbers
for(int i = 0; i < 5; i++) {
arr[i] = i * 2;
}
18. Transpose of a Square Matrix
What is it?
The transpose of a matrix is obtained by
interchanging its rows and columns. That means, the element at
position [i][j] in the original matrix becomes the
element at position [j][i] in the transposed matrix.
- We use two 2D arrays — one for the original matrix and one for the result.
- Nested loops are used to interchange elements.
Program:
#include <stdio.h>
int main() {
int a[5][5], result[5][5];
int n;
printf("Enter size of square matrix: ");
scanf("%d", &n);
printf("Enter elements of the matrix:\n");
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}
// Find transpose
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
result[j][i] = a[i][j];
}
}
printf("Transpose of the matrix:\n");
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
Example Output:
Enter size of square matrix: 3
Enter elements of the matrix:
1 2 3
4 5 6
7 8 9
Transpose of the matrix:
1 4 7
2 5 8
3 6 9
Note: The transpose of a square matrix flips its rows and columns — row 1 becomes column 1, and so on.