Class 9th CBSE

104 – Computer Programming And Programming Methodology

104 - Computer Programming And Programming Methodology- Feb-2021

SOLUTION

Q-l(A)Do as directed (Any Ten) (10)

1.Which is valid expression in C language?
A.char my_variable = “ABC”;
B.char my_variable = ‘ABC’;
C.char my_variable = ‘A’;
D.char my_variable = “A”;
2.Extension of C source code file is …………..
A. .c
B. .cpp
C. .obj
D. .exe
3.Which of the following is correct control specifier for double data type?
A. %d
B. %u
C. %f
D. %lf
4.Which of the following is correct statement?
A. #define n = 5
B. #define int n = 5
C. #define n 5
D. #define n = 5;
5.Operator % in the C language is called…………….. .
A. Percentage operator
B. Modulus operator
C.Division operator
D.Quotient operator
6.What is the output of the C program?
void main()
{
int a = 3+5/2;
printf(“%d”,a);
getch();
}
A. 3
B. 5
C. 2
D. Can not assign an expression to variable at the time of declaration.
7. Which mathematical function would you use to round off 8.33 to 9?
A. ceil(8.33)
B. floor(8.33)
C.ceil(8.33,9)
D.floor(8.33,9)
8.In C language,the symbolic constant is defined……………..
A. Before main
B. After main
C.Any where
D.None of these
9.switch statement cannot accept
A. int
B. char
C. float
D. None of these
10.A label statement consists of an identifier followed by
A. ;
B. :
C. ,
D. =
11.An array index starts with …………………..
A.-1
B. 1
C. 2
D. 0

Q.1(B)Answer in short (any five) (10)

1. What is an object code?
Ans :-
Object code generally refers to the output, a compiled file, which is produced when the Source Code is compiled with a C compiler.
2. Explain keyword.
Ans :-
-> Keywords are predefined or reserved words that have special meanings to the compiler.
-> The keywords cannot be used as variable name.
-> The list of C keyword are :- Auto,break,case,char,do,while,if ,int etc.
3. Give the syntax of forloop.
Ans :-
The syntax of for loop are :-
for(initialization;condition;increment/decrement)
{
statment;
}
4. Explain strcpy().
Ans :-
->strcpy is a C standard library function that copies a string from one location to another. It is defined in the string. h header file.
->The strcpy() is a library function available in string library in C, and is used to copy the content of one string to another.
Syntax :- Char * strcpy(char * dest, const char *src)
5. Explain nested if condition.
Ans :- Nested if statements mean an if statement inside another if statement.
The general syntax of nested if-else statement in C is as follows:
if (condition1) {
/* code to be executed if condition1 is true */
if (condition2) {
/* code to be executed if condition2 is true */
} else {
/* code to be executed if condition2 is false */
}
} else {
/* code to be executed if condition1 is false */
}
6. Define the term algorithm.
Ans :-
-> An algorithm is a sequence of instructions that are carried out in a predetermined sequence in order to solve a problem or complete a work.
-> A function is a block of code that can be called and executed from other parts of the program.
->A set of instructions for resolving an issue or carrying out a certain activity.
7. Explain relational operators with an example.
Ans : –
->Relational operator are used to compare value of two expression depemding on their relation.
->An expression that contains relational operator is called relational expression.
The relational operator are :-
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== is equal to
!= is not equal to

Q.2 Answer the following questions. (Any three) (15)

