0% found this document useful (0 votes)
4 views34 pages

Assignment Answers Cpps

The document provides an overview of computers, programming languages, number systems, algorithms, flowcharts, data types, variables, operators, control flow statements, and loops in C programming. It explains different types of programming languages, the importance of algorithms and flowcharts, the structure of C programs, and various data types with examples. Additionally, it covers operators, control flow statements, and looping constructs in C, illustrating each concept with code examples.

Uploaded by

afreensamreen2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views34 pages

Assignment Answers Cpps

The document provides an overview of computers, programming languages, number systems, algorithms, flowcharts, data types, variables, operators, control flow statements, and loops in C programming. It explains different types of programming languages, the importance of algorithms and flowcharts, the structure of C programs, and various data types with examples. Additionally, it covers operators, control flow statements, and looping constructs in C, illustrating each concept with code examples.

Uploaded by

afreensamreen2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link] IS COMPUTER ? EXPLAIN DIFFERENT TYPES OF COMPUTER LANGUAGES?

Computer:A computer is an electronic device that process data and performs tasks according to a set
of instructions called a program. It can execute variety of operations, including calculations, data
storage and enables to solve problems and automate process.

High-Level Languages:

• Definition: Programming languages that are easy to understand and write, similar to human
language.

• Example: C,JAVA, Python etc….

• Explanation: In Python, you can write printf("Hello, World!") to display a message. This code is easy
to read and understand, making it high-level.

Low-Level Languages:

• Definition: Programming languages that are closer to machine code and provide more control over
hardware.

• Example: Assembly language

• Explanation: In Assembly language, you might write something like MOV AX, 1 to move a value into
a register. This is less readable but gives more direct control over the computer's operations.

Machine-Level Languages:

• Definition: The lowest level of programming, consisting of binary code that the CPU can directly
execute.

• Example: Binary code (e.g., 10101000)

• Explanation: This is the language the computer's hardware understands directly, but it’s very hard
for humans to read or write.

[Link] ABOUT NUMBER SYSTEMS WITH EXAMPLES EACH

Number System are the technique to represent numbers in computer system. Every value ur saving &
getting from computer memory has defined as number system.

NUMBER SYSTEM RADIX USED DIGITS EXAMPLE


Binary 2 0,1 (11101011)2
Octal 8 0,1,2,3,4,5,6,7 (360)8
Decimal 10 0,1,2,3,4,5,6,7,8,9 (240)10
Hexa Decimal 16 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F (F0)16

CONVERSIONS:

[Link] to other: * Divide number by base of other, write reminder from bottom to top.

Decimal to binary:
Ex:(12345)10

• Decimal to octal:
Ex:(12345)10
• Decimal to Hexa Decimal:
Ex: (12345)10

[Link] to Other:
• Binary to decimal:-Multiply the digit with 2 with place value
exponents, evaluate and becomes decimal.
Ex:

• Binary to Octal:-Divide them in 3 groups ,from least


significant(right) bits, to complete 3 groups add 0.
Ex:

• Binary to Hexa decimal: Divide it into 4 groups Ex:


[Link] to Other:
• Octal to binary:
Ex:

• Octal to Hexadecimal:
Ex:

• Octal to Decimal:
Ex:

[Link] to Other:
• Hexadecimal to Binary:
Ex:

• Hexadecimal to Decimal:
Ex:
• Hexadecimal to Octal:
Ex:

[Link] ABOUT NEED OF ALGORITHM AND FLOWCHARTS IN


PROGRAMMING WITH EXAMPLE
Need of algorithms in programming:
An algorithm is a step-by-step procedure or formula for solving a
problem or completing a task.

IMPORTANCE:
1. Problem solving:-Algorithms provide a clear method to
approach and solve complex problems systematically.
2. Clarity: Well-defined algorithms improve understanding and
communication among team members.
3. Reusability: Once created, algorithms can be reused in different
programs or projects.

Need for flow charts:


IT’s graphical representation, showing steps and their sequence
using symbols like(arrow,ovel,rectangle….ect…).
IMPORTANCE:
1. Visual Clarity: Flowcharts provide a clear visual outline
of the process, making it easier to understand and
analyze.
2. Debugging: They help identify logical errors by allowing
programmers to visualize the flow of operations.
3. Documentation: Flowcharts serve as documentation for
the algorithm, making it easier for others to follow the
logic.
4. Communication: They enhance communication among
team members by providing a universal way to represent
processes.
[Link] ABOUT STRUCTURE OF C PROGRAM
Any C program is consists of 6 main sections:
1. Documentation
2. Link
3. Global declaration ,function
4. Main function
5. Sub program
Documentation section:
It helps anyone to gat overview of the program consists of
comment lines (name,time,date..)
Link section:
The header files of the functions that are used in the program.
Definitions section:
All symbolic constants are written in definition section.
GDS:
It can be used any where in the program , declares used defined
Main function:
Necessary to have one main(),semicolon; and soon.
Declaration:
Variables must be declared before they are used.

