Monday, December 22, 2025

C LAN. UNIT 4&5

 UNIT:4

1. Explain pointers with example.

Introduction

In C programming, a pointer is a variable that stores the address of another variable. Instead of holding a value directly, it points to the memory location where the value is stored.


Definition of Pointer

A pointer is a variable that stores the memory address of another variable.


Declaration of Pointer

Pointer variables are declared using the * (asterisk) symbol.

Syntax:

datatype *pointer_name;

Example:

int *p;

Address-of Operator (&)

The & operator is used to get the address of a variable.

p = &a;

Dereferencing Operator (*)

The * operator is used to access the value stored at the address held by the pointer.

*p

Example Program

#include <stdio.h>
int main()
{
    int a = 10;
    int *p;

    p = &a;

    printf("Value of a = %d\n", a);
    printf("Address of a = %u\n", &a);
    printf("Value stored in p = %u\n", p);
    printf("Value pointed by p = %d\n", *p);

    return 0;
}

Output

Value of a = 10
Address of a = 65524
Value stored in p = 65524
Value pointed by p = 10

(Note: Memory address may change every time the program runs.)


Explanation of Output

  • Value of a shows the value stored in variable a

  • Address of a shows the memory address of a

  • Value stored in p is same as address of a

  • Value pointed by p gives the value at that address, i.e., 10


Advantages of Pointers

  1. Efficient memory usage

  2. Used in dynamic memory allocation

  3. Helps in call by reference

  4. Useful for arrays and strings


Conclusion

Pointers are an important feature of C language that allow direct access to memory. They help in writing efficient and powerful programs and are widely used in advanced programming.


Q.2  Difference between array and pointer.

Difference between Array and Pointer 

  1. Array stores multiple values of the same data type.
    Pointer stores the address of a variable.

  2. Array name represents the base address of the first element.
    Pointer is a separate variable that holds an address.

  3. Array size must be specified at the time of declaration.
    Pointer does not require size at declaration.

  4. Memory for an array is allocated at compile time.
    Memory for a pointer is allocated at runtime.

  5. Array name is a constant and cannot be changed.
    Pointer value can be changed.

  6. Array elements are stored in continuous memory locations.
    Pointer can point to any memory location.

  7. Array elements are accessed using index notation like a[i].
    Pointer accesses value using dereferencing operator (*p).

  8. Array cannot directly point to another array.
    Pointer can point to another pointer or an array.

  9. Array name cannot be incremented or decremented.
    Pointer supports arithmetic operations.

  10. Array is mainly used to store data.
    Pointer is mainly used to access and manipulate memory.

Q.3 Structure program for student details. 

Answer:

A structure in C is a user-defined data type that is used to store different types of data items under a single name. It is very useful when we want to represent a record like student details, employee information, etc. Using structure improves program readability and data management.

Definition of Structure:

A structure is defined using the struct keyword followed by structure name and its members.

Structure Program for Student Details:

#include <stdio.h> #include <conio.h> struct student { int rollno; char name[20]; float marks; }; void main() { struct student s; clrscr(); printf("Enter Roll Number: "); scanf("%d", &s.rollno); printf("Enter Name: "); scanf("%s", s.name); printf("Enter Marks: "); scanf("%f", &s.marks); printf("\n--- Student Details ---\n"); printf("Roll Number : %d\n", s.rollno); printf("Name : %s\n", s.name); printf("Marks : %.2f\n", s.marks); getch(); } 

Output :

Enter Roll Number: 101 Enter Name: Pravina Enter Marks: 78.50 --- Student Details --- Roll Number : 101 Name : Pravina
Marks : 78.50

Explanation:
  1. The struct student is declared to store student information.

  2. It contains three members: roll number, name, and marks.

  3. Structure variable s is created inside the main() function.

  4. scanf() is used to accept input values from the user.

  5. printf() is used to display student details.

  6. Structure allows grouping of different data types.

  7. It helps in easy handling of large and complex data.

Conclusion:
Thus, structure in C is an efficient way to store and manage student details using a single variable.

Q.4 Explain Union. 

Answer:

A union in C is a user-defined data type that allows us to store different types of data in the same memory location. All members of a union share the same memory space, but only one member can store a value at a time. Union is mainly used when memory optimization is required.

Definition:

Union is defined using the union keyword followed by union name and its members.

Syntax:

union union_name {
    data_type member1;
    data_type member2;
    ...
};