A.Explain flowchart in detail.
Ans :- A flowchart is the grpahical representation of an algorithm with the help of different symbols, shapes, and arrows in order to show a process or a program. With algorithm , we can easily understand a program. The main puspose of a flowchart is to analyse differnt processes. Several standard graphics are applied in a flowchart.
Various symbols used in a flowchart are :-
Oval (Start/End): The process starts with an oval symbol labeled “Start” and ends with another oval labeled “End.”
Rectangle (Process): The rectangles represent processes. In this example, there are two processes: “Pick up the lamp” and “Insert the plug into the socket.”
Diamond (Decision): The diamond shape represents a decision point. In this case, it is a yes/no question: “Is the lamp plugged in?” Depending on the answer, the flow takes different paths.
Parallelogram (Input/Output): The parallelogram represents input or output. In this case, it’s labeled “Turn on the switch.”
Arrows: Arrows connect the symbols, indicating the flow of the process from one step to another.
Example of a flowchart
-> Flow chart for the area of circle
B.Explain constant in detail.
Ans :- A constant refers to a fixed value that cannot be altered or modified during the execution of a program. Constants are used to represent unchanging and specific values, such as numerical values, characters, or strings, that retain the same value throughout the program’s execution.
Some basic keypoint about the constant are :-
1. Declaration and Initialization:-
->Constants are typically declared and initialized at the beginning of a program or in a specific section dedicated to constant declarations.
->In many programming languages, a keyword (e.g., const in C and C++) is used to declare constants.
-> const int MAX_VALUE = 100;
2. Types of Constants:-
->Numeric Constants: Represent fixed numerical values. Examples include integers (5), floating-point numbers (3.14), and hexadecimal values (0x0A).
->Character Constants: Represent individual characters. Enclosed in single quotes, e.g., ‘A’.
->String Constants: Represent sequences of characters. Enclosed in double quotes, e.g., “Hello, World!”.
->Boolean Constants: Represent truth values (true or false).
3.Scope :-
->The scope of a constant determines where it can be accessed or used in the program.
->Constants declared at the global level are accessible throughout the entire program, while those declared within a function or a block have limited scope.
Constants play a crucial role in making programs more robust, understandable, and maintainable by encapsulating fixed values and providing meaningful names to them. They are an essential concept in software development for ensuring the stability and reliability of code.
C.Explain scanf(), getc(), getch(), gets(), and getchar().
Ans :-
(1)Scanf() :-
->The scanf() function is used for reading input from the standard input (usually the keyboard). It is part of the Standard Input/Output library (stdio.h).
->It allows the program to read formatted data. The format specifier in scanf() specifies the type of data to be read and the corresponding variable where the data will be stored.
Example :-
#include <stdio.h>
int main() {
int num;
printf(“Enter an integer: “);
scanf(“%d”, &num); // Reads an integer from the user and stores it in ‘num’
printf(“You entered: %d\n”, num);
return 0;
}
(2) getc():-
->The getc() function is used to read a character from a specified file stream.
->It is typically used to read characters from files, but it can also be used with the standard input (stdin), similar to getchar()
exmaple :-
#include <stdio.h>
int main() {
char ch;
printf(“Enter a character: “);
ch = getc(stdin); // Reads a character from standard input
printf(“You entered: %c\n”, ch);
return 0;
}
(3) getch():-
->The getch() function is not a standard C library function. It is commonly used in older versions of C or with certain compilers.
->It is used to read a character directly from the console without echoing it to the screen.
->It’s often recommended to avoid using getch() as it’s not a standard function and can lead to non-portable code.
(4) gets():-
->The gets() function is used to read a line of text from the standard input.
->It reads characters from the input until a newline character (‘\n’) is encountered. It then terminates the string with a null character (‘\0’).
Example :-
#include <stdio.h>
int main() {
char str[50];
printf(“Enter a string: “);
gets(str); // Reads a line of text from standard input
printf(“You entered: %s\n”, str);
return 0;
}
D.Explain C program body structure in detail.
Ans :-
In C programming, the structure of a program is organized into sections that collectively make up the body of the program.
(1) The first section is document section
->Optional section that includes comments providing information about the program.
->Comments can include details such as the program’s purpose, author, creation date, and any other relevant information.
->Comments in C are preceded by /* for multi-line comments or // for single-line comments.
Example :-
/* This is a simple C program
Author: John Doe
Date: January 1, 2023 */
(2) The second Section is “Header Section”
->This section includes preprocessor directives that specify the header files needed for the program.
->Header files contain declarations for functions and macros that the program will use.
->Some example of Header file are :-
#include <stdio.h> // Standard Input/Output functions
#include <stdlib.h> // Standard Library functions
(3) Macro Definitions Section:
->Optional section where macro definitions can be placed using #define.
->Macros are preprocessor directives that perform text replacement before compilation.
->Some example of Macro Section are :-
#define PI 3.14159
(4) Global Declarations Section:
->This section includes global variable declarations and function prototypes.
->Global variables are accessible throughout the entire program, while function prototypes provide information about functions before they are defined.
->Some example of Global Declarations Section are :-
int globalVariable; // Global variable declaration
void myFunction(int param); // Function prototype
(5) main() Function:
->Every C program must have a main() function, which serves as the entry point of the program.
->The execution of the program starts from the main() function.
->Some example of main() function are :-
int main() {
// Program logic goes here
return 0;
}
(6) Function Definitions:
-> The body of the program contains the definitions of functions declared in the global declarations section. Like :-
void myFunction(int param) {
// Function logic goes here
}
(7)Code Statements:
->Inside the main() function and other user-defined functions, you write the code statements that define the program’s logic.
Statements are terminated by a semicolon (“;”). like
int main() {
printf(“Hello, World!\n”); // Example code statement
return 0;
}
(8) Return Statement:
->The return statement is used to exit a function.
->In the main() function, it is used to indicate a successful termination of the program.
int main() {
// Program logic goes here
return 0; // Indicates successful termination
}
(9)Closing Brace:
->Every opening brace { must be matched with a closing brace }.
->The closing brace signifies the end of a block of code, such as the body of a function or a loop.
int main() {
// Program logic goes here
return 0;
} // End of main() function

