Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

C Programming Arrays: Exercises and Solutions

Tech 2

Multiple Choice Questions

(1) Given declarations int i; char x[10];, the correct statement to assign values to array x is:

for(i=0; i<6; i++) x[i]=getchar();

(2) For character arrays delcared as char a[]="abcd"; char b[]={'a','b','c','d','e'};:

Both arrays have identical length due to null terminator inclution.

(3) With declaration int i; int x[3][3]={2,3,4,5,6,7,8,9,10};, executing:

for(i=0;i<3;i++) printf("%4d",x[i][2-i]);

Outputs: 4 6 8

(4) Valid two-dimensional array initialization:

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

(5) Correct array characteristic:

Elements are distinguished through subscript indexing.

(6) To output the lexicographically larger string between str1 and str2:

if(strcmp(str1,str2)>0) printf("%s",str1); else printf("%s",str2);

(7) For array aa[4][4] = {{1,2,3,4},{5,6,7,8},{3,9,10,2},{4,2,9,6}}:

int i, s = 0;
for (i = 0; i < 4; i++)
   s += aa[i][1];
printf("%d\n", s);

Result: 19

(8) Character array str[15] = "hello!" has actual character count:

printf("%d\n", strlen(str)); // Output: 6

(9) After input "happy!":

char str[14] = {"I am "};
strcat(str, "sad!");
scanf("%s", str);
printf("%s", str); // Output: happy!

(10) Incorrect array description:

Remaining elements initialize to zero, not to last specified value.

Fill-in-the-Blank Questions

(1) For int i=3,x[4]={1,2,3};, element x[i] equals 0.

(2) String "I am a student" has length 14, with a[3] containing 'm'.

(3) In int k[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}}: k[2][1] is 10, k[1][2] is 7.

(4) Array a[4][4] has row lower bound 0 and column upper bound 3.

(5) For char a[]="abcdef":

printf("%d,%d\n",sizeof(a),strlen(a)); // Output: 7,6

(6) Program execution result:

char str[20] = "This is my book";
str[4] = '\0';
str[9] = '\0';
printf(" %d", strlen(str)); // Output: 4

(7) String comparison program outputs:

char name[3][20] = { "Tony", "Join", "Mary" };
int m = 0, k;
for (k = 1; k <= 2; k++)
     if (strcmp(name[k], name[m]) > 0)
         m = k;
puts(name[m]); // Output: Tony

(8) Statistical computation with input 20 30 5 85 40 produces:

max=85
min=5
sum=180
aver=30.00

(9) Charactre extraction program with input This_is_a_C_Program! generates:

Ti_saCPorm
Tss_Pgm

(10) Character counting program yields:

char s[] = "12345678";
int c[4] = { 0 }, k, i;
for (k = 0; s[k]; k++) {
    switch (s[k]) {
        case'1': i = 0; break;
        case'2': i = 1; break;
        case'3': i = 2; break;
        case'4': i = 3;
    }
    c[i]++;
}
// Output: 1 1 1 5

Programming Exercises

(1) Find minimum value and position among 15 integers:

#include<stdio.h>
int main() {
    int data[15], pos = 0;
    
    for (int idx = 0; idx < 15; idx++)
        scanf("%d", &data[idx]);
        
    for (int idx = 1; idx < 15; idx++)
        if (data[idx] < data[pos])
            pos = idx;
            
    printf("Minimum: %d at position: %d", data[pos], pos);
    return 0;
}

(2) Convert decimal to hexadecimal representation:

#include<stdio.h>
int main() {
    int num, digits[16], count = 0;
    
    do {
        scanf("%d", &num);
        if (num < 0) printf("Enter positive integer:\n");
    } while(num < 0);
    
    while(num) {
        digits[count] = num % 16;
        num /= 16;
        count++;
    }
    
    for (int idx = count-1; idx >= 0; idx--) {
        if (digits[idx] < 10) 
            printf("%d", digits[idx]);
        else 
            printf("%c", 'A' + digits[idx] - 10);
    }
    return 0;
}

(3) Count comma-separated words in string:

#include<stdio.h>
int main() {
    char text[100];
    int words = 0, active = 0;
    
    gets(text);
    for (int idx = 0; text[idx] != '\0'; idx++) {
        if (text[idx] == ',') 
            active = 0;
        else if (!active) {
            active = 1;
            words++;
        }
    }
    printf("Words: %d\n", words);
    return 0;
}

