Saturday, August 15, 2026

Mobile Contact Manager || C Lab Programs

Program 12: Manually join names and check screen fit.

Problem Statement:: A basic mobile contact manager stores first and last names separately. For displaying full names in the contact list, the system needs to join them manually. Additionally, the system must check the length of each full name to ensure it fits within the 20-character screen limit.

Problem Description:

  • Input: First name (string) and Last name (string).

  • Output: Full name joined by a space, the total length, and a fit/no-fit message.

  • Constraints: Implement without using built-in string functions (like strcat or strlen); screen limit is 20 characters.

  • Method: Use character arrays and manual while loops to copy characters and calculate length.

Pgm Logic:

  1. Start.

  2. Input first name and last name strings.

  3. Initialize indices i = 0, j = 0, and length = 0.

  4. Loop through the first name array until the null terminator (\0) is reached, copying each character into the full name array and incrementing length.

  5. Insert a space character (' ') into full[length] and increment length.

  6. Loop through the last name array until \0, copying characters into full name and incrementing length.

  7. Terminate the full name string by adding \0 at the end.

  8. Print the full name and its calculated length.

  9. If length > 20, print "Name too long for screen"; otherwise, print "Name fits the screen".

  10. Stop.

Program Code:

// Purpose: To join first and last names manually and verify if they fit a 20-character screen.

#include <stdio.h>


int main()

{

    char first[10], last[10], full[20];

    int i = 0, j = 0, length = 0;


    printf("Enter first name: ");

    scanf("%s", first);

    printf("Enter last name: ");

    scanf("%s", last);


    // Manually copy first name into the full name array

    while(first[i] != '\0')

    {

        full[length++] = first[i++];

    }


    // Manually add a space between names

    full[length++] = ' ';


    // Manually copy last name into the full name array

    while(last[j] != '\0')

    {

        full[length++] = last[j++];

    }


    // Manually terminate the new string with a null character

    full[length] = '\0';


    printf("Full Name: %s\n", full);

    printf("Total Length: %d\n", length);


    if(length > 20)

    {

        printf("Name too long for screen.\n");

    }

    else

    {

        printf("Name fits the screen.\n");

    }


    return 0;

}


Output: 

Enter first name: Alexander 

Enter last name: Johnson 

Full Name: Alexander Johnson 

Total Length: 18 

Name fits the screen.

RESULT: Thus the program has been executed and the output was verified.

Remarks: This program was successfully compiled and tested in the onlineGDB tool. It bypasses string.h by directly interacting with the character indices of the arrays.

Program Explanation: Strings in C are essentially arrays of characters ending with a \0 (null) character. The program uses while loops to travel through the input arrays, stopping only when the \0 is detected. By manually moving characters to a third array (full), we perform concatenation. The final length check ensures the combined string doesn't exceed the hypothetical 20-character mobile display.


For all 2026 published C Lab Program posts Index page: click here

For all 2026 published articles list: click here

…till the next post, bye-bye & take care

Functions for Pattern Programs in C: A Beginner’s Guide to Modular Design

Functions for Pattern Programs in C: A Beginner’s Guide to Modular Design

When you first start writing pattern programs in C, everything usually lives inside a single main() function. You write your outer loop, your inner loop, your print statements, and your newlines all in one long, monolithic block of code.

While this works great for learning basic loop mechanics, it quickly becomes messy when you want to print multiple patterns, change sizes dynamically, or scale your code. The solution? Modular design using functions.

In this guide, we will explore how to transition your pattern programs from rigid, single-file scripts into clean, reusable, and modular C functions.

1. The Problem with Monolithic Pattern Code

Imagine you want to print a square pattern, a right-angled triangle, and a pyramid in the same C program. If everything is written inside main(), your code will look something like this:

#include <stdio.h>

