FOC Assignments solution

 

Use goto Statement to Print Numbers from 1 to 5

Task: Write a program to print numbers from 1 to 5 using the goto statement.

#include <stdio.h>

int main() {

    int i = 1;

start:

    if (i > 5) goto end;

    printf("%d ", i);

    i++;

    goto start;

end:

    printf("\n");

    return 0;

}




Assignment:

Use break and continue in a Loop

Task: Write a program to print numbers from 1 to 10 but skip 5 and stop the loop when number reaches 8.

#include <stdio.h>

int main() {

    for (int i = 1; i <= 10; i++) {

        if (i == 5)

            continue;  // skip 5

        if (i == 8)

            break;     // stop at 8

        printf("%d ", i);

    }

    printf("\n");

    return 0;

}



Assignment:

Find the Sum of First N Natural Numbers Using a Do-While Loop

Task: Write a program to calculate the sum of first N natural numbers using a do-while loop.

#include <stdio.h>

int main() {

    int n, i = 1, sum = 0;

    printf("Enter a positive number: ");

    scanf("%d", &n);

    do {

        sum += i;

        i++;

    } while (i <= n);

    printf("Sum = %d\n", sum);

    return 0;

}


Assignment:

Print Numbers from 1 to N Using a While Loop

Task: Write a program that takes an integer N from the user and prints numbers from 1 to N using a while loop.

#include <stdio.h>

int main() {

    int n, i = 1;

    printf("Enter a positive number: ");

    scanf("%d", &n);

    while (i <= n) {

        printf("%d ", i);

        i++;

    }

    printf("\n");

    return 0;

}


Assignment:

Implicit and Explicit Type Conversion

Task: Write a program to demonstrate implicit and explicit type conversion.

  • Read an integer and a float.

  • Add them and store the result in a float variable.

  • Print the result.

    #include <stdio.h>

    int main() {

        int a;

        float b, result;

        printf("Enter an integer: ");

        scanf("%d", &a);

        printf("Enter a float: ");

        scanf("%f", &b);

        // Implicit type conversion: 'a' is converted to float for addition

        result = a + b;

        // Explicit type conversion: float to int (typecast)

        int c = (int)result;

        printf("Sum (float): %.2f\n", result);

        printf("Sum (int after typecast): %d\n", c);

        return 0;

    }

    Assignment:

    Use the Ternary Operator to Find the Maximum of Two Numbers

    Task: Write a program that reads two numbers and uses the ternary operator to print the maximum.

    #include <stdio.h>

    int main() {

        int x, y, max;

        printf("Enter two numbers: ");

        scanf("%d %d", &x, &y);

        max = (x > y) ? x : y;

        printf("Maximum number is %d\n", max);

        return 0;

    }

Post a Comment

0 Comments