Q.3 Answer the following questions. (Any three) (15)

(A)Explain any five mathematical functions in detail.
Ans :-
Maths function can be access by using Header file like <math.h>
The 5 mathmetical function are :-
(i)sqrt(): Square Root Function
->Purpose: Calculates the square root of a given number.
->Function Prototype:
double sqrt(double x);
Example :-
#include <stdio.h>
#include <math.h>
int main() {
double num = 25.0;
double result = sqrt(num);
printf(“Square root of %.2f is %.2f\n”, num, result);
return 0;
}
(ii) pow(): Power Function :-
-> Purpose: Calculates the value of a number raised to the power of another number.
Function Prototype:
double pow(double x, double y);
Example :-
#include <stdio.h>
#include <math.h>
int main() {
double base = 2.0;
double exponent = 3.0;
double result = pow(base, exponent);
printf(“%.2f raised to the power %.2f is %.2f\n”, base, exponent, result);
return 0;
}
(iii) sin(): Sine Function:-
->Purpose: Calculates the sine of an angle in radians.
->Function Prototype:
double sin(double x);
->Example :
#include <stdio.h>
#include <math.h>
int main() {
double angle = 1.0; // Angle in radians
double result = sin(angle);
printf(“The sine of %.2f radians is %.2f\n”, angle, result);
return 0;
}
(iv) log(): Natural Logarithm Function
->Purpose: Calculates the natural logarithm (base e) of a given number.
->Function Prototype:
double log(double x);
Example:
#include <stdio.h>
#include <math.h>
int main() {
double num = 10.0;
double result = log(num);
printf(“Natural logarithm of %.2f is %.2f\n”, num, result);
return 0;
}
(v) fabs(): Absolute Value Function for Floating-Point Numbers
->Purpose: Calculates the absolute value of a floating-point number.
->Function Prototype:
double fabs(double x);
#include <stdio.h>
#include <math.h>
int main() {
double num = -7.5;
double result = fabs(num);
printf(“The absolute value of %.2f is %.2f\n”, num, result);
return 0;
}
(B)Explain switch….case statement in detail.
Ans :-
->The switch…case statement in C is a control flow statement used for decision-making. It allows you to select a choice from multiple options based on the value of an expression
->The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possibles values of a single variable called switch variable.
->This structure is particularly useful when you have a variable that can take different values, and you want to execute different code for each possible value. Here’s the detailed explanation of the switch…case statement:
Syntax:-
switch (expression) {
case constant1:
// Code to be executed if expression equals constant1
break;
case constant2:
// Code to be executed if expression equals constant2
break;
// Additional cases as needed
default:
// Code to be executed if expression doesn’t match any constant
}
Components:
(i)switch keyword:
->Indicates the beginning of the switch statement.
expression:
->A variable or expression whose value is tested against various case constants.
The result of this expression determines which case is executed.
(ii)case labels:
->Constants or literal values against which the expression is compared.
->If the expression matches a case constant, the corresponding block of code is executed.
(iii)break statement:
->Terminates the switch statement and prevents fall-through to subsequent case statements.
->Without break, the control will “fall through” to the next case, potentially executing unintended code.
(iv)default case:
->Optional and used for handling the situation where the expression doesn’t match any of the specified case constants.
->Similar to an else statement in an if…else construct.
Example :-
#include <stdio.h>
int main() {
int day = 3;
switch(day) {
case 1:
printf(“Monday\n”);
break;
case 2:
printf(“Tuesday\n”);
break;
case 3:
printf(“Wednesday\n”);
break;
case 4:
printf(“Thursday\n”);
break;
case 5:
printf(“Friday\n”);
break;
default:
printf(“Weekend\n”);
}
return 0;
}

