PPS Assignment 2 CE/IT

1.Write a short note on Switch Case. 

Ans: In C language, a switch case is a control statement that allows a program to take different actions based on the value of a single variable or expression. It follows the syntax: 

The switch statement evaluates the expression and then compares it to several constant values (cases) until a matching case is found. Once a matching case is found, the corresponding code block is executed, and the program continues from there. 

The “default” keyword is used to specify what code should be executed if none of the cases match the expression. It is optional but recommended to include it to handle unexpected cases. 

It is important to note that in C language, the expression used in the switch statement must evaluate to an integer, character, or enumeration type. Additionally, the cases must be constant integer expressions. 

2. What is Loop? Explain all the loops in detail ( with syntax and examples.) For,While,Do..while and GOTO. 

Ans: A loop is a programming construct that allows a section of code to be executed repeatedly based on a certain condition. In C language, there are four types of loops: for, while, do-while, and goto. 

For Loop: 

The for loop is used to execute a block of code repeatedly for a fixed number of times.  

The syntax of a for loop is as follows: 

The initialization step is executed only once at the beginning of the loop. The condition is checked before each iteration of the loop, and if it is true, the code inside the loop is executed. After each iteration, the increment/decrement step is executed. The loop stops when the condition becomes false. 

Example: 

While Loop: 

The while loop is used to execute a block of code repeatedly as long as a certain condition is true.  

The syntax of a while loop is as follows: 

The condition is checked at the beginning of each iteration of the loop, and if it is true, the code inside the loop is executed. The loop continues until the condition becomes false. 

Example: 

Do-While Loop: 

The do-while loop is similar to the while loop, but it guarantees that the code inside the loop is executed at least once.  

The syntax of a do-while loop is as follows: 

The code inside the loop is executed first, and then the condition is checked. If the condition is true, the loop continues, and if it is false, the loop stops. 

Example: 

3. Write Difference between : 1) break and continue 2) while and do..while. 

Ans: The difference between break and continue in C language is as follows: 

break statement is used to exit from a loop or switch statement when a certain condition is met. When a break statement is executed, the program control jumps to the statement immediately following the loop or switch statement. 

Example: 

continue statement is used to skip the current iteration of a loop and move on to the next iteration. When a continue statement is executed, the program control jumps to the beginning of the loop and starts the next iteration. 

Example: 

The difference between while and do-while loop in C language is as follows: 

while loop checks the condition first and then executes the code inside the loop. If the condition is false, the loop will not execute at all. 

Syntax: 

Example: 

do-while loop executes the code inside the loop first and then checks the condition. The loop will execute at least once, even if the condition is false. 

Syntax: 

Example: 

4. What is an array? Briefly explain the array. 

Ans: An array is a collection of elements of the same data type that are stored in a contiguous block of memory. Each element in the array can be accessed using an index that starts from 0. 

For example, to declare an array of integers with 5 elements, the syntax would be:  int arr[5]; 

To access an element in the array, we use the index of that element inside square brackets. The index starts from 0, which means the first element in the array has an index of 0, the second element has an index of 1, and so on. 

5. What is a 2D array? How we can create 2D arrays. Demonstrate 2D array with example. 

Ans: A 2D array is a collection of elements of the same data type that are organized in a matrix format with rows and columns. It can be thought of as a table with rows and columns, where each cell holds a value.The syntax for declaring a 2D array is as follows: 

datatype arrayname[rows][columns]; 

For example, to declare a 2D array of integers with 3 rows and 4 columns, the syntax would be: 

int arr[3][4]; 

To access an element in the 2D array, we use two indices inside square brackets, one for the row and one for the column. 

6. Write a program to list all prime numbers within a given range. 

Ans : 

#include <stdio.h>
#include <conio.h>
void main() {
    int lower, upper, i, j, flag;
    clrscr();
    printf("Enter the lower limit of the range: ");
    scanf("%d", &lower);
    printf("Enter the upper limit of the range: ");
    scanf("%d", &upper);
    printf("Prime numbers between %d and   %d are: ", lower, upper);
    for (i = lower; i <= upper; i++) {
        if (i == 1 || i == 0)
            continue;
        flag = 1;
        for (j = 2; j <= i/2; j++) {
            if (i % j == 0) {
                flag = 0;
                break;
            }
        }
        if (flag == 1)
            printf("%d ", i);
    }
    getch();
}

