C-programming some questions
1.What is the significance of algorithm and flowchart in programming? Write an algorithm and draw flowchart to check whether the given number is prime or not.
Algorithms and flowcharts are essential tools in programming. They help in organizing and presenting the steps involved in solving a problem. An algorithm is a set of well-defined steps to solve a problem, while a flowchart is a graphical representation of an algorithm.
A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself. The algorithm and flowchart to check whether a given number is prime or not are as follows:
Algorithm to check whether a given number is prime or not:
- Input a positive integer n.
- Set flag=1.
- If n==1, print "1 is neither prime nor composite" and go to step 6.
- For i=2 to n-1, do the following: a. If n%i==0, set flag=0 and go to step 5.
- If flag==0, print "n is not a prime number." Otherwise, print "n is a prime number."
- Stop.
Flowchart to check whether a given number is prime or not:
lua+---------------+
|Start |
+---------------+
| |
v |
+---------------+
| Input n |
+---------------+
| |
v |
+---------------+
| flag=1 |
+---------------+
| |
v |
+---------------+
| if n==1 |
| print "1 is |
| neither prime |
| nor composite"|
| go to step 6. |
+---------------+
| |
v |
+---------------+
| for i=2 to |
| n-1, do the |
| following: |
| |
| if n%i==0, |
| set flag=0 |
| and go to |
| step 5. |
+---------------+
| |
v |
+---------------+
| if flag==0, |
| print "n is |
| not a prime |
| number." |
| Otherwise, |
| print "n is a |
| prime number."|
+---------------+
| |
v |
+---------------+
|Stop |
+---------------+
Note: The above algorithm and flowchart assume that the input number is a positive integer. Negative numbers and non-integers are not considered prime.
2.What are variables? Explain different types of data in C.
In computer programming, a variable is a named storage location that holds a value or data. Variables are used to store and manipulate data during the execution of a program. The value stored in a variable can be changed at any time during the program's execution.
In C programming, there are several types of data that can be stored in variables. These include:
Integer - This type of data is used to store whole numbers. It can be signed (positive or negative) or unsigned (positive only).
Float - This type of data is used to store decimal numbers with single precision.
Double - This type of data is used to store decimal numbers with double precision.
Character - This type of data is used to store a single character, such as a letter or symbol.
String - This type of data is used to store a sequence of characters.
Boolean - This type of data is used to store true/false values.
Variables are declared with a data type and a name in C. For example, to declare an integer variable called "num", you would write:
arduinoint num;
To assign a value to the variable, you can use the assignment operator (=). For example:
makefilenum = 10;
You can also declare and assign a value to a variable in a single line:
arduinoint num = 10;
Variables can be used in mathematical expressions, conditional statements, and loops to perform various operations and manipulate data.
3.Explain entry-controlled and exit controlled loops with examples
Entry-controlled and exit-controlled loops are two types of loops in programming.
- Entry-controlled loop: In an entry-controlled loop, the loop condition is checked at the beginning of each iteration. If the condition is true, the loop body is executed. The loop continues until the condition becomes false. The most common entry-controlled loop in programming is the "while" loop.
Example of entry-controlled loop:
perlint i = 1;
while (i <= 10) {
printf("%d\n", i);
i++;
}
In this example, the loop condition is "i <= 10". At the beginning of each iteration, the condition is checked. If the condition is true, the loop body is executed, which in this case is printing the value of "i" and incrementing it by 1. The loop continues until the value of "i" is greater than 10.
- Exit-controlled loop: In an exit-controlled loop, the loop condition is checked at the end of each iteration. If the condition is true, the loop body is executed again. The loop continues until the condition becomes false. The most common exit-controlled loop in programming is the "do-while" loop.
Example of exit-controlled loop:
perlint i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 10);
In this example, the loop body is executed first, which in this case is printing the value of "i" and incrementing it by 1. Then, the loop condition is checked. If the condition is true, the loop body is executed again. The loop continues until the value of "i" is greater than 10. Note that the loop body is executed at least once in an exit-controlled loop, whereas it may not be executed at all in an entry-controlled loop if the condition is false at the beginning.
4.Define array. Write a program to add two matrix of size M×N.
An array is a collection of variables of the same data type that are grouped together under a single name. The variables in an array are stored in contiguous memory locations, and each variable is accessed using an index or a subscript.
In C programming, arrays can be used to store a collection of values of the same data type, such as integers, floats, or characters.
Here is a program in C to add two matrices of size MxN:
scss#include <stdio.h>
int main()
{
int M, N, i, j;
printf("Enter the number of rows and columns of the matrices: ");
scanf("%d %d", &M, &N);
int matrix1[M][N], matrix2[M][N], result[M][N];
printf("Enter the elements of matrix1:\n");
for(i=0; i<M; i++)
{
for(j=0; j<N; j++)
{
scanf("%d", &matrix1[i][j]);
}
}
printf("Enter the elements of matrix2:\n");
for(i=0; i<M; i++)
{
for(j=0; j<N; j++)
{
scanf("%d", &matrix2[i][j]);
}
}
printf("Resultant matrix:\n");
for(i=0; i<M; i++)
{
for(j=0; j<N; j++)
{
result[i][j] = matrix1[i][j] + matrix2[i][j];
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
In the above program, the user is prompted to enter the number of rows and columns of the matrices. Then, three matrices matrix1
, matrix2
, and result
are declared with size MxN. The user is then prompted to enter the elements of both matrices. Finally, the program calculates the sum of the two matrices and stores the result in the result
matrix, which is then printed to the console.
5.Write a program to find the sum of two numbers using a function with no return type but with arguments.
Here is a program in C to find the sum of two numbers using a function with no return type but with arguments:
arduino#include <stdio.h>
void sum(int a, int b) // function declaration
{
int c = a + b; // calculate sum of a and b
printf("The sum of %d and %d is %d", a, b, c); // print the sum
}
int main()
{
int num1, num2;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
sum(num1, num2); // function call
return 0;
}
In the above program, the function sum
is declared with two integer arguments a
and b
. Inside the function, the sum of a
and b
is calculated and stored in the variable c
. The result is then printed to the console using printf
function.
In the main
function, the user is prompted to enter two integers num1
and num2
. The sum
function is then called with the arguments num1
and num2
. The sum
function does not return anything, so there is no need to store its result in a variable.
When you run the program and enter two numbers, it will call the sum
function and print the sum of the two numbers.
6.Define string and string handling function with suitable examples
A string is a sequence of characters that is used to represent text in computer programs. In C programming, a string is represented as an array of characters, terminated by a null character '\0'.
C provides a number of string handling functions that can be used to manipulate strings. Here are some examples:
- strlen() - This function is used to find the length of a string, which is the number of characters in the string excluding the null character.
arduino#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "Hello, world!";
int len = strlen(str);
printf("The length of the string is %d\n", len);
return 0;
}
Output:
csharpThe length of the string is 13
- strcpy() - This function is used to copy one string to another string.
arduino#include <stdio.h>
#include <string.h>
int main()
{
char src[] = "Hello, world!";
char dest[20];
strcpy(dest, src);
printf("The source string is: %s\n", src);
printf("The destination string is: %s\n", dest);
return 0;
}
Output:
csharpThe source string is: Hello, world!
The destination string is: Hello, world!
- strcat() - This function is used to concatenate two strings. It takes two arguments: the destination string and the source string to be appended.
arduino#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "Hello, ";
char str2[] = "world!";
strcat(str1, str2);
printf("The concatenated string is: %s\n", str1);
return 0;
}
Output:
csharpThe concatenated string is: Hello, world!
- strcmp() - This function is used to compare two strings. It returns an integer value that indicates the relationship between the two strings.
arduino#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "Hello, world!";
char str2[] = "hello, world!";
int result = strcmp(str1, str2);
if(result == 0)
printf("The two strings are equal\n");
else if(result < 0)
printf("The first string is less than the second string\n");
else
printf("The first string is greater than the second string\n");
return 0;
}
Output:
csharpThe first string is greater than the second string
These are just a few examples of the string handling functions available in C programming. There are many more string functions available that can be used to manipulate strings in various ways.
7.Why are functions important in programming? How are arguments passed to the function in C?
Functions are important in programming for several reasons:
Reusability - Functions can be defined once and used multiple times in a program. This saves time and reduces code duplication.
Modularity - Functions break down a program into smaller and more manageable parts, making the code easier to understand and maintain.
Abstraction - Functions can hide the details of their implementation from the rest of the program, providing a high-level interface for interacting with the program.
Code organization - Functions can help organize code into logical groups, making it easier to navigate and understand.
In C programming, arguments are passed to a function using one of two methods:
Pass by value - In this method, a copy of the argument value is passed to the function. Any changes made to the argument value inside the function do not affect the original value outside the function. This is the default method of passing arguments in C.
Pass by reference - In this method, a reference or pointer to the argument is passed to the function. Any changes made to the argument inside the function affect the original value outside the function.
Here's an example of passing arguments to a function in C:
arduino#include <stdio.h>
// function declaration
void print_sum(int a, int b);
int main() {
int x = 10, y = 20;
// function call
print_sum(x, y);
return 0;
}
// function definition
void print_sum(int a, int b) {
int sum = a + b;
printf("The sum of %d and %d is %d\n", a, b, sum);
}
In the above example, the function print_sum
is defined with two integer parameters a
and b
. Inside the function, the sum of a
and b
is calculated and printed to the console using printf
.
In the main
function, two integer variables x
and y
are declared and initialized. The print_sum
function is then called with the arguments x
and y
.
The arguments x
and y
are passed to the function by value, which means that a copy of their values is passed to the function. Any changes made to the parameters a
and b
inside the function do not affect the values of x
and y
outside the function.
Overall, functions are a powerful tool in programming that can help make code more modular, reusable, and organized.
8.WAP to print following pattern
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Here's the program to print the pattern:
arduino#include <stdio.h>
int main() {
int n = 5;
int i, j;
for (i = 1; i <= n; i++) {
for (j = 1; j <= n-i+1; j++) {
if (i % 2 == 1) {
printf("%d ", j);
}
else {
printf(" %d", j);
}
}
printf("\n");
}
return 0;
}
Output:
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
In this program, we use a nested for
loop to iterate through the rows and columns of the pattern. The outer loop iterates through the rows from 1 to n
, and the inner loop iterates through the columns.
We use an if
statement to check if the row number is odd or even. If it's odd, we print the numbers from left to right, and if it's even, we print the numbers from right to left. This creates the alternating pattern of the numbers.
Finally, we print a newline character \n
after each row to move to the next line.
9.What are the control statements? Differentiate between while and do while loop with suitable example.
In programming, control statements are used to control the flow of execution of a program. There are three types of control statements in C:
Selection statements - These statements are used to choose between two or more alternative paths of execution based on a condition. Examples include
if
,if-else
, andswitch
.Iteration statements - These statements are used to repeat a block of code multiple times. Examples include
for
,while
, anddo-while
loops.Jump statements - These statements are used to transfer control to a different part of the program. Examples include
break
,continue
, andgoto
.
Now, let's differentiate between the while
and do-while
loops.
while
loop:
The while
loop is a pre-test loop, which means that the loop condition is checked before executing the loop body. If the loop condition is false initially, the loop body is not executed at all.
Here's an example of a while
loop that prints the numbers from 1 to 5:
arduino#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
return 0;
}
Output:
1 2 3 4 5
In the above example, the loop condition i <= 5
is checked before executing the loop body. If the condition is true, the loop body is executed, and the value of i
is incremented by 1. This process is repeated until the condition becomes false.
do-while
loop:
The do-while
loop is a post-test loop, which means that the loop body is executed at least once, even if the loop condition is false.
Here's an example of a do-while
loop that prints the numbers from 1 to 5:
arduino#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);
return 0;
}
Output:
1 2 3 4 5
In the above example, the loop body is executed at least once, because the loop condition i <= 5
is checked after executing the loop body. If the condition is true, the loop body is executed again, and the value of i
is incremented by 1. This process is repeated until the condition becomes false.
So, the main difference between while
and do-while
loop is that the while
loop checks the loop condition before executing the loop body, while the do-while
loop checks the loop condition after executing the loop body at least once.
10.WAP to print even numbers from 51 to 100.
Here's a program to print even numbers from 51 to 100:
arduino#include <stdio.h>
int main() {
int i;
for (i = 52; i <= 100; i += 2) {
printf("%d ", i);
}
return 0;
}
Output:
52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100
In this program, we use a for
loop to iterate through the numbers from 52 to 100 in steps of 2. We start from 52 because it is the first even number in the range, and we print only even numbers using the %
(modulus) operator.
The %
operator returns the remainder of a division operation. If a number is even, it will have a remainder of 0 when divided by 2, so we use the %
operator to check if the current number is even. If it is, we print it using the printf()
function.
11.WAP to sort N elements of an integer array in ascending order
Here's a program to sort N elements of an integer array in ascending order using the Bubble Sort algorithm:
scss#include <stdio.h>
void bubble_sort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int i, n, arr[100];
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
bubble_sort(arr, n);
printf("Sorted array in ascending order:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output:
yamlEnter the number of elements: 5
Enter 5 elements:
5 2 8 3 1
Sorted array in ascending order:
1 2 3 5 8
In this program, we use the Bubble Sort algorithm to sort the elements of an integer array in ascending order. The algorithm works by repeatedly swapping adjacent elements if they are in the wrong order, until the entire array is sorted.
We define a function bubble_sort()
that takes an integer array arr[]
and its size n
as arguments. The function implements the Bubble Sort algorithm using two nested loops, and swaps adjacent elements if they are in the wrong order.
In the main()
function, we read the array elements from the user and call the bubble_sort()
function to sort the array. Finally, we print the sorted array in ascending order using a for
loop.
12.Does a function return a multiple values? When and how a function returns multiple values? Illustrate with suitable example.
In C, a function can only return a single value. However, it is possible to simulate returning multiple values by using various techniques such as returning a struct or an array, passing pointers as arguments, or using global variables. Here's an example of how to return multiple values from a function using a struct:
c#include <stdio.h>
struct Point {
int x;
int y;
};
struct Point get_coordinates() {
struct Point p;
printf("Enter x and y coordinates: ");
scanf("%d %d", &p.x, &p.y);
return p;
}
int main() {
struct Point p1 = get_coordinates();
struct Point p2 = get_coordinates();
printf("Point 1: (%d, %d)\n", p1.x, p1.y);
printf("Point 2: (%d, %d)\n", p2.x, p2.y);
return 0;
}
Output:
mathematicaEnter x and y coordinates: 3 4
Enter x and y coordinates: 5 6
Point 1: (3, 4)
Point 2: (5, 6)
In this example, we define a struct Point
that has two integer fields x
and y
. We define a function get_coordinates()
that reads two integers from the user and returns a Point
struct with the coordinates.
In the main()
function, we call get_coordinates()
twice to get the coordinates of two points. The function returns a Point
struct, which we assign to variables p1
and p2
. We can access the x
and y
fields of each Point
struct using the .
operator and print them using printf()
statements.
This is a simple example of how to return multiple values from a function using a struct. Depending on the problem, other techniques may be more appropriate.
13.Why do you need a structure? How a structure differs from a union with suitable programs.? Explain in detail.
In C, a structure is a composite data type that allows you to group together variables of different data types under a single name. Structures are useful for representing complex data types, such as records or objects, and for organizing related data into a single unit.
A union, on the other hand, is a special type of structure that allows you to store different data types in the same memory location. A union is useful when you need to store different types of data in the same memory space, but only one data type at a time.
Here's an example program that demonstrates the use of a structure:
arduino#include <stdio.h>
struct person {
char name[20];
int age;
float height;
};
int main() {
struct person p1 = {"John", 30, 1.8};
printf("Name: %s\n", p1.name);
printf("Age: %d\n", p1.age);
printf("Height: %.2f meters\n", p1.height);
return 0;
}
In this program, we define a structure person
that has three fields: a character array name
, an integer age
, and a float height
. We create a variable p1
of type person
and initialize its fields using a struct initializer. We then print the values of the fields using printf()
statements.
Now, let's take a look at an example program that demonstrates the use of a union:
arduino#include <stdio.h>union my_union {int i;float f;char c;};int main() {union my_union u;u.i = 42;printf("u.i = %d\n", u.i);u.f = 3.14;printf("u.f = %.2f\n", u.f);u.c = 'A';printf("u.c = %c\n", u.c);return 0;}
In this program, we define a union my_union
that has three fields: an integer i
, a float f
, and a character c
. We create a variable u
of type my_union
and assign a value of 42 to its i
field. We then print the value of u.i
using printf()
.
Next, we assign a value of 3.14 to the f
field of u
and print its value. Finally, we assign the character 'A' to the c
field of u
and print its value.
The output of the program is:
cssu.i = 42
u.f = 3.14
u.c = A
As you can see, when we assign a value to one field of the union, the values of the other fields are lost because they share the same memory location. This is one of the key differences between a structure and a union. A structure allows you to store multiple values of different data types in separate memory locations, while a union allows you to store multiple values of different data types in the same memory location, but only one value at a time.
14.WAP using array to find largest and smallest number from a list of 100 given numbers.
Here's a program in C that uses an array to find the largest and smallest numbers from a list of 100 given numbers:
scss#include <stdio.h>
int main() {
int numbers[100];
int i, largest, smallest;
// Input 100 numbers from the user
printf("Enter 100 numbers:\n");
for (i = 0; i < 100; i++) {
scanf("%d", &numbers[i]);
}
// Find the largest and smallest numbers
largest = smallest = numbers[0];
for (i = 1; i < 100; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}
// Print the largest and smallest numbers
printf("Largest number: %d\n", largest);
printf("Smallest number: %d\n", smallest);
return 0;
}
In this program, we declare an integer array numbers
of size 100. We use a loop to input 100 numbers from the user and store them in the array.
We then use another loop to find the largest and smallest numbers in the array. We initialize the variables largest
and smallest
to the first element of the array, and then compare each subsequent element with these variables to update their values if necessary.
Finally, we print the values of largest
and smallest
to the console.
15.Define operator and operand. List the types of operators and explain any five of them
In programming, an operator is a symbol or set of symbols that performs an operation on one or more operands. An operand is a value or expression that an operator operates on.
There are several types of operators in programming, including:
Arithmetic operators: perform mathematical operations such as addition, subtraction, multiplication, and division. Some programming languages also have additional arithmetic operators such as modulus (remainder after division) and exponentiation.
Comparison operators: compare two values and return a Boolean value (true or false) depending on whether the comparison is true or false. Examples of comparison operators include "equal to" (==), "not equal to" (!=), "greater than" (>), and "less than" (<).
Logical operators: perform logical operations such as "and" (&&), "or" (||), and "not" (!). Logical operators are commonly used in conditional statements and loops.
Assignment operators: assign a value to a variable. Examples of assignment operators include "=" (assign), "+=" (add and assign), and "-=" (subtract and assign).
Bitwise operators: perform operations on the individual bits of a value. Examples of bitwise operators include "&" (bitwise AND), "|" (bitwise OR), and "~" (bitwise NOT).
Let's explain a few of these operators with examples:
Arithmetic operator: The addition operator (+) adds two operands together. For example, 2 + 3 = 5.
Comparison operator: The greater than operator (>) compares two operands and returns true if the left operand is greater than the right operand. For example, 5 > 3 is true.
Logical operator: The logical AND operator (&&) returns true if both operands are true. For example, (5 > 3) && (7 < 10) is true.
Assignment operator: The assignment operator (=) assigns a value to a variable. For example, int x = 5; assigns the value 5 to the variable x.
Bitwise operator: The bitwise OR operator (|) performs a bitwise OR operation on two operands. For example, 5 | 3 = 7, because in binary, 5 is 101 and 3 is 011, so the OR operation returns 111, which is 7 in decimal.