Student Union Program

#include <stdio.h> #include <conio.h> union student { int rollno; char name[20]; float marks; }; void main() { union student s; clrscr(); printf("Enter Roll Number: "); scanf("%d", &s.rollno); printf("Roll Number : %d\n", s.rollno); printf("\nEnter Name: "); scanf("%s", s.name); printf("Name : %s\n", s.name); printf("\nEnter Marks: "); scanf("%f", &s.marks); printf("Marks : %.2f\n", s.marks); getch(); }

Program Explanation

  1. union student is declared to store roll number, name, and marks.

  2. All members of the union share the same memory location.

  3. Union variable s is declared inside void main().

  4. scanf("%d", &s.rollno) stores roll number in union memory.

  5. scanf("%s", s.name) stores name and overwrites roll number.

  6. scanf("%f", &s.marks) stores marks and overwrites name.

  7. printf() displays only the currently stored value.


Output (Sample Output)

Enter Roll Number: 101 Roll Number : 101 Enter Name: Pravina Name : Pravina Enter Marks: 78.50 Marks : 78.50

⚠️ Important Note (Very Important for Exam):
In union, all members share the same memory location.
So, only the last entered value is correctly stored.
Previous values get overwritten.

One-line Difference :

  • Structure: All members have separate memory and all values are stored.

  • Union: All members share same memory, only one value at a time.


Q.5 Swap two numbers using pointers. 

Answer:

Swapping two numbers using pointers means exchanging the values of two variables by using their memory addresses. Pointers allow a function to directly access and modify the actual values of variables.

Program: Swap Two Numbers Using Pointers

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