7. Write a program to print Fibonacci series of given numbers.

Ans :

#include <stdio.h>
#include <conio.h>
void main() {
    int num, i, first = 0, second = 1, next;
    clrscr();
    printf("Enter the number of terms: ");
    scanf("%d", &num);
    printf("Fibonacci Series: ");
    for (i = 1; i <= num; i++) {
        printf("%d ",first);
        next = first + second;
        first = second;
        second = next;
    }
    getch();
}

8.Write a program to find the factorial of a number. (without recursion)

Ans :

#include <stdio.h>
#include <conio.h>
void main() {
    int num, i, fact = 1;
    printf("Enter a number: ");
    scanf("%d", &num);
    for (i = 1; i <= num; i++) {
        fact *= i;
    }
    printf("Factorial of %d is %d", num, fact);
    getch();
}

9. Write a program to read 10 integers in an array. Find the addition of all elements.

Ans:

#include <stdio.h>
#include <conio.h>
void main() {
    int arr[10], i, sum = 0;
    clrscr();
    printf("Enter 10 integers:\n");
    for (i = 0; i < 10; i++) {
        scanf("%d", &arr[i]);
    }
    for (i = 0; i < 10; i++) {
        sum += arr[i];
    }
    printf("Sum of all elements in the array is %d", sum);
    getch();
}

10. .Write a Program to print Addition of two matrices.

Ans :

#include <stdio.h>
#include <conio.h>
void main() {
    int mat1[3][3], mat2[3][3], sum[3][3], i, j;
    clrscr();s
    printf("Enter the elements of the first matrix (3x3):\n");
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            scanf("%d", &mat1[i][j]);
        }
    }
    printf("Enter the elements of the second matrix (3x3):\n");
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            scanf("%d", &mat2[i][j]);
        }
    }
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            sum[i][j] = mat1[i][j] + mat2[i][j];
        }
    }
    printf("Sum of the two matrices:\n");
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            printf("%d ", sum[i][j]);
        }
        printf("\n");
    }
    getch();
}

11. Short note on String.

Ans: In C language, a string is an array of characters terminated by a null character ‘\0’. The null character is used to indicate the end of the string. For example, the string “hello” is represented in C as an array of characters {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’}. The length of this string is 5 characters, but the size of the array is 6 (including the null character). C provides a number of built-in functions to work with strings. Here are some commonly used string functions in C: strlen(): calculates the length of a string (excluding the null character). strcpy(): copies a string from one location to another. strcat(): concatenates two strings into one. strcmp(): compares two strings to see if they are equal. strchr(): searches a string for a given character and returns a pointer to its first occurrence. To use these functions, you need to include the header file string.h. C also provides a way to declare a string literal directly in your code, without having to manually create an array of characters. For example, you can write “hello” instead of {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’}. The compiler automatically creates an array of characters for you and adds the null character at the end.

12.Explain different methods to read and print strings.

Ans: 1.Using printf() and scanf() functions:

You can use the printf() function to print a string, and the scanf() function to read a string. The %s format specifier is used to specify a string in both functions. Here’s an example:

#include <stdio.h>
#include <conio.h>
void main() {
    char str[100];
    clrscr();
    printf("Enter a string: ");
    scanf("%s", str);
    printf("You entered: %s", str);
    getch();
}

2.Using puts() and gets() functions:

You can use the puts() function to print a string, and the gets() function to read a string. The puts() function automatically adds a newline character after the string, while gets() reads a string until a newline character is encountered. Here’s an example:

#include <stdio.h>
#include <conio.h>
void main() {
    char str[100];
    clrscr();
    printf("Enter a string: ");
    gets(str);
    printf("You entered: ");
    puts(str);
    getch();
}

3.Using fgets() and fputs() functions:

You can use the fgets() function to read a string from a file, and the fputs() function to write a string to a file. These functions are more secure than gets() and puts() because you can specify the maximum number of characters to be read or written. Here’s an example:

#include <stdio.h>
#include <conio.h>
void main() {
    FILE *fp;
    char str[100];
    clrscr();
    fp = fopen("test.txt", "w");
    printf("Enter a string: ");
    fgets(str, 100, stdin);
    fputs(str, fp);
    fclose(fp);
    printf("String written to file!");
    getch();
}

13.Explain the following :strlen, strcpy, strncpy, strcat, strncat, strcmp, strncmp, strstr, strchr, strrchr.

Ans :

  • strlen(): This function is used to determine the length of a string, i.e., the number of characters in the string. It takes a string as input and returns an integer value representing the length of the string.
  • strcpy(): This function is used to copy one string to another. It takes two strings as input – the destination string and the source string – and copies the contents of the source string to the destination string.
  • strncpy(): This function is similar to strcpy(), but it allows you to specify the maximum number of characters to be copied from the source string to the destination string.
  • strcat(): This function is used to concatenate two strings. It takes two strings as input – the destination string and the source string – and appends the contents of the source string to the end of the destination string.
  • strncat(): This function is similar to strcat(), but it allows you to specify the maximum number of characters to be appended from the source string to the destination string.
  • strcmp(): This function is used to compare two strings. It takes two strings as input and returns an integer value indicating whether the strings are equal or not. If the two strings are equal, it returns 0. If the first string is greater than the second string, it returns a positive value. If the first string is less than the second string, it returns a negative value.
  • strncmp(): This function is similar to strcmp(), but it allows you to specify the maximum number of characters to be compared from the two strings.
  • strstr(): This function is used to search for a substring within a string. It takes two strings as input – the main string and the substring to be searched for – and returns a pointer to the first occurrence of the substring in the main string. If the substring is not found, it returns a NULL pointer.
  • strchr(): This function is used to search for a character within a string. It takes two arguments – a string and a character to search for – and returns a pointer to the first occurrence of the character in the string. If the character is not found, it returns a NULL pointer.
  • strrchr(): This function is similar to strchr(), but it searches for the last occurrence of the character in the string.

14. What is a function? Why is it important?

Ans: In computer programming, a function is a self-contained block of code that performs a specific task and can be called from other parts of a program. It takes inputs (called parameters or arguments) and returns outputs (called return values), which can be used by the calling code. Functions are important in C programming because they help in organizing complex code into smaller, manageable pieces, making the code more modular, easier to read, and easier to maintain. By breaking down a large program into smaller functions, each function can be focused on a specific task, making the code easier to test and debug. Functions also enable code reuse, allowing programmers to use the same function in multiple parts of a program or even in different programs. This helps to reduce redundancy and makes code development faster and more efficient. In addition, C programming provides several built-in functions that programmers can use to perform various tasks, such as string manipulation, mathematical calculations, and input/output operations. These functions are part of the standard library and are available to all C programs.

15. Explain type (category) of Functions. Explain in detail with examples.

Ans : 1. Library Functions: These are the functions that are provided by the C standard library. They are predefined and can be used by programmers in their programs without having to write the function code. Some examples of library functions in C programming are printf(), scanf(), malloc(), strlen(), strcpy(), sin(), cos(), sqrt(), and exit(). These functions are grouped into various header files, such as stdio.h, stdlib.h, math.h, and string.h, among others.

2.User-defined Functions: These are the functions that are created by programmers to perform specific tasks in their programs. These functions are defined by the programmer and can be called from other parts of the program to perform the task. User-defined functions are useful in breaking down a large program into smaller, more manageable pieces, making the code more modular and easier to maintain.

3.Recursive Functions: These are the functions that call themselves during their execution. Recursive functions are useful in solving problems that can be broken down into smaller subproblems, such as the Fibonacci sequence and the factorial of a number.

4.Inline Functions: These are the functions that are expanded inline by the compiler during compilation. The inline functions are used to optimize the performance of a program by avoiding the overhead of function call and return. The inline function code is copied and pasted at the point of function call, eliminating the overhead of function call and return.

5.Function Pointers: These are the pointers that point to a function in memory. Function pointers are useful in passing functions as arguments to other functions or in assigning a function to a variable.

Leave a Comment

Your email address will not be published. Required fields are marked *

error: Content is protected !!
Scroll to Top