(C)Explain exit control loop in detail.
Ans :-
Exit control loop in C to examine the termination condition for an exit. Control would leave the main body of the loop if the evaluation for the termination condition yielded a true result. Otherwise, the control makes another entry inside the loop.
This kind of loop often deals with the loop’s exit control statement.
DO WHILE LOOP
->The most applicable illustration of an exit control loop is the do-while loop.
->The while loop has been modified to become the do-while loop.
->The do-while loop is the most appropriate loop when it is necessary to run the program and do certain activities at least once.
Syntax :-
do
{
// main body of the do-while loop
}
while (termination condition/ test expression);
while (termination condition/ test expression);
->Do-while loop:
(i)An exit control loop is the do-while loop.
(ii)The termination condition/test expression is assessed at exit in the do-while loop.
(iii)The usage of the semicolon, which designates the end of the do-while loop, at the conclusion of the termination condition in the do-while loop is a requirement.
Example :-
do
{
printf(“\n%d”,i);
i++;
} while(i<=6) ;
(ii)While loop:
->An entrance control loop is the while loop.
->The while loop evaluates the test expression and termination condition as soon as it enters the loop.
->The while loop does not require anything to be executed after the termination condition.
Syntax:
while(condition)
{
// loop body
}
Example:
#include <stdio.h> // standard program line for input and output
#include <conio.h> // libraries
void main()
{
float x, y, answer; // declaration of float datatype variables
int choice; // naming variables with the int datatype
do
{
printf(“\n 1.Addition \n 2.Subtraction \n 3.Multiplication \n 4.Division \n 5.Exit”);
// by giving the user an increasing number of options
printf(“\n Enter Your Choice: “); // using the user’s input
scanf(“%d”, &choice); // putting a user-entered value into a variable
if(choice!= 5)
{
printf(“\n Enter X : ” ); // using the user’s input
scanf(“%f”, &x); // putting a user-entered value into a variable
printf(“\n Enter Y : ” ); // using the user’s input
scanf(“%f”, &y); // putting a user-entered value into a variable
}
switch(choice)
{
case 1: // addition case
answer = x + y; // basic operations in addition
printf(“\n the addition of %f and %f is : %f”, x, y, answer);
//answer will be in float datatype
break;
case 2: // subtraction case
answer = x – y; // basic operations in substraction
printf(“\n the subtraction of %f and %f is : %f”, x, y, answer);
//answer will be in float datatype
break;
case 3: // multiplication case
answer = x * y; // basic operations in multiplication
printf(“\n the multiplication of %f and %f is : %f”, x, y, answer);
//answer will be in float datatype
break;
case 4: // division case
answer = x / y; // basic operations in division
printf(“\n the division of %f and %f is : %f”, x, y, answer);
//answer will be in float datatype
break;
case 5:
exit(0); // exit operation
default: // program line to handle user-input errors
printf(“\n sorry, you have entered the invalid input!!!”);
}
getch();
} while(choice!= 5);
}
(D)Write a short note on one dimensional array.
Ans :-
-> A one-dimensional array in programming is a collection of elements of the same data type arranged in a linear sequence.
->It is one of the simplest and most fundamental data structures, providing a way to store and access a fixed-size collection of elements using a single identifier (array name) and an index or subscript
->One-dimensional arrays are the building blocks of more complex data structures and algorithms.
-> They provide a simple and efficient way to organize and manipulate collections of data in a program.
Here are some key points about one-dimensional arrays:
(1)Declaration:
In C, the declaration of a one-dimensional array involves specifying the data type of its elements and the array’s name followed by its size in square brackets [].
->int numbers[5]; // Declaration of an integer array with size 5
(2) Initialization:
You can initialize the elements of an array during declaration or later in the program.
->int numbers[5] = {1, 2, 3, 4, 5}; // Initialization during declaration
(3) Indexing:
Array elements are accessed using an index or subscript, starting from 0 for the first element.
int thirdElement = numbers[2]; // Accessing the third element (index 2)
(4) Size:
The size of a one-dimensional array is fixed during declaration and cannot be changed during the program’s execution.
int numbers[5]; // Array size is 5
(5)Traversal:
You can traverse through the elements of an array using loops, such as ‘for’ or ‘while’.
for (int i = 0; i < 5; i++) {
printf(“%d “, numbers[i]);
}
(6) Common Operations:
One-dimensional arrays are commonly used for tasks like storing lists of items, representing vectors, and performing mathematical operations on sets of data.
// Summing the elements of an array
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
(7)Memory Representation:
In memory, the elements of a one-dimensional array are stored in contiguous locations.
(8)Limitations:
One-dimensional arrays have a fixed size, which can be a limitation when the number of elements is not known at compile time.