void swap(int *a, int *b) {
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

void main() {
    int x, y;

    clrscr();

    printf("Enter first number: ");
    scanf("%d", &x);

    printf("Enter second number: ");
    scanf("%d", &y);

    printf("\nBefore Swapping:");
    printf("\nX = %d, Y = %d", x, y);

    swap(&x, &y);

    printf("\nAfter Swapping:");
    printf("\nX = %d, Y = %d", x, y);

    getch();
}

Explanation:

  1. Pointer variables are used to store addresses of variables.

  2. swap() function takes two pointer arguments.

  3. *a and *b access the actual values using dereferencing.

  4. Temporary variable temp is used for swapping.

  5. Values are swapped inside the function.

  6. Changes reflect in main() due to call by reference.

  7. Pointers make swapping possible without returning values.


Output (Sample Output)

Enter first number: 10
Enter second number: 20

Before Swapping:
X = 10, Y = 20

After Swapping:
X = 20, Y = 10

UNIT 5: 

Q.1 Explain File Handling and File Modes. 

Answer:

File handling in C is used to store data permanently in a file instead of storing it temporarily in memory. Files help in storing large data and allow data to be read and written even after the program is closed. C provides various functions and file modes to perform file operations.


File Handling in C

File handling is the process of creating, opening, reading, writing, and closing a file using C programs.
In C, file handling is done using a FILE pointer.

Steps in File Handling:

  1. Declare a file pointer.

  2. Open a file using fopen().

  3. Perform file operations (read/write).

  4. Close the file using fclose().

File Pointer Declaration:

FILE *fp;

Opening a File:

fp = fopen("data.txt", "w");

File Modes in C

File modes specify the purpose for which a file is opened.

  1. "r" (Read mode)

    • Opens an existing file for reading.

    • File must exist.

    • Data cannot be modified.

  2. "w" (Write mode)

    • Opens a file for writing.

    • Creates a new file if it does not exist.

    • Deletes old data if file already exists.

  3. "a" (Append mode)

    • Opens a file for appending data.

    • New data is added at the end of file.

    • Old data is not deleted.

  4. "r+" (Read and Write mode)

    • Opens an existing file for both reading and writing.

    • File must exist.

  5. "w+" (Write and Read mode)

    • Opens a file for reading and writing.

    • Creates a new file or overwrites existing file.

  6. "a+" (Append and Read mode)

    • Opens a file for reading and appending.

    Data is added at the end of the file.

    Common File Handling Functions:

  • fopen() – opens a file
  • fclose() – closes a file
  • fprintf() – writes formatted data
  • fscanf() – reads formatted data
  • fgetc() / fputc() – read/write a character

Q.2 Program to Write and Read File. 

File handling in C is used to store data permanently in a file. Using file handling, we can write data into a file and later read the same data from the file.

Program: Write and Read File in C

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

void main() {
    FILE *fp;
    char ch;

    clrscr();

    /* Writing data to file */
    fp = fopen("data.txt", "w");
    if (fp == NULL) {
        printf("File cannot be opened");
        getch();
        return;
    }

    printf("Enter text (end with #): ");
    while ((ch = getchar()) != '#') {
        fputc(ch, fp);
    }
    fclose(fp);

    /* Reading data from file */
    fp = fopen("data.txt", "r");
    printf("\n\nFile Contents:\n");
    while ((ch = fgetc(fp)) != EOF) {
        printf("%c", ch);
    }
    fclose(fp);

    getch();
}

Explanation:

1. File pointer fp is declared using FILE *.
2. File is opened in write mode using fopen().
3. User input is written to file using fputc().
4. File is closed after writing using fclose().
5. File is reopened in read mode.
6. Data is read using fgetc().
7. File content is displayed on the screen.


Output (Sample Output):

Enter text (end with #): Hello GTU

File Contents:
Hello GTU

Q.3 Explain EOF and feof(). 

EOF and feof() are used in C file handling to detect the end of a file while reading data from a file.


EOF (End Of File)

EOF is a symbolic constant defined in stdio.h. It indicates that the end of a file has been reached or an error has occurred during file reading.

Use of EOF:

  • Returned by file reading functions like fgetc(), fscanf(), etc.

  • Helps in stopping the read operation when file ends.

Example:

while ((ch = fgetc(fp)) != EOF) {
    printf("%c", ch);
}

feof() Function

feof() is a file handling function used to check whether the end of a file has been reached or not.

Syntax:

feof(FILE *fp);

Use of feof():

  • Returns non-zero value if end of file is reached.

  • Returns zero if end of file is not reached.

Example:

while (!feof(fp)) {
    ch = fgetc(fp);
    printf("%c", ch);
}

Explanation Points

  1. EOF stands for End Of File.

  2. EOF is a macro defined in stdio.h.

  3. It is used as a condition to stop reading a file.

  4. feof() is a function that checks end of file status.

  5. feof() returns non-zero when file ends.

  6. EOF is compared with returned value of file functions.

  7. Both are used to control file reading operations.

Q.4 Explain Bitwise Operators 

Bitwise operators in C are used to perform operations on individual bits of integer data types. They are very useful in low-level programming, such as device drivers, encryption, and optimization tasks.


Types of Bitwise Operators

  1. AND (&)

    • Performs logical AND on each pair of bits.

    • Result bit is 1 only if both bits are 1.

    • Example: 5 & 30101 & 0011 = 0001 → Result = 1

  2. OR (|)

    • Performs logical OR on each pair of bits.

    • Result bit is 1 if any one of the bits is 1.

    • Example: 5 | 30101 | 0011 = 0111 → Result = 7

  3. XOR (^)

    • Performs logical XOR on each pair of bits.

    • Result bit is 1 if bits are different.

    • Example: 5 ^ 30101 ^ 0011 = 0110 → Result = 6

  4. Complement (~)

    • Inverts all bits of a number.

    • Example: ~50101 → 1010 (for 4-bit representation)

  5. Left Shift (<<)

    • Shifts bits to the left by specified positions.

    • Fills rightmost bits with 0.

    • Example: 5 << 10101 << 1 = 1010 → Result = 10

  6. Right Shift (>>)

    • Shifts bits to the right by specified positions.

    • Fills leftmost bits with 0 (for unsigned numbers).

    • Example: 5 >> 10101 >> 1 = 0010 → Result = 2


Example Program

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

void main() {
    int a = 5, b = 3;
    clrscr();

    printf("a = %d, b = %d\n", a, b);
    printf("a & b = %d\n", a & b);
    printf("a | b = %d\n", a | b);
    printf("a ^ b = %d\n", a ^ b);
    printf("~a = %d\n", ~a);
    printf("a << 1 = %d\n", a << 1);
    printf("a >> 1 = %d\n", a >> 1);

    getch();
}

Explanation

  1. Bitwise operators work on binary representation of numbers.

  2. AND (&) gives 1 only if both bits are 1.

  3. OR (|) gives 1 if any bit is 1.

  4. XOR (^) gives 1 if bits are different.

  5. Complement (~) flips all bits.

  6. Left shift (<<) multiplies number by 2^n.

  7. Right shift (>>) divides number by 2^n (for positive integers).

Output of Bitwise Operators :

a = 5, b = 3 a & b = 1 a | b = 7 a ^ b = 6 ~a = -6 a << 1 = 10 a >> 1 = 2

Q.5 Explain C Preprocessor Directives 

C preprocessor directives are instructions given to the compiler to process the program before actual compilation. They help in including files, defining constants, macros, and conditional compilation. Preprocessor directives start with # and are handled by the preprocessor, not by the compiler.


Types of Preprocessor Directives

  1. #include

    • Used to include header files in a program.

    • Example: #include <stdio.h> or #include "myfile.h"

  2. #define

    • Used to define constants or macros.

    • Example:

      #define PI 3.14
      #define SQUARE(x) ((x)*(x))
      
  3. #undef

    • Used to undefine a macro.

    • Example: #undef PI

  4. #ifdef / #ifndef / #endif

    • Used for conditional compilation.

    • #ifdef compiles code if the macro is defined.

    • #ifndef compiles code if the macro is not defined.

    • Example:

      #define FLAG
      #ifdef FLAG
          printf("FLAG is defined");
      #endif
      
  5. #if / #elif / #else / #endif

    • Used for conditional compilation based on expressions.

    • Example:

      #define VALUE 10
      #if VALUE > 5
          printf("Value is greater than 5");
      #else
          printf("Value is 5 or less");
      #endif
      
  6. #error

    • Generates a compilation error intentionally.

    • Example: #error "This file cannot be compiled"

  7. #pragma

    • Provides special instructions to the compiler.

    • Example: #pragma once (ensures header file is included only once)


Explanation Points

  1. Preprocessor directives are handled before compilation.

  2. They start with # and have no semicolon.

  3. #include adds header files for standard functions.

  4. #define is used to create constants or macros.

  5. Conditional directives like #ifdef and #if control compilation.

  6. #error stops compilation intentionally if needed.

  7. Preprocessor helps in code reuse, readability, and modular programming.


Conclusion

C preprocessor directives are instructions to the compiler to process code before compilation. They are used for including files, defining constants, macros, and controlling conditional compilation.




Sunday, December 21, 2025

C LANGUAGE

UNIT=1

 Q.1  Define Programming Language. Differentiate between Compiler and Interpreter.


Ans.   Define Programming Language

A Programming Language is a formal language used to write instructions (programs) that a computer can understand and execute.

                It allows programmers to communicate with the computer to perform specific tasks like calculations, data processing, file handling, and controlling hardware.

        Programming languages use syntax (rules) and semantics (meaning).

       Programs written in high-level languages (like C, C++, Java) must be translated into machine language.

C language is a high-level, structured, and procedure-oriented programming language developed by Dennis Ritchie.


》Uses of Programming Language

  To develop software and applications

   To solve real-world problems logically

    To control hardware and system resources

     To create efficient and reusable programs


》Compiler

     A Compiler is a language translator that converts the entire source code written in a high-level language (like C) into machine code at once.

      It checks all errors together after compilation.

      It generates an object code / executable file.

      Example: C compiler (GCC, Turbo C)

Working of Compiler

Source Code → Compiler → Object Code → Execution


》Interpreter

     An Interpreter is a language translator that converts one statement at a time from high-level language into machine code and executes it immediately.

      It checks errors line by line.

      No separate object code is generated.

      Example: Python interpreter

Working of Interpreter

     Source Code → Interpreter → Execution (line by line)


》Difference Between Compiler and Interpreter (Without Table)

1.Compiler translates the entire program at once, whereas interpreter translates the program line by line.

2.Compiler shows all errors after compiling the whole program, whereas interpreter shows errors immediately.

3.Compiler generates object code, but interpreter does not generate object code.

4.Programs compiled using compiler execute faster, while interpreted programs execute slower.

5.Compiler-based languages like C require compilation only once, while interpreted languages need interpreter every time.


》Conclusion

Compiler is faster and more efficient for large programs like C programs.

Interpreter is easier for debugging and learning.

C language uses a compiler, which makes it suitable for system programming and performance-critical applications.



Q.2. Explain Structure of a C Program with Diagram

   A C program follows a fixed and well-defined structure.

    Each part of a C program has a specific purpose and is written in a proper sequence.

    Understanding the structure of a C program helps in writing clear, correct, and error-free programs.


》Structure of a C Program:

      A C program is generally divided into the following parts:

●Documentation Section

●Link Section

●Definition Section

●Global Declaration Section

●main() Function

●User Defined Functions


》Diagram: Structure of a C Program




+----------------------------+

| Documentation Section      |

| (Comments)                 |

+----------------------------+

| Link Section               |

| (#include statements)      |

+----------------------------+

| Definition Section         |

| (#define statements)       |

+----------------------------+

| Global Declaration Section |

| (Global variables,         |

|  function prototypes)      |

+----------------------------+

| main() Function            |

| {                          |

|   Declaration statements   |

|   Executable statements    |

| }                          |

+----------------------------+

| User Defined Functions     |

| (Function definitions)     |

+----------------------------+


》Explanation of Each Section

1. Documentation Section

>This section contains comments.

>It is used to describe the program such as program name, author name, date, and purpose.

>Comments improve program readability.

>Comments are ignored by the compiler.

>Example:


/* Program to find sum of two numbers */


2. Link Section

>This section includes header files using #include.

>Header files provide predefined functions.

>Example: stdio.h is used for input/output functions like printf() and scanf().

>Example:


#include <stdio.h>


3. Definition Section

>This section defines constants using #define.

>Constants defined here cannot be changed during program execution.

>It helps to make programs more readable and maintainable.

>Example:

#define PI 3.14


4. Global Declaration Section

>This section declares global variables and function prototypes.

>Global variables can be accessed by all functions in the program.

>Function prototypes tell the compiler about functions used later.

>Example:

int a, b;

int add(int, int);


5. main() Function

>Execution of a C program always starts from the main() function.

>It is the most important part of a C program.

>It contains:

Declaration of local variables

Executable statements


>Example:

int main()

{

    int sum;

    sum = a + b;

    printf("%d", sum);

    return 0;

}


6. User Defined Functions

>These functions are written by the programmer.

>They are used to divide a large program into smaller parts.

>This improves modularity, reusability, and readability of code.

>They are defined outside the main() function.

>Example:


int add(int x, int y)

{

    return x + y;

}


3. Explain C Tokens with examples.

Introduction

>C Tokens are the smallest individual units of a C program.

>The C compiler breaks a program into tokens to understand and compile it.

>Every keyword, variable name, constant, operator, and special symbol in a C program is considered a token.

》Main types of C tokens are: Keywords, Identifiers, Constants, Strings, Operators, and Special Symbols.

2.Identifier – Short Explanation


An Identifier is a name given to a variable, function, array, or any other user-defined item in a C program.

Identifiers are used to identify program elements uniquely.


Examples:

sum, total_marks, main, add


Rules for Identifiers:

Must begin with a letter (a–z or A–Z) or underscore (_)

Cannot start with a digit

No spaces or special symbols allowed

Keywords cannot be used as identifiers


Example in C:

int sum; 

➡️ Here, sum is an identifier.







Q.4. Write algorithm and flowchart to find maximum of three numbers.

》An Algorithm is a finite set of step-by-step instructions used to solve a particular problem.

       It defines the logic of the program in a simple and systematic manner.


●Algorithm to Find Maximum of Three Numbers

Step 1: Start

Step 2: Read three numbers a, b, and c

Step 3: Check if a > b

    >If Yes, go to Step 4

     >If No, go to Step 6

Step 4: Check if a > c

     >If Yes, print “a is maximum”

     >If No, print “c is maximum”

Step 5: Go to Step 8

Step 6: Check if b > c

     >If Yes, print “b is maximum”

     >If No, print “c is maximum”

Step 7: Go to Step 8

Step 8: Stop


》A Flowchart is a graphical representation of an algorithm.

It uses standard symbols to represent different steps like input, processing, decision, and output.



(DRAW Shapes (LOOK IN ABOVE SS) in below explaination)


1. Terminator Symbol

     Shape: Oval

     Purpose: Represents Start and End of a flowchart

     Example:

         Start, End

2. Input / Output Symbol

     Shape: Parallelogram

     Purpose: Used to take input or display output

      Example:

          Read a, b, c

          Print maximum

3. Process Symbol

      Shape: Rectangle

      Purpose: Used for calculations and processing

      Example:

       sum = a + b

       max = a

4. Decision Symbol

      Shape: Diamond

      Purpose: Used for conditions and comparisons

           It has Yes/No or True/False branches

    Example:

        a > b ?

5. Flow Line

      Shape: Arrow

       Purpose: Shows the direction of flow of the program

Flowchart diagram:




●Conclusion

》Algorithm explains the logic in words, while flowchart explains the same logic using diagrams.

》Both are important tools for problem solving and are widely used in C programming.


Q.5. Explain Type Conversion and Typecasting

(Intro)

Type conversion can be done automatically by the compiler or manually by the programmer. Based on this,it is classified into Type Conversion and Typecasting.

1.Type Conversion (Implicit Type Conversion)

      ➡️ Here, integer value 10 is automatically converted into 10.0 (float).


2.Typecasting (Explicit Type Conversion).

   Syntax: (data_type) expression

  

➡️ Here, a is explicitly converted into float to get correct decimal result 2.5.








●Difference Between Type Conversion and Typecasting (Theory)

>Type conversion is automatic, whereas typecasting is manual.

>Type conversion is performed by the compiler, while typecasting is performed by the programmer.

>Type conversion is safer, while typecasting may lead to data loss.

>Type conversion does not require any special syntax, but typecasting requires casting operator.



____Unit:2____

1. Explain if, if-else, else-if ladder and switch-case.







2. Differentiate between Entry vs Exit controlled loop and break vs continue.

Entry Control Loop vs Exit Control Loop

》Entry control loop checks the condition before executing the loop body, while exit control loop checks the condition after executing the loop body.

》Entry control loop may execute zero times, whereas exit control loop executes at least one time.

》In entry control loop, if condition is false initially, loop body is skipped, but in exit control loop, loop body runs once even if condition is false.

》Entry control loop is used when the number of iterations is known in advance, while exit control loop is used when at least one execution is required.

》Logic of entry control loop is simple and straightforward, while exit control loop logic is slightly complex.

》Entry control loop is also called pre-test loop, while exit control loop is called post-test loop.

》for and while loops are entry control loops in C.   

      do-while loop is an exit control loop in C.

》Entry control loop is mostly used in counting and repetition tasks.

      Exit control loop is mostly used in menu-driven and user-interactive programs.


●Break vs Continue

》The break statement terminates the loop completely, whereas the continue statement skips only the current iteration.

》After break, control comes outside the loop, but after continue, control goes to the next iteration.

》break stops further execution of the loop, while continue allows the loop to run again.

》break is used when no more looping is required, but continue is used when some values need to be ignored.

》break can be used in loops and switch statements, whereas continue is used only in loops.

》break skips all remaining statements of the loop permanently, while continue skips remaining statements only for that iteration.

》break immediately exits the loop, but continue only skips the rest of the current loop cycle.

》break immediately exits the loop, but continue only skips the rest of the current loop cycle.


Q.3. Write a program to check prime number.

#include <stdio.h>

#include <conio.h>


void main() {

    int n, i, flag = 0;


    clrscr();


    printf("Enter a number: ");

    scanf("%d", &n);


    if (n <= 1) {

        flag = 1;

    } else {

        for (i = 2; i <= n / 2; i++) {

            if (n % i == 0) {

                flag = 1;

                break;

            }

        }

    }


    if (flag == 0)

        printf("%d is a Prime number", n);

    else

        printf("%d is NOT a Prime number", n);


    getch();

}


Output

Enter a number: 7

7 is a Prime number


Enter a number: 10

10 is NOT a Prime number


Explanation (Easy & Short)

1. User enters a number n.

2. If n is 1 or less, it is not prime.

3. Loop checks divisibility from 2 to n/2.

4. If divisible → Not Prime, otherwise → Prime.


Q.4  Write pattern program:

1

2 1

3 2 1

4 3 2 1


#include <stdio.h>

#include <conio.h>


void main() {

    int i, j;

    

    clrscr();  // Clear the screen (specific to conio.h)


    for(i = 1; i <= 4; i++) {         // Outer loop for rows

        for(j = i; j >= 1; j--) {     // Inner loop for printing numbers

            printf("%d ", j);

        }

        printf("\n");                  // Move to next row

    }


    getch();  // Wait for a key press before closing

}


●Explanation:

>Outer loop for(i=1;i<=4;i++) controls the rows.

>Inner loop for(j=i;j>=1;j--) prints numbers from current row number down to 1.

>printf("\n") moves to the next row after printing each line.

>The program prints the pattern exactly as required.



Q.5. Explain nested loops with example.




____unit 3______

Q.1. Explain 1-D and 2-D Arrays with Example

●Introduction

        An array is a collection of elements of the same data type stored at contiguous memory locations.

       Arrays are used to store multiple values in a single variable name.

     They make it easy to process large sets of data using loops.

        Arrays in C can be 1-D (one-dimensional) or 2-D (two-dimensional).


●1-D Array (One-Dimensional Array)

          A 1-D array stores elements in a single row.

     It is also called a linear array.

Syntax:

data_type array_name[size];


Example:

int marks[5]; // 1-D array of 5 integers


Example Program: 1-D Array


#include <stdio.h>

#include<conio.h>

void main() {

    int marks[5] = {80, 75, 90, 85, 70};

    int i;

clrscr();


    for(i = 0; i < 5; i++) {

        printf("marks[%d] = %d\n", i, marks[i]);

    }

getch();

}


Output:

marks[0] = 80

marks[1] = 75

marks[2] = 90

marks[3] = 85

marks[4] = 70


●2-D Array (Two-Dimensional Array)

      A 2-D array stores elements in rows and columns, forming a matrix/table.


Syntax:

data_type array_name[rows][columns];


Example:

int matrix[2][3]; // 2 rows and 3 columns


Example Program: 2-D Array

#include <stdio.h>

#include <conio.h>

void main() {

    int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};

    int i, j;

clrscr();

    for(i = 0; i < 2; i++) {

        for(j = 0; j < 3; j++) {

            printf("%d ", matrix[i][j]);

        }

        printf("\n");

    }

getch();

}


Output:

1 2 3

4 5 6


●Key Differences

      1-D array → single row of elements; 2-D array → multiple rows and columns.

       1-D array is like a list; 2-D array is like a table or matrix.

      1-D array needs one subscript [i]; 2-D array needs two [i][j].

       Both store elements of the same data type.

       Arrays help in efficient data processing with loops.


Q.2. Program to find maximum element from array.

#include <stdio.h>

#include <conio.h>


void main() {

    int arr[10], i, n, max;


    clrscr();  // Clear screen


    printf("Enter number of elements (max 10): ");

    scanf("%d", &n);


    printf("Enter %d elements:\n", n);

    for(i = 0; i < n; i++) {

        scanf("%d", &arr[i]);

    }


    max = arr[0];  // Assume first element as maximum


    for(i = 1; i < n; i++) {

        if(arr[i] > max) {

            max = arr[i];  // Update max if current element is larger

        }

    }


    printf("Maximum element in the array = %d", max);


    getch();  // Wait for key press

}

》Sample Input

Enter number of elements (max 10): 5

Enter 5 elements:

12 45 7 22 34

》Output

Maximum element in the array = 45


●Explanation :

>arr[10] is the array to store elements.

>max stores the maximum value.

>The first element is assumed as maximum.

>Loop compares each element with max.

       If a larger element is found, max is updated.

>After loop ends, max contains the largest element in the array.


Q.3. Explain String Functions in C

Introduction

      A string in C is a sequence of characters terminated by a null character \0.

       Strings are stored as arrays of characters.

        C provides a set of library functions in string.h to manipulate strings easily.


●Commonly Used String Functions

》strlen(str)

      Returns the length of the string         (number of characters before \0).

Example:


char str[] = "Hello";

printf("%d", strlen(str)); // Output: 5


》strcpy(dest, src)

    Copies the source string into the destination string.

Example:


char src[] = "Hello";

char dest[10];

strcpy(dest, src);

printf("%s", dest); // Output: Hello


》strcat(dest, src)

     Concatenates (joins) source string at the end of destination string.

Example:


char str1[20] = "Hello ";

char str2[] = "World";

strcat(str1, str2);

printf("%s", str1); // Output: Hello World


》strcmp(str1, str2)

     Compares two strings.

            If both strings are equal, it returns 0; otherwise, it returns a negative or positive value.

Example:


strcmp("abc", "abd"); // Returns negative value


》strrev(str) 

        Reverses the string.

Example:


char str[] = "Hello";

strrev(str);

printf("%s", str); // Output: olleH


》strupr(str) / strlwr(str)

     Converts string to uppercase / lowercase.

Example:


char str[] = "Hello";

strupr(str);

printf("%s", str); // Output: HELLO


●Conclusion

String functions in C help to handle, manipulate, and compare strings easily.


●Program code:

#include <stdio.h>

#include <conio.h>

#include <string.h>


void main() {

    char str1[20], str2[20], str3[20];

    int len;


    clrscr();  // Clear screen


    // Input two strings (single word only)

    printf("Enter first string: ");

    scanf("%s", str1);  

    printf("Enter second string: ");

    scanf("%s", str2);


    // 1. strlen() - Length of first string

    len = strlen(str1);

    printf("\nLength of first string: %d", len);


    // 2. strcpy() - Copy string

    strcpy(str3, str1);

    printf("\nString copied to str3: %s", str3);


    // 3. strcat() - Concatenate strings

    strcat(str1, str2);

    printf("\nAfter concatenation (str1 + str2): %s", str1);


    // 4. strcmp() - Compare strings (numeric result)

    printf("\nResult of strcmp(str2, str3): %d", strcmp(str2, str3));


    // 5. strrev() - Reverse string

    strrev(str3);

    printf("\nReverse of str3: %s", str3);


    // 6. strupr() - Uppercase string

    strupr(str3);

    printf("\nUppercase of str3: %s", str3);


    // 7. strlwr() - Lowercase string

    strlwr(str3);

    printf("\nLowercase of str3: %s", str3);


    getch();  // Wait for key press

}

●Sample Input


Enter first string: hello

Enter second string: world


●Sample Output


Length of first string: 5

String copied to str3: hello

After concatenation (str1 + str2): helloworld

Result of strcmp(str2, str3): 15

Reverse of str3: olleh

Uppercase of str3: OLLEH

Lowercase of str3: olleh


Q.4. Explain User Defined Functions

●Introduction

      A function is a block of code that performs a specific task.

         Functions help in reducing code repetition, making programs modular, and easier to debug.

       》There are two types of functions in C:

   1>Built-in functions – Provided by C library (like printf(), scanf())

   2>User-defined functions – Created by the programmer


●Definition

     A user-defined function is a function written by the programmer to perform a specific task repeatedly whenever needed.


● Advantages of User Defined Functions

    Code Reusability – Write once, use multiple times.

    Modularity – Program can be divided into smaller, manageable parts.

     Ease of Debugging – Errors can be easily traced in smaller functions.

     Reduces Complexity – Makes large programs easier to understand.

      Better Readability – Function names describe their task.


●Structure of a User Defined Function

      A function has 4 main parts:

  >Function Declaration (Prototype) –        Tells the compiler about the function.

      int sum(int a, int b);

  >Function Definition – Contains the actual code of the function.

int sum(int a, int b) {

    return a + b;

}

    >Function Call – Used to execute the function in main().


result = sum(5, 3);

    >Return Type – Data type of value returned by function (int, float, void).


●Example Program

#include <stdio.h>

#include <conio.h>


// Function Definition

int sum(int a, int b) {

    return a + b;

}


void main() {

    int x = 5, y = 3, result;


    clrscr();  // Clear screen


    // Function Call

    result = sum(x, y);


    printf("Sum of %d and %d is %d", x, y, result);


    getch();  // Wait for key press

}

●Output

Sum of 5 and 3 is 8


Q.5. Recursive Factorial Program

      ●Introduction

            A recursive function is a function that calls itself to solve a problem.

            Factorial of a number n is n! = n × (n-1) × (n-2) × … × 1.

        Recursive factorial uses the formula:

            factorial(n)=n×factorial(n-1)

Base case: factorial(0) = 1 or factorial(1) = 1

●Program:

#include <stdio.h>

#include <conio.h>


// Function to calculate factorial

int factorial(int n) {

    if(n <= 1)

        return 1;          // Base case

    else

        return n * factorial(n - 1);  // Recursive call

}


void main() {

    int num, fact;


    clrscr();  // Clear screen


    printf("Enter a number: ");

    scanf("%d", &num);


    fact = factorial(num);  // Call the recursive function


    printf("Factorial of %d is %d", num, fact);


    getch();  // Wait for key press

}

●Sample Input / Output

>Input:

Enter a number: 4

>Output:

Factorial of 4 is 24


●Explanation 

    factorial() calls itself until n becomes 1.

      Each call multiplies n with factorial(n-1).

     Base case (n <= 1) stops the recursion.

    The final result is returned and printed in main().

Personality Development[imp]

Short Questions Answers: Q.1 Define Personality. Personality is the combination of a person’s thoughts, feelings, and behavior that makes th...