[Link] ABOUT DATAYPES AND VARIABLES WITH EXAMPLE

Data Types:
Data types specify the type of data that a variable can store

1. Primary data type:


• Integer(int): used to store whole numbers(both +ve,-ve).
• Syntax: intvariable_name;
Ex: #include<stdio.h>
Int main(){
Int num=10;
Printf(“The value of num is:%d”,num);
return 0;}
Out put:
The value of num is:10
• float: used to store decimal numbers.
• Syntax: float variable_name;
Ex: #include<stdio.h>
Int main(){
Float pi=3.14;
Printf(“The value of pi is:%2f”,pi);
return 0;}
Out put:
• Double: used for double precision floating point.
• Syntax: double float variable_name;
Ex: #include<stdio.h>
Int main(){
Double float pi=3.14159
Printf(“The value of pi is:%2f”,pi);
return 0;}
Out put: The value of pi is:3.14159
• Char: used for single characters.
Syntax: char variable_name;
Ex: #include<stdio.h>
int main(){
char grade=’A’;
printf(“The grade is:%c”,grade);
return 0;}
Out put: The grade is: A
2. Derived Data Types :
• Array: A collection of same elements of the same data
type.
Syntax: data_type array_name[size];
Ex: #include int main() {
int numbers[3] = {1, 2, 3};
printf("First number: %d", numbers[0]);
return 0; }
Output: First number: 1
[Link] defined data types:
• Structure(struct): A user defined data type that group
related variables.
Syntax:
struct structure_name
{ data_type member1; data_type member2; };
Ex: #include struct
Person { char name[20];
int age;
}
int main()
{ struct Person person1 = {"John", 25};
printf("Name: %s, Age: %d", [Link], [Link]);
return 0; }
Output: Name: John, Age: 25

Variables
A variable is a named storage location in memory that
holds a value. Each variable has a specific data type that
determines what kind of data it can hold.
Characteristics of Variables:
• Declaration: You must declare a variable before using it,
specifying its type and name.
o Example: int count;

• Initialization: You can assign an initial value to a variable at the


time of declaration or later in the program.
o Example: int count = 10;

• Scope: The region of the program where the variable is


accessible. Variables can have local or global scope.
• Data type: variables can hold different types of data eg:
{int,float,char….}
Program on variable and data type:
#include <stdio.h>

int main() {
// Variable declarations and initializations
int age = 30; // Integer variable
float height = 5.9; // Float variable
double weight = 150.5; // Double variable
char initial = 'J'; // Char variable

// Array of integers
int scores[5] = {85, 90, 78, 88, 92};
// Structure definition and initialization
struct Person {
char name[50];
int age;
};

struct Person person1 = {"Alice", 28};

// Output the values


printf("Age: %d\n", age);
printf("Height: %.1f\n", height);
printf("Weight: %.1f\n", weight);
printf("Initial: %c\n", initial);

// Output scores
printf("Scores: ");
for (int i = 0; i < 5; i++) {
printf("%d ", scores[i]);
}
printf("\n");

// Output structure values


printf("Name: %s, Age: %d\n", [Link],
[Link]);

return 0;
}

Operators in Programming
Operators are symbols or keywords that perform
operations on variables and values. They help manipulate
data, perform calculations, and make decisions.

Types of Operators:
1. Arithmetic Operators:
Used for basic mathematical operations.
o + (Addition): a + b

o - (Subtraction): a - b

o * (Multiplication): a * b

o / (Division): a / b

o % (Modulus): a % b (Remainder)

EX: a = 10
b=3
print("Addition:", a + b)
print("Modulus:", a % b)
[Link] (Comparison) Operators:
Compare values and return True or False.
• == (Equal to): a == b

• != (Not equal to): a != b

• > (Greater than): a > b

• < (Less than): a < b

• >= (Greater than or equal to): a >= b

• <= (Less than or equal to): a <= b

Ex: a = 5
b=8
print("Is a equal to b?", a == b)
print("Is a less than b?", a < b)
[Link] Operators:
Used to combine conditional statements.
• and: Returns True if both conditions are True.

• or: Returns True if at least one condition is True.

• not: Reverses the result of the condition