Q-4Answer the following questions. (Any three) (15)

(A)Write a short note on pointer.
Ans :-
-> A pointer in programming is a variable that stores the memory address of another variable.
-> Pointers are a powerful feature in many programming languages, allowing for dynamic memory allocation, efficient manipulation of data structures, and direct access to memory locations. Here are some key points about pointers:
(1)Declaration:
A pointer is declared using the data type of the variable it will point to, followed by an asterisk *, and the name of the pointer variable.
int *ptr; // Declaration of an integer pointer
(2) Initialization:
-> Pointers are typically initialized with the memory address of another variable using the address-of operator ‘&’.
int x = 10;
int *ptr = &x; // Pointer ‘ptr’ now holds the address of variable ‘x’
(3) Dereferencing:
->Dereferencing a pointer means accessing the value at the memory address it points to. It is done using the dereference operator *.
int y = *ptr; // ‘y’ now holds the value stored at the memory address pointed to by ‘ptr’
(4)Dynamic Memory Allocation:
->Pointers are commonly used for dynamic memory allocation, where memory is allocated at runtime using functions like malloc() (in C) or new (in C++).
int *dynamicArray = (int*)malloc(5 * sizeof(int));
(5) Pointers and Arrays:
->Pointers and arrays are closely related. An array name itself is a constant pointer pointing to the first element of the array.
int arr[5] = {1, 2, 3, 4, 5};
int *arrPtr = arr; // ‘arrPtr’ points to the first element of the array ‘arr’
(6) Pointer Arithmetic:
->Pointers can be incremented or decremented to move to the next or previous memory location.
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // ‘ptr’ points to the first element of the array ‘arr’
int secondElement = *(ptr + 1); // Accessing the second element using pointer arithmetic