(4) Sort even-indexed characters in ascending order:

#include<stdio.h>
#include<string.h>
int main() {
    char input[100];
    int marker;
    
    gets(input);
    
    for (int base = 0; base < strlen(input)-2; base += 2) {
        marker = base;
        for (int compare = base+2; compare < strlen(input); compare += 2)
            if (input[compare] < input[marker]) 
                marker = compare;
                
        if (marker != base) {
            input[marker] ^= input[base];
            input[base] ^= input[marker];
            input[marker] ^= input[base];
        }
    }
    puts(input);
    return 0;
}

(5) Generate Pascal's triangle for 10 rows:

#include<stdio.h>
int main() {
    int triangle[10][10];
    
    for (int row = 0; row < 10; row++) {
        triangle[row][0] = triangle[row][row] = 1;
    }
    
    for (int row = 2; row < 10; row++)
        for (int col = 1; col < row; col++)
            triangle[row][col] = triangle[row-1][col-1] + triangle[row-1][col];
            
    for (int row = 0; row < 10; row++) {
        for (int col = 0; col <= row; col++)
            printf("%4d", triangle[row][col]);
        printf("\n");
    }
    return 0;
}

(6) Concatenate string with its reverse:

#include<stdio.h>
#include<string.h>
int main() {
    char source[100], target[100];
    int length;
    
    scanf("%s", source);
    length = strlen(source);
    
    for (int idx = 0; idx < length; idx++)
        target[idx] = source[idx];
        
    for (int idx = 0; idx < length; idx++)
        target[length + idx] = source[length - 1 - idx];
        
    target[2 * length] = '\0';
    printf("%s\n", target);
    return 0;
}

(7) Encrypt four-digit number using substitution cipher:

#include<stdio.h>
int main() {
    int number, result = 0, digits[4];
    scanf("%d", &number);
    
    for (int pos = 3; pos >= 0; pos--) {
        int adjusted_pos = abs(pos - 3);
        digits[adjusted_pos] = (number % 10 + 5) % 10;
        result = result * 10 + digits[adjusted_pos];
        number /= 10;
    }
    printf("Encrypted: %d", result);
    return 0;
}

(8) Locate first occurrence of value 18 in matrix:

#include<stdio.h>
int main() {
    int matrix[3][4] = {{3,4,5,18}, {8,12,16,54}, {43,34,18,7}};
    int row, col;
    
    for (row = 0; row < 3; row++) {
        for (col = 0; col < 4; col++)
            if (matrix[row][col] == 18) break;
        if (col < 4) break;
    }
    printf("Value 18 found at row %d, column %d\n", row+1, col+1);
    return 0;
}

(9) Analyze 4x4 array with formula a[i][j]=3i+2j-6:

#include<stdio.h>
int main() {
    int grid[4][4], row_sum = 0;
    float col_avg = 0;
    int negative_count = 0;
    
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 4; j++)
            grid[i][j] = 3 * i + 2 * j - 6;
            
    for (int j = 0; j < 4; j++)
        row_sum += grid[1][j];
        
    for (int i = 0; i < 4; i++)
        col_avg += grid[i][3];
    col_avg /= 4;
    
    for (int i = 0; i < 4; i++)
        if (grid[i][i] < 0)
            negative_count++;
            
    printf("Row 2 sum: %d\n", row_sum);
    printf("Column 4 average: %f\n", col_avg);
    printf("Negative diagonal elements: %d\n", negative_count);
    return 0;
}

(10) Josephus problem implementation:

#include<stdio.h>
int main() {
    int passwords[100];
    int people, limit, current = 0;
    
    printf("Enter people count and initial limit: ");
    scanf("%d%d", &people, &limit);
    printf("Enter %d passwords: ", people);
    
    for (int i = 0; i < people; i++)
        scanf("%d", &passwords[i]);
        
    printf("\nElimination order: ");
    
    for (int eliminated = 0; eliminated < people; eliminated++) {
        int counter = 1;
        while (counter < limit) {
            while (passwords[current] == 0)
                current = (current + 1) % people;
            counter++;
            current = (current + 1) % people;
        }
        
        while (passwords[current] == 0)
            current = (current + 1) % people;
            
        printf("%d ", current + 1);
        limit = passwords[current];
        passwords[current] = 0;
    }
    return 0;
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.