int main() {
    // Square Pattern
    int n1 = 4;
    for (int i = 1; i <= n1; i++) {
        for (int j = 1; j <= n1; j++) {
            printf("* ");
        }
        printf("\n");
    }

    printf("\n");

    // Triangle Pattern
    int n2 = 4;
    for (int i = 1; i <= n2; i++) {
        for (int j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n");
    }

    return 0;
}

As you can see, this approach creates repetitive code blocks, clutters your workspace, and makes debugging difficult if something goes wrong.

2. What is Modular Design?

Modular design is the practice of breaking a large program down into smaller, self-contained, and manageable pieces—known as functions.

Instead of forcing main() to handle everything, you isolate specific tasks:

  • The Logic Isolator: Each pattern gets its own dedicated function (e.g., printSquare(), printTriangle()).

  • The Driver (main): The main() function simply acts as a coordinator, calling these functions whenever needed.

3. Refactoring a Pattern into a C Function

Let's take our right-angled triangle logic and wrap it inside a clean, reusable function.

Code Implementation

#include <stdio.h>

// Function definition to print a right-angled triangle
void printTriangle(int rows) {
    for (int i = 1; i <= rows; i++) {
        for (int j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n");
    }
}

int main() {
    int height = 5;
    
    printf("Printing a Triangle of height %d:\n", height);
    printTriangle(height); // Calling the function with an argument
    
    return 0;
}

Why This is Better:

  • Encapsulation: The pattern logic is completely hidden inside printTriangle().

  • Parameterization: By passing int rows as an argument, we can generate a triangle of any size dynamically without rewriting loop boundaries.

4. Building a Multi-Pattern Modular Program

Now let's combine multiple pattern functions into a single modular program. This demonstrates the true power of code reusability.

#include <stdio.h>

// Function declarations (Prototypes)
void printSquare(int n);
void printTriangle(int n);

int main() {
    int size = 4;
    
    printf("--- Square Pattern ---\n");
    printSquare(size);
    
    printf("\n--- Triangle Pattern ---\n");
    printTriangle(size);
    
    return 0;
}

// Function definitions
void printSquare(int n) {
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            printf("* ");
        }
        printf("\n");
    }
}

void printTriangle(int n) {
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n");
    }
}

Benefits of Modularizing Your Pattern Code

  1. Reusability: Write your pattern logic once, and call it multiple times with different parameters.

  2. Readability: Your main() function stays clean, short, and easy to read at a glance.

  3. Maintainability: If you need to fix a bug or optimize loop performance, you only have to update the code in one specific function rather than digging through a massive main() block.

By adopting modular design, you take a major step forward from writing simple scripts to engineering clean, professional C software!



For all Pattern Programs list click here

…till the next post, bye-bye & take care

Friday, August 14, 2026

Warehouse Revenue Calculation || C Lab Programs

Program 11: Calculate total warehouse revenue per branch.

Problem Statement:: A small warehouse tracks many units of different products shipped from multiple branches. Another dataset shows how much revenue each product generates per unit. Develop a C program that combines these datasets to calculate the total revenue generated by each branch.

Problem Description:

  • Input: Number of branches, number of products, a 2D array of units shipped, and a 1D array of revenue per product unit.

  • Output: The total revenue calculated for each branch.

  • Constraints: All counts, units, and revenue values must be non-negative integers.

  • Method: Store shipment data in a 2D array and product revenue in a 1D array; multiply and accumulate to find totals.

Pgm Logic:

  1. Start.

  2. Input the number of branches and products.

  3. Declare a 2D array units[branches][products] and a 1D array revenue[products].

  4. Input shipment units for each branch and product.

  5. Input revenue per unit for each product.

  6. For each branch i:

    • Initialize total = 0.

    • For each product j:

      • Calculate total += units[i][j] * revenue[j].

    • Print the total revenue for branch i.

  7. Stop.

Program Code:

// Purpose: To combine shipment and revenue datasets using arrays to calculate total revenue per branch.

#include <stdio.h>


int main() {

    int branches, products, i, j;

    printf("Enter number of branches: ");

    scanf("%d", &branches);

    printf("Enter number of products: ");

    scanf("%d", &products);

    int units[branches][products];

    int revenue[products];

    printf("\nEnter number of units shipped by each branch for each product:\n");

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

        printf("Branch %d:\n", i+1);

        for(j = 0; j < products; j++)

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

    }

    printf("\nEnter revenue per unit for each product:\n");

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

        printf("Product %d revenue: ", j+1);

        scanf("%d", &revenue[j]);

    }

    printf("Total revenue per branch:\n");

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

        int total = 0;

        for (j = 0; j < products; j++)

            total += units[i][j] * revenue[j];

        printf("Branch %d: %d\n", i + 1, total);

    }

    return 0;

}


Output: 

Enter number of branches: 3 

Enter number of products: 2 

(Enter units: 20, 10; 20, 30; 50, 20) 

(Enter revenue: 20, 30) 

Total revenue per branch: Branch 1: 700 Branch 2: 1300 Branch 3: 1600

RESULT: Thus the program has been executed and the output was verified.

Remarks: Compiled and run in Code::Blocks. This program illustrates the practical application of matrix-like data processing in business scenarios.

Program Explanation: The 2D array acts as a table where rows are branches and columns are products. The program iterates through each branch (row) and multiplies each shipment count by its corresponding unit price from the 1D revenue array to derive a sum for that branch.


For all 2026 published C Lab Program posts Index page: click here

For all 2026 published articles list: click here

…till the next post, bye-bye & take care

Interview Special: Top 10 Pattern-Based Coding Questions in C

Interview Special: Top 10 Pattern-Based Coding Questions in C

When you walk into a technical interview for a software engineering role, the interviewer isn't just looking for whether you memorized syntax. They want to evaluate your logic-building skills, spatial reasoning, and ability to handle edge cases.