(7) Null Pointers:
->Pointers can be assigned the value NULL to indicate that they do not point to any valid memory location.
int *nullPtr = NULL;
(8) Pointer to Functions:
->Pointers can also be used to store addresses of functions, allowing for dynamic function calls.
int add(int a, int b) {
return a + b;
}
int (*ptrToFunc)(int, int) = add; // Pointer to a function
-Pointers are a fundamental concept in C and C++ programming, providing a level of control over memory that is essential for certain applications. While they offer great flexibility, improper use of pointers can lead to issues such as memory leaks, segmentation faults, and undefined behavior. Understanding pointers is crucial for systems programming, low-level operations, and certain advanced programming techniques.

(B)Explain jumping statement in detail with an example.
Ans :-
-> Jump statements in programming are used to alter the normal flow of control within a program.
-> here are three main jump statements in the C programming language: ‘break’, ‘continue’, and ‘goto’. I’ll explain each one with examples:
1. ‘break’ Statement:
->The ‘break’ statement is used to terminate the execution of a loop or switch statement prematurely. It is often used to exit a loop based on a certain condition.
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
printf(“%d “, i);
}
return 0;
}
2. ‘continue’ Statement:
-> The continue statement is used to skip the rest of the code inside a loop for the current iteration and proceed to the next iteration.
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the rest of the loop body for i = 3
}
printf(“%d “, i);
}
return 0;
}

3. ‘goto’ Statement:
-> The goto statement is used to transfer control to a labeled statement within the same function. However, the use of goto is generally discouraged because it can make code less readable and harder to maintain.
#include <stdio.h>
int main() {
int i = 1;
loop_start: // Label
if (i <= 5) {
printf(“%d “, i);
i++;
goto loop_start; // Jump to the labeled statement
}
return 0;
}
-> It’s important to use jump statements judiciously, as excessive use of break, continue, and goto can make the code less readable and more prone to errors. In many cases, there are alternative ways to structure code without the need for these statements.
(C)Explain linear search method of one-dimensional array with an example.
Ans :-
-> Linear search, also known as sequential search, is a simple searching algorithm that finds the position of a target value within a one-dimensional array.
-> The search starts from the beginning of the array and proceeds sequentially until the target value is found or the entire array has been traversed.
Linear Search Algorithm:
-> Start from the first element of the array.
->Compare the target value with the current element.
->If the target value is found, return the index of the element.
->If the target value is not found, move to the next element in the array.
->Repeat steps 2-4 until the target value is found or the end of the array is reached.
->If the target value is not found after traversing the entire array, return a special value (e.g., -1) to indicate that the value is not present.
Example :-
#include <stdio.h>
int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Target found, return the index
}
}
return -1; // Target not found
}
int main() {
int numbers[] = {2, 8, 15, 23, 42, 5, 17, 34};
int targetValue = 17;
int arraySize = sizeof(numbers) / sizeof(numbers[0]);
int result = linearSearch(numbers, arraySize, targetValue);
if (result != -1) {
printf(“Target value %d found at index %d\n”, targetValue, result);
} else {
printf(“Target value %d not found in the array\n”, targetValue);
}
return 0;
}
Linear search is a straightforward algorithm, but it may not be the most efficient for large datasets. Its time complexity is O(n), where n is the size of the array. For more efficient searches, consider using algorithms like binary search on sorted arrays.
(D)Explain ternary and sizeof() operators in detail with an example.
Ans :-
(1)Ternary Operator (?:):
->The ternary operator, also known as the conditional operator, is a concise way to express an if-else statement in a single line. It has the following syntax:
condition ? expression_if_true : expression_if_false;
->If the condition is true, the entire expression evaluates to expression_if_true.
->If the condition is false, the entire expression evaluates to expression_if_false.
#include <stdio.h>
int main() {
int num = 10;
char* result = (num % 2 == 0) ? “even” : “odd”;
printf(“%d is %s\n”, num, result);
return 0;
}
(2) sizeof() Operator:
The sizeof() operator in C is used to determine the size, in bytes, of a variable or a data type. It can be used with variables, data types, or expressions.
#include <stdio.h>
int main() {
int num = 42;
size_t size = sizeof(num);
printf(“Size of num: %zu bytes\n”, size);
return 0;
}
#include <stdio.h>
int main() {
size_t size_of_int = sizeof(int);
size_t size_of_double = sizeof(double);
printf(“Size of int: %zu bytes\n”, size_of_int);
printf(“Size of double: %zu bytes\n”, size_of_double);
return 0;
}
OR
#include <stdio.h>
int main() {
int arr[5];
size_t size_of_arr = sizeof(arr);
printf(“Size of arr: %zu bytes\n”, size_of_arr);
return 0;
}
The sizeof() operator is particularly useful when dealing with memory allocation, working with arrays, or determining the size of structures in C. Note that the result of sizeof() is of type size_t.