Ex: x = 5
print(x > 3 and x < 10) # Both conditions are True
print(x > 3 or x < 2) # One condition is True
print(not(x > 3)) # Reverses the result
[Link] Operators:
Used to assign values to variables.
• =: Assign value.
• +=: Add and assign.
• -=: Subtract and assign.
Ex: a = 5
a += 3 # Equivalent to a = a + 3
print(a)
[Link] and Decrement Using += and -=
• Increment (+=): Adds a value to the variable.
• Decrement (-=): Subtracts a value from the variable.
Ex: # Initialize a variable
x=5

# Increment
print("Initial value of x:", x)
x += 1 # Equivalent to x = x + 1
print("After incrementing by 1:", x)

# Decrement
x -= 1 # Equivalent to x = x - 1
print("After decrementing by 1:", x)
Control Flow Statements in C
Flow control statements are used to make decisions, repeat
blocks of code, and jump to specific sections of code.
• if statement: Executes a block of code if a certain condition is
true
Syntax:
if(condition)
{ // Statements to execute if // condition is true }
1. #include
2. int main(){
3. int number=0;
4. printf("Enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. return 0; 10. }
if-else statement: Executes one block of code if a condition is
true and another block if the condition is false.
Syntax :
if (condition)
{ // statements to execute if condition is true }
else
{ // statements to execute if condition is false }
int main()
{ int i = 20;
if (i < 15)
{ printf("i is smaller than 15");
}
else { printf("i is greater than 15");
}
return 0; }
• else-if statement: Executes one block of code if a condition is
true and another block if the other condition is true
1. #include <stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number==10){
7. printf("number is equals to 10");
8. }
9. else if(number==50){
10. printf("number is equal to 50");
11. }
12. else if(number==100){
13. printf("number is equal to 100");
14. }
15. else{
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }
• nested-if statement: It has if statements inside the another if
statement.
Syntax:
if (condition1)
{ // Executes when condition1 is true
if (condition_2)
{ // statement 1 }
else
{ // Statement 2 } }
else
{ if (condition_3)
{ // statement 3 }
else
{ // Statement 4 } }
EX: #include <stdio.h>
int main() {
int num;
// Take input from the user
printf("Enter a number: ");
scanf("%d", &num);
// Outer if-else to check if the number is positive, negative, or
zero
if (num > 0) {
printf("The number is positive.\n");
// Nested if to check if the number is even or odd
if (num % 2 == 0) {
printf("It is even.\n");
} else {
printf("It is odd.\n");
}
} else if (num < 0) {
printf("The number is negative.\n");
} else {
printf("The number is zero.\n");
}
return 0;
}
. Switch Statement
Used when multiple conditions are checked for a single
variable.
Syntax: switch (expression) {
case constant1:
// Code for case 1
break;
case constant2:
// Code for case 2
break;
default:
// Code if no case matches
}
Ex: #include <stdio.h>

int main() {
int day = 2;

switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
default:
printf("Invalid day\n");
}

return 0;
}
[Link] ABOUT LOOPS WITH EXAMPLE PROGRAM
Loops in C Programming
Loops in C allow a set of instructions to be executed repeatedly
until a certain condition is met. They are essential for tasks that
require repetition without writing redundant code.
The most commonly used looping statements are:

Types of Loops in C
1. for Loop
2. while Loop
3. do-while Loop

1. for Loop
The for loop is used when the number of iterations is known in
advance. It consists of initialization, condition, and
increment/decrement steps.
Syntax:
for (initialization; condition; increment/decrement)
{
// Code to execute
}
Example: #include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}
2. while Loop
The while loop is used when the number of iterations is not
known in advance. It continues until the condition becomes
false.
Syntax:
while (condition) {
// Code to execute
}
EX:#include <stdio.h>

int main() {
int i = 5;
while (i > 0) {
printf("%d\n", i);
i--; // Decrement i by 1
}
return 0;
}
3. do-while Loop
The do-while loop ensures the code is executed at least once,
even if the condition is false. It checks the condition after the
first iteration.
Syntax:
do {
// Code to execute
} while (condition);
EX: #include <stdio.h>

int main() {
int i = 1;
do {
printf("Hello\n");
} while (i > 1); // Condition is false, but loop runs once
return 0;
}
4. Using break and continue in Loops
• break: Exits the loop immediately.
• continue: Skips the current iteration and moves to the next
one.
Ex: #include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
if (i == 3)
break; // Exit the loop when i is 3
printf("%d\n", i);}
for (int i = 0; i < 5; i++) {
if (i == 2)
continue; // Skip iteration when i is 2
printf("%d\n", i);
}
return 0;
}
[Link] ABOUT ARRAYS WITH EXAMPLE PROGRAMS
Arrays in C Programming
An array is a collection of elements of the same data type
stored in contiguous memory locations. Arrays help manage
large data sets efficiently by grouping related data under a
single name.

Types of Arrays in C
1. One-dimensional Array
2. Two-dimensional Array
3. Multi-dimensional Array

1. One-Dimensional Array
A one-dimensional (1D) array stores a list of elements in a
single row.
Syntax:
data_type array_name[size];
Ex: #include <stdio.h>

int main() {
int arr[5] = {10, 20, 30, 40, 50}; // Initialize the array

printf("Array elements:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]); // Access each element
}

return 0;
}
2. Two-Dimensional Array
A two-dimensional (2D) array stores data in a matrix-like
format (rows and columns).
Syntax: data_type array_name[rows][columns];
EX: #include <stdio.h>
int main() {
int matrix[2][2] = {{1, 2}, {3, 4}}; // Initialize 2x2 matrix
printf("Matrix elements:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", matrix[i][j]); }// Access matrix elements
printf("\n");}
return 0;
}
3. Multi-Dimensional Array
C also supports multi-dimensional arrays (3D, 4D, etc.).
However, they are generally used less frequently as they
become complex to manage.
Syntax:
data_type array_name[dim1][dim2][dim3]...;
Input and Output in Arrays
You can also take input for arrays from the user at runtime.
Ex
#include <stdio.h>
int main() {
int arr[5];
// Input array elements from the user
printf("Enter 5 numbers:\n");
for (int i = 0; i < 5; i++) {
scanf("%d", &arr[i]); // Store user input in array
}
// Display the array elements
printf("You entered:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Advantages of Arrays in C
1. Efficient Storage: Store multiple values under one variable.
2. Easier Access: Access any element using the index.
3. Faster Execution: Contiguous memory allocation speeds up
processing.
[Link] ABOUT LINEAR SEARCH WITH EXAMPLE PROGRAM
Linear search is a straightforward searching technique where
each element of the array is checked sequentially until the
desired element is found or the end of the array is reached.
It works for both sorted and unsorted arrays but is inefficient
for large datasets, as it requires checking each element one-by-
one.
Algorithm of Linear Search
1. Start from the first element.
2. Compare the element with the target element.
3. If the elements match, return the index.
4. If not, move to the next element.
5. If the target element is not found after checking all elements,
return -1.
Example Program in C:
#include<stdio.h>
int main() {
int arr[100], n, i, search; // Taking input for the size of the array
printf("Enter the number of elements in the array: ");
scanf("%d", &n); // Taking input for array elements
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]); } // Input the element to search
printf("Enter the element to search: ");
scanf("%d", &search); // Linear search logic
for (i = 0; i < n; i++) {
if (arr[i] == search) {
printf("Element %d found at position %d.\n", search, i + 1);
return 0; // Exit the program after finding the element } } // If
the element is not found in the array
printf("Element %d not found in the array.\n", search);
return 0; }

Time Complexity
• Best Case: O(1) — When the element is at the first position.
• Worst Case: O(n) — When the element is at the last position or
not presen

Advantages and Disadvantages


• Advantages:
o Simple to implement.

o Works for both sorted and unsorted arrays.

• Disadvantages:
o Not efficient for large datasets due to O(n) time

complexity.

[Link] ABOUT FUNCTIONS WITH EXAMPLES


A function in C is a collection of statements designed to execute
a specific task when invoked.
Basic Structure of a Function:
return_type function_name(parameter_type parameter_name)
{
// Function body
// Code to execute
return value; // Optional
}
Components:
1. Return Type: The data type of the value returned by the
function (e.g., int, float, void).
2. Function Name: A descriptive name for the function.
3. Parameters: Inputs to the function; can be zero or more.
4. Function Body: The block of code that defines what the
function does.
Example 1: Function with No Parameters and No Return Value
#include <stdio.h>
// Function definition
void printMessage() {
printf("Hello, welcome to the C programming world!\n");
}
int main() {
// Function call
printMessage();
return 0;
}

Example 2: Function with Parameters and a Return Value


#include <stdio.h>
// Function declaration
int add(int a, int b) {
return a + b; // Return the sum of a and b
}
int main() {
int num1, num2, sum;
// User input
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);

// Function call
sum = add(num1, num2); // Call the add function
// Display the result
printf("Sum: %d\n", sum);
return 0;
}

Example 3: Function with Multiple Return Values (Using


Pointers)
#include <stdio.h>
// Function to swap two numbers
void swap(int *x, int *y) {
int temp;
temp = *x; // Store the value at address x in temp
*x = *y; // Assign value at address y to address x
*y = temp; // Assign temp to address y}
int main() {
int num1 = 5, num2 = 10;
printf("Before swapping: num1 = %d, num2 = %d\n", num1,
num2);
// Call swap function
swap(&num1, &num2); // Pass addresses of num1 and num2
printf("After swapping: num1 = %d, num2 = %d\n", num1,
num2);
return 0;
}
Summary:
1. Function without arguments and without return value: o No
input and no output, just performs an action.
2. Function without arguments and with return value: o No
input, but returns a value.
3. Function with arguments and without return value: o Takes
input (arguments) but does not return anything.
4. Function with arguments and with return value: o Takes input
and returns a result after performing some operation.

[Link] about breaking control statements. i)break


ii)continue.
Control statements in C help to alter the flow of execution in a
program. Two important control statements used for controlling
loops are break and continue.
1. break Statement
The break statement is used to terminate a loop or switch
statement prematurely. When a break statement is
encountered, the control jumps to the statement immediately
following the loop or switch block.
Key Points:
• It can be used in for, while, do-while, and switch statements.
• It is typically used to exit a loop based on a specific condition.
Ex:
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
printf("%d ", i);
}
printf("\nLoop terminated at i = 5.\n");
return 0;
}
2. continue Statement
The continue statement is used to skip the current iteration of
a loop and move to the next iteration. When continue is
encountered, the remaining code inside the loop for that
iteration is skipped, and control jumps to the next iteration of
the loop.
Key Points:
• It can be used in for, while, and do-while loops.
• Useful for skipping certain conditions while still allowing the
loop to run.
Ex:
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip the rest of the loop for even numbers
}
printf("%d ", i);
}
printf("\nAll even numbers skipped.\n");
return 0;
}
PROGRAMS:
[Link] a C Program to Swap the values of two variables.