Among junior and mid-level coding rounds, pattern-based questions remain a favorite screening tool. Why? Because solving them requires precise command over nested loops, variable scope, boundary conditions, and control flow.

In this special interview guide, we will break down the top 10 pattern-based coding questions in C that frequently appear in technical assessments, complete with explanations and code implementations.

Why Do Interviewers Ask Pattern Questions?

  • Loop Mastery: They test whether you truly understand how inner and outer loops interact.

  • Algorithmic Thinking: They measure your ability to map mathematical relationships (rows vs. columns) to code.

  • Attention to Detail: Small off-by-one errors or mismanaged spaces instantly break a pattern, revealing your debugging discipline.

The Top 10 Pattern Coding Questions

1. Solid Square Matrix

  • The Challenge: Print a solid square of stars.

  • Code Implementation:

#include <stdio.h>
int main() {
    int n = 4;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}

2. Right-Angled Triangle

  • The Challenge: Print stars increasing row by row.

  • Code Implementation:

#include <stdio.h>
int main() {
    int n = 4;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}

3. Inverted Right-Angled Triangle

  • The Challenge: Print a triangle that starts wide and shrinks.

  • Code Implementation:

#include <stdio.h>
int main() {
    int n = 4;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= (n - i + 1); j++) {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}

4. Numeric Right-Angled Triangle

  • The Challenge: Print numbers instead of stars in a triangle format (1, 1 2, 1 2 3, etc.).

  • Code Implementation:

#include <stdio.h>
int main() {
    int n = 4;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            printf("%d ", j);
        }
        printf("\n");
    }
    return 0;
}

5. Repeated Row Number Triangle

  • The Challenge: Print the row number repeatedly across each row (1, 2 2, 3 3 3, etc.).

  • Code Implementation:

#include <stdio.h>
int main() {
    int n = 4;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            printf("%d ", i);
        }
        printf("\n");
    }
    return 0;
}

6. Floyd's Triangle

  • The Challenge: Print consecutive numbers continuously across rows (1, 2 3, 4 5 6, etc.).

  • Code Implementation:

#include <stdio.h>
int main() {
    int n = 4, num = 1;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            printf("%d ", num++);
        }
        printf("\n");
    }
    return 0;
}

7. Centered Pyramid Pattern

  • The Challenge: Print a symmetrical centered pyramid using spaces and stars.

  • Code Implementation:

#include <stdio.h>
int main() {
    int n = 4;
    for (int i = 1; i <= n; i++) {
        for (int space = 1; space <= (n - i); space++) printf(" ");
        for (int star = 1; star <= (2 * i - 1); star++) printf("*");
        printf("\n");
    }
    return 0;
}

8. Diamond Pattern

  • The Challenge: Combine an upright pyramid and an inverted pyramid to form a complete diamond.

  • Code Implementation:

#include <stdio.h>
int main() {
    int n = 3;
    // Upper Pyramid
    for (int i = 1; i <= n; i++) {
        for (int s = 1; s <= (n - i); s++) printf(" ");
        for (int st = 1; st <= (2 * i - 1); st++) printf("*");
        printf("\n");
    }
    // Lower Inverted Pyramid
    for (int i = n - 1; i >= 1; i--) {
        for (int s = 1; s <= (n - i); s++) printf(" ");
        for (int st = 1; st <= (2 * i - 1); st++) printf("*");
        printf("\n");
    }
    return 0;
}

9. Binary 0-1 Triangle

  • The Challenge: Alternate 1 and 0 values in a triangular grid based on row/column parity.

  • Code Implementation:

#include <stdio.h>
int main() {
    int n = 4;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            if ((i + j) % 2 == 0) printf("1 ");
            else printf("0 ");
        }
        printf("\n");
    }
    return 0;
}

10. Hollow Square Border Pattern

  • The Challenge: Print a square where only the outer border contains stars, and the inside is hollow (spaces).

  • Code Implementation:

#include <stdio.h>
int main() {
    int n = 4;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (i == 1 || i == n || j == 1 || j == n) {
                printf("* ");
            } else {
                printf("  "); // Inner empty space
            }
        }
        printf("\n");
    }
    return 0;
}

Interview Success Tips

  1. Talk Through Your Logic: Interviewers love candidates who verbalize their thought process. Explain why you are setting your inner loop boundary or handling whitespace.

  2. Dry Run with Small Inputs: Before finalizing your code, manually trace your loops on paper using $N = 3$ to catch potential fencepost errors.

  3. Keep Code Clean: Use meaningful loop counters (row, col) when tackling multi-layered patterns to avoid confusion.

Mastering these 10 patterns guarantees that you will walk into your next coding interview with the confidence and logic-building agility required to ace loop-based challenges!



For all Pattern Programs list click here

…till the next post, bye-bye & take care