Write an algorithm or a program to print factorial of inputted number (05)

The algorithm to calculate the factorial of a number.
1. Start
2. Read the input number (n).
3. Initialize a variable factorial to 1.
4. For i from 1 to n:
.Multiply factorial by i.
5. Print the value of factorial.
6. End
Example
#include <stdio.h>
int main() {
int n;
unsigned long long factorial = 1;
// Step 2: Read the input number
printf(“Enter a non-negative integer: “);
scanf(“%d”, &n);
// Check if the input is non-negative
if (n < 0) {
printf(“Factorial is not defined for negative numbers.\n”);
} else {
// Step 4: Calculate the factorial
for (int i = 1; i <= n; ++i) {
factorial *= i;
}
// Step 5: Print the result
printf(“Factorial of %d = %llu\n”, n, factorial);
}
return 0;
}
Explanation:
->The program reads a non-negative integer (n) as input.
->It checks if the input is non-negative, as the factorial is not defined for negative numbers.
->If the input is valid, it calculates the factorial using a loop that iterates from 1 to n.
->The result is printed.

Write an algorithm or a program to reverse a string. (05)

Algorithm:
1. Start
2. Read the input string.
3. Initialize two pointers, start pointing to the beginning of the string and end pointing to the end of the string.
4. Swap the characters at positions start and end.
5. Increment start and decrement end.
6. Repeat steps 4-5 until start is greater than or equal to end.
7. Print the reversed string.
8. End
C Program
#include <stdio.h>
#include <string.h>
// Function to reverse a string
void reverseString(char str[]) {
int start = 0;
int end = strlen(str) – 1;
// Swap characters until start is greater than or equal to end
while (start < end) {
// Swap characters at positions start and end
char temp = str[start];
str[start] = str[end];
str[end] = temp;
// Move to the next pair of characters
start++;
end–;
}
}
int main() {
char inputString[100];
// Step 2: Read the input string
printf(“Enter a string: “);
fgets(inputString, sizeof(inputString), stdin);
// Remove the newline character if present
if (inputString[strlen(inputString) – 1] == ‘\n’) {
inputString[strlen(inputString) – 1] = ‘\0’;
}
// Step 3-7: Reverse the string
reverseString(inputString);
// Step 8: Print the reversed string
printf(“Reversed string: %s\n”, inputString);
return 0;
}
Explanation:
->The program reads a string as input using fgets to handle spaces and newline characters.
-> It removes the newline character from the input string if present.
-> The reverseString function is used to reverse the string in-place.
-> The main function then calls reverseString and prints the reversed string.
Fun & Easy to follow
Works on all devices
Your own Pace
Super Affordable

Get Started Free

Volutpat diam ut venenatis tellus in metus. Gravida cum sociis natoque penatibus et magnis dis. Odio pellentesque diam volutpat commodo.