#include<stdio.h>
Int main(){
Int num1,num2;
Printf(“Enter num1:”);
scanf("%d", &num1);
printf("Enter num2: ");
scanf("%d", &num2);
printf("Before swapping: num1= %d, num2 = %d\n", num1,
num2);
int temp = num1; num1 = num2; num2= temp;
printf("After swapping: num1 = %d, num2 = %d\n", num1,
num2);
return 0; }

[Link] a C program using Arithmetic operators in C


#include <stdio.h>
int main() {
float num1, num2;
float sum, difference, product, quotient, remainder;
printf("Enter first number: ");
scanf("%f", &num1);
printf("Enter second number: ");
scanf("%f", &num2);
sum = num1 + num2;
difference = num1 - num2;
product = num1 * num2;
quotient = num1 / num2;
remainder = (int)num1 % (int)num2;
printf("Sum: %.2f\n", sum);
printf("Difference: %.2f\n", difference);
printf("Product: %.2f\n", product);
printf("Quotient: %.2f\n", quotient);
printf("Remainder (of integer parts): %d\n", (int)remainder);
return 0;
}

[Link] a C Program For Addition of two matrices.


#include <stdio.h>

int main() {
int rows, cols;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
int matrix1[rows][cols], matrix2[rows][cols], sum[rows][cols];

printf("Enter elements of the first matrix:\n");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("matrix1[%d][%d]: ", i, j);
scanf("%d", &matrix1[i][j]);
}
}
printf("Enter elements of the second matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("matrix2[%d][%d]: ", i, j);
scanf("%d", &matrix2[i][j]);
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
} printf("Sum of the two matrices:\n");
for (int i = 0; i < rows; i++)
{ for (int j = 0; j < cols; j++) {
printf("%d ", sum[i][j]);
} printf("\n"); }
return 0; }

[Link] of a given positive integer value

#include<stdio.h>
int main() {
int n, fact = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
fact = fact * i;
printf("Factorial of %d is %d\n", n, fact);
return 0; } }
[Link] or odd program
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number % 2 == 0) {
printf("%d is an even number.\n", number);
} else {
printf("%d is an odd number.\n", number);
}
return 0;
}
[Link] of number
#include <stdio.h>
int main() {
int count, i;
float number, sum = 0.0;
printf("Enter the number of elements you want to sum: ");
scanf("%d", &count);
for (i = 0; i < count; i++) {
printf("Enter number %d: ", i + 1);
scanf("%f", &number);
sum += number; // Add the entered number to sum
}
printf("The sum of the entered numbers is: %.2f\n", sum);
return 0;
}

You might also like