LDP Assignment

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

UNIT- 1: Introduction to Programming Languages

Q1. What is Machine Language?


Ans)
1. Machine language is a low-level language composed of binary code, consisting of 0s and
1s.
2. It is also referred to as machine code or object code and is challenging for humans to
understand.
3. Computers exclusively comprehend machine language, making it the only language they
directly process.
4. All programs, including those in languages like Swift or C++, are ultimately translated into
machine language before execution on a computer's processor.
5. Example:-
An example of machine language is given below, which will display the letter "A"
1000 times on the screen.

1. 169 1 160 0 153 0 128 153 0 129 153 130 153 0 131 200 208 241 96

Q2. List out types of programming language and explain.


Ans)
Machine level language OR Low level language
• It is language of 0’s and 1’s.
• Computer directly understand this language.

Assembly language
• It uses short descriptive words (MNEMONIC) to represent each of the machine
language instructions.
• It requires a translator knows as assembler to convert assembly language into
machine language so that it can be understood by the computer.

Higher level language


• It is a machine independent language.
• We can write programs in English like manner and therefore easier to learn and use.

Q3. Explain Basic of block diagram and functions of various components of computer.
Ans)
A computer can process data, pictures, sound and graphics. They can solve
highly complicated problems quickly and accurately. A computer as shown in Fig.
performs basically five major computer operations or functions irrespective of
their size and make. These are
1. Input: This is the process of entering data and programs in to the computer
system. You should know that computer is an electronic machine like any other
machine which takes as inputs raw data and performs some processing giving
out processed data.

2. Storage: The process of saving data and instructions permanently is known


as storage. Data has to be fed into the system before the actual processing
starts. It is because the processing speed of Central Processing Unit (CPU) is so
fast that the data has to be provided to CPU with the same speed. Therefore the
data is first stored in the storage unit for faster access and processing.

3. Processing: The task of performing operations like arithmetic and logical


operations is called processing. The Central Processing Unit (CPU) takes data
and instructions from the storage unit and makes all sorts of calculations based
on the instructions given and the type of data provided. It is then sent back to the
storage unit.

4. Output: This is the process of producing results from the data for getting useful
information. Similarly the output produced by the computer after processing must
also be kept somewhere inside the computer before being given to you in human
readable form.

5. Control: The manner how instructions are executed and the above operations
are performed. Controlling of all operations like input, processing and output are
step by step processing of all operations inside the computer.
Q4. Explain Flowcharts and Algorithms.
Ans)
Flowcharts

1. A flowchart is a graphical representation of the steps a program takes to process


data. In this, we can use several geometric patterns to illustrate the numerous actions
the program carries out.
2. It is easy to design and also very user friendly.
3. A flowchart can be used in different disciplines to describe a process.
4. It is easy to debug the errors in flowcharts.
5. Simple to display branching and looping.

Algorithms

1. An algorithm is a procedure or set of rules that defines how a program is to be


executed.
2. It is comparatively difficult to create and also a bit challenging to be understood by
a layman.
3. Algorithms are used in the domain of mathematics and computer science.
4. It is difficult to debug the errors in algorithms.
5. Hard to display branching and looping.

Q5. What is Compiler, interpreter and assembler.


Ans)
1. Compiler:
- A compiler is a program that translates the entire source code written in a high-level
programming language (like C) into machine code or an equivalent low-level code.
- It generates a standalone executable file, which can be executed independently without
needing the original source code.
- Compilation is done before the program is run, and errors are typically reported after the
entire code is processed.

2. Interpreter:
- An interpreter, on the other hand, translates the source code into machine code and
executes it line by line.
- It doesn't produce a standalone executable; instead, it interprets and executes the code
directly.
- Errors are reported as soon as they are encountered, allowing for easier debugging during
runtime.

3. Assembler:
- Assemblers are used for low-level programming languages like assembly language, which
is a human-readable representation of machine code.
- An assembler translates assembly language code into machine code or object code.
- Unlike compilers and interpreters, assemblers deal with a one-to-one correspondence
between assembly language instructions and machine code instructions.
UNIT- 2: Fundamentals and Control Structure in C

Q1. Explain Basic Structure of C.


Ans) A C program is divided into six sections:
1. Documentation- Consists of the description of the program, programmer's name,
and creation date. These are generally written in the form of comments.
2. Link- All header files are included in this section which contains different
functions from the libraries. A copy of these header files is inserted into your
code before compilation.
3. Definition- Includes preprocessor directive, which contains symbolic constants.
E.g.: #define allows us to use constants in our code. It replaces all the constants
with its value in the code.
4. Global Declaration- Includes declaration of global variables, function declarations, static
global variables, and functions.
5. Main() Function- For every C program, the execution starts from the main() function. It
is mandatory to include a main() function in every C program.
6. Subprograms- Includes all user-defined functions (functions the user provides).
They can contain the inbuilt functions and the function definitions declared in the
Global Declaration section. These are called in the main() function.

Example:-

Q2. Explain constants and variables.


Ans)
Constants :-

1. A constant is a name given to the variable whose values can’t be altered or changed.
2. A constant is very similar to variables in the C programming language, but it can hold
only a single variable during the execution of a program.
3. It means that once we assign value to the constant, then we can’t change it
throughout the execution of a program- it stays fixed.
Example of constant-

#include<stdio.h>
void main(){
int q = 9 ;
const int a = 10 ;
q = 15 ;
a = 100 ; // creates an error
printf(“q = %d\na = %d”, q, a ) ;
}

Output- assignment of read-only variable 'a'

Variables
1. Variables are containers for storing data values, like numbers and characters.
2. In C, there are different types of variables (defined with different keywords), for example:
3. int - stores integers (whole numbers), without decimals, such as 123 or -123
4. float - stores floating point numbers, with decimals, such as 19.99 or -19.99
5. char - stores single characters, such as 'a' or 'B'.
6. Char values are surrounded by single quotes

Example-

#include <stdio.h>
int main() {
// Create variables
int myInt = 15;
// Integer (whole number)

float myFlo = 5.99;


// Floating point number

char myChar = 'D';


// Character

printf("%d\n", myInt);
printf("%f\n", myFlo);
printf("%c\n", myChar);

return 0;

Output-
15

5.990000

D
Q3. Explain operators.
Ans) An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions.

C language is rich in built-in operators and provides the following types of operators −

1. Arithmetic Operators :- An arithmetic operator performs mathematical operations such as


addition, subtraction, multiplication, division etc on numerical values (constants and variables).
2. Relational Operators :- A relational operator checks the relationship between two operands. If the
relation is true, it returns 1; if the relation is false, it returns value 0.
3. Logical Operators :- An expression containing logical operator returns either 0 or 1
4. Assignment Operators:- An assignment operator is used for assigning a value to a variable.
5. Increment and Decrement operators :- Increment (++) and Decrement (--) are unary operators.
Increment (++) operator adds 1 to operand. Decrement (--) operator subtracts 1 from operand.
6. Ternary Operators/Conditional Operators :- We use the ternary operator in C to run one code
when the condition is true and another code when the condition is false.
7. Bitwise Operators :- During computation, mathematical operations like: addition,
subtraction, multiplication, division, etc are converted to bit-level which makes processing faster
and saves power.
8. Special Operators :- Special operators in programming, like the ternary and sizeof operators, add
unique functionality such as conditional evaluations and variable size determination.

Q4. Define break, continue and go-to statement.


Ans)
Break statement
• The break is a keyword in C which is used to bring the program control out of the loop.
• The break statement is used inside loops or switch statement.
• The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the
inner loop first and then proceeds to outer loops.

Continue statement
• The continue statement in C programming works somewhat like the break statement.
Instead of forcing termination, it forces the next iteration of the loop to take place, skipping
any code in between.

• For the for loop, continue statement causes the conditional test and increment portions
of the loop to execute. For the while and do...while loops, continue statement causes the
program control to pass to the conditional tests.

Go-to statement
• Go-to is an virtual loop
• The go-to statement allows us to transfer control of the program to the specified label.
• Go-to is keyword
Q5. Explain Nesting of control structures.
Ans)
In C, nesting of control structures refers to the practice of placing one control
structure (like a loop or conditional statement) inside another.

This creates a hierarchical or layered structure for controlling the flow of the
program.

For example:
#include <stdio.h>
int main() {
int i, j;
for (i = 1; i <= 5; i++) {
// Outer loop
for (j = 1; j <= i; j++) {
// Inner loop
printf("* ");
}
printf("\n");
}
return 0;
}

Q6. Explain Data type.


Ans)
Data types are the type of data stored in a C program. Data types are used while defining a variable
or functions in C. It’s important for the compiler to understand the type of predefined data it is
going to encounter in the program.

In general terms, a data type is an attribute that tells a computer how to interpret the value. Types
Of Data Types In C- There are majorly two main categories of Data Type in C:

1. Primitive/Primary Data Type- The C programming language has five primitive or primary data
types.

2. Derived Data Types- Derived data types are primary data types that are grouped together. You can
group many elements of similar data types. These data types are defined by the user.

Q7. Define Constants and Variables.


Ans)
Constants are values that remain fixed throughout the program and are declared using the
`const` keyword or preprocessor directives like `#define` (e.g., `const float PI = 3.14;`).

Variables in C are named storage locations whose values can change during program
execution, declared with a specific data type (e.g., `int x;`).
Q8. What is type conversion? Explain it.
Ans)
Type conversion in C are of 2 types :-

1) Implicit Type Conversion- Implicit type casting means conversion of data types without losing its
original meaning.

Example code:-
#include <stdio.h>
main()
{
int number = 1;
char character = 'J'; /*ASCII value is 74 */
int sum;
sum = number + character;
printf("Value of sum : %d\n", sum ); }

Output- Value of sum : 75

2) Explicit Type Conversion- Some scenarios of program in which we may have to force type
conversion Explicitly that is called Explicit type Conversion Suppose we have a variable div that
stores the division of two operands which are declared as an int data type.

Example code-

#include<stdio.h>
int main()
{
float a = 1.2; //int b = a;
int b = (int)a + 1;
printf("Value of a is %f\n", a);
printf("Value of b is %d\n",b);
return 0; }

Output-
Value of a is 1.200000
Value of b is 2

Q9. What is Constants, comments and header files ?


Ans)
1. Constants in C:
- Constants in C are fixed values that do not change during program execution. They are
declared using the `const` keyword or preprocessor directives like `#define` to represent
values that remain constant throughout the program.

2. Comments in C:
- Comments in C are non-executable portions of code used for documentation. They
provide explanations or notes within the source code to improve readability. Comments can
be single-line (//) or multi-line (/* */).
3. Header Files in C:
- Header files in C contain declarations for functions, macros, data types, and other
constructs. They are included at the beginning of a C program using `#include` preprocessor
directive to provide information about the external features used in the program.

Q10. Explain Looping statements.


Ans)
Loop is used to execute the block of code several times according to the condition given in the loop.
It means it executes the same code multiple times.

While Loop
• while is an entry controlled loop
• Statements inside the body of while are repeatedly executed till the condition is true
• while is keyword

do while Loop
• do while is an exit controlled loop.
• Statements inside the body of do while are repeatedly executed till the condition is true.
• Do and while are keywords.

for Loop
• for is an entry controlled loop
• Statements inside the body of for are repeatedly executed till the condition is true
• for is keyword
Syntax

Syntax
UNIT- 3: Pointers and Structures

Q1. Explain the concept of a 1-dimensional and 2-dimensional array.


Ans:
- 1-Dimensional Array: A 1-dimensional array is a collection of elements of the same data
type arranged in a sequential order. Each element is accessed by its index or position in the
array. In C, the declaration of a 1-dimensional array is done as follows:

Example in c:-
int arr[5]; // Declaration of an integer array with 5 elements

- 2-Dimensional Array: A 2-dimensional array is an array of 1-dimensional arrays. It can be


thought of as a table of elements, where each element is identified by two indices (row and
column). In C, the declaration of a 2-dimensional array is as follows:

Example in c:-
int matrix[3][4]; // Declaration of a 3x4 integer matrix

Q2. What is Array? Explain with example.


Ans:
- Array: An array is a collection of elements of the same data type, stored in contiguous
memory locations, and each element is identified by an index or a key. Arrays provide a
convenient way to store and manipulate data.

Example in c:-
int numbers[5]; // Declaration of an integer array with 5 elements

Here, `numbers` is an array that can store 5 integers. The elements can be accessed using
indices, such as `numbers[0]`, `numbers[1]`, etc.

Q3. How to declare and initialize arrays and strings.


Ans:
- Declaration and Initialization of Arrays:
int numbers[5]; // Declaration of an integer array with 5 elements

// Initialization
numbers[0] = 1;
numbers[1] = 2;
// ...

// Alternatively, declaration and initialization together


int numbers2[3] = {10, 20, 30};
- Declaration and Initialization of Strings:
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // String termination with null character
// Alternatively, using string literal
char greeting2[] = "Hello"; // The size is automatically determined

Q4. Explain String functions.


Ans:
- Strings in C are represented as arrays of characters. Some commonly used string functions
from the <string.h> library include:
- strlen(str): Returns the length of the string `str`.
- strcpy(dest, src): Copies the string `src` to `dest`.
- strcat(dest, src): Concatenates the string `src` to `dest`.
- strcmp(str1, str2): Compares two strings lexicographically.

Q5. Explain the difference between built-in functions and user-defined functions. Provide
examples of each.
Ans:
- Built-in Functions: These are functions that are provided by the programming language or
libraries. For example, in C, `printf()` and `scanf()` are built-in functions.

Example in c:-
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}

- User-defined Functions: These are functions created by the programmer. They provide a
way to modularize code and reuse it. Example:

Example in c:-
#include <stdio.h>

// User-defined function
int add(int a, int b) {
return a + b;
}

int main() {
int result = add(3, 4);
printf("Sum: %d\n", result);
return 0;
}
Q6. Describe the process of defining and declaring a function in programming. Provide an
example of a user-defined function with parameters and a return value.
Ans:
- Defining and Declaring a Function:
// Declaration
int add(int a, int b);

// Definition
int add(int a, int b) {
return a + b;
}

- Example of a User-defined Function:


#include <stdio.h>

// Function declaration
int add(int a, int b);

int main() {
int result = add(3, 4);
printf("Sum: %d\n", result);
return 0;
}

// Function definition
int add(int a, int b) {
return a + b;
}

Q7. What is the purpose of function prototypes in programming?

Ans:
- Function prototypes declare the function's name, return type, and parameter types without
providing the actual implementation. They serve as a forward declaration to inform the
compiler about the existence of a function before it's used in the code. This allows the
compiler to perform type checking and catch errors early.

Example in c:-
// Function prototype
int add(int a, int b);

int main() {
int result = add(3, 4);
// ...
return 0;
}

// Function definition
int add(int a, int b) {
return a + b;
}

Q8. Explain the concept of recursion in functions. How does a recursive function call itself?
Provide an example of a recursive function and explain its functionality.
Ans:
- Recursion in Functions:
Recursion is a programming concept where a function calls itself directly or indirectly to
solve a problem. In a recursive function, there should be a base case to stop the recursion and
prevent an infinite loop.

- Example in c:-
#include <stdio.h>

// Recursive function to calculate factorial


int factorial(int n) {
// Base case
if (n == 0 || n == 1) {
return 1;
}
// Recursive call
else {
return n * factorial(n - 1);
}
}

int main() {
int result = factorial(5);
printf("Factorial: %d\n", result);
return 0;
}

Q9. What are function parameters?


Ans:
- Function parameters are variables used in a function to receive values from the calling code.
They act as placeholders for the actual values (arguments) that will be passed to the function
when it is called. Parameters define the input that a function expects.

Example in c:-
// Function declaration with parameters
int add(int a, int b);

// Function definition
int add(int a, int b) {
return a + b;
}

// Function call with arguments


int result = add(3, 4);

Q10. Explain the difference between pass-by-value and pass-by-reference.


Ans:
- Pass-by-Value: In pass-by-value, the actual value of the argument is passed to the function.
Changes made to the parameters inside the function do not affect the original values outside
the function.

Example in c:-
void modifyValue(int x) {
x = 10;
}

int main() {
int num = 5;
modifyValue(num);
// 'num' remains 5
return 0;
}

- Pass-by-Reference: In pass-by-reference, the memory address (reference) of the argument is


passed to the function. Changes made to the parameters inside the function affect the original
values outside the function.

Example in c:-
void modifyReference(int *x) {
*x = 10;
}

int main() {
int num = 5;
modifyReference(&num);
// 'num' is now 10
return 0;
}

Q11. Discuss the types of functions in programming.


Ans:
- Types of Functions:
1. Built-in Functions: Provided by the programming language or libraries (e.g., `printf()` in
C).
2. User-defined Functions: Created by the programmer for specific tasks.
3. Recursive Functions: Functions that call themselves to solve a problem.
4. Library Functions: Functions from external libraries that provide additional
functionalities.
5. Callback Functions: Functions passed as arguments to other functions.
6. Inline Functions: Specified to be expanded in line, avoiding the overhead of function
calls.
Q12. Explain the concept of pre-processing, recursion, and macros.
Ans:
- Pre-processing: In C, the pre-processor performs operations before actual compilation.
Directives start with `#`, and common uses include file inclusion (`#include`), macro
definition (`#define`), and conditional compilation (`#ifdef`, `#ifndef`).

Example in c:-
#include <stdio.h>
#define PI 3.1415

int main() {
printf("Value of PI: %f\n", PI);
return 0;
}

- Recursion and Macros: Recursion is a programming concept where a function calls itself.
Macros in C are defined using `#define` and can be recursive.

Example in c:-
#include <stdio.h>
#define FACTORIAL(n) (n == 0 ? 1 : n * FACTORIAL(n - 1))

int main() {
printf("Factorial of 5: %d\n", FACTORIAL(5));
return 0;
}

Q13. How to solve problems using recursion, like Ackermann’s Function.


Ans:
- Solving Problems using Recursion (Ackermann’s Function): Ackermann’s Function is a
classic example of a recursive function that is not easily expressible using conventional loops.
Example in c:-
#include <stdio.h>
int ackermann(int m, int n) {
if (m == 0) {
return n + 1;
} else if (m > 0 && n == 0) {
return ackermann(m - 1, 1);
} else {
return ackermann(m - 1, ackermann(m, n - 1));
}
}

int main() {
int result = ackermann(2, 3);
printf("Ackermann(2, 3): %d\n", result);
return 0;
}
UNIT- 4: Pointers and Structures

Q1. Declare a pointer variable and initialize it to store the address of an integer variable.
Ans)
#include <stdio.h>

int main() {
int num = 42;
int *ptr = &num;
return 0;
}

Q2. Create a pointer to a pointer (double pointer) and assign it the address of the above
pointer variable.
Ans)
#include <stdio.h>

int main() {
int num = 42;
int *ptr = &num;
int **doublePtr = &ptr;
return 0;
}

Q3. Different between pointer to array and array to pointer.


Ans)
#include <stdio.h>

int main() {
int arr[5] = {1, 2, 3, 4, 5};

// Pointer to an array
int (*ptrToArray)[5] = &arr;

// Array to a pointer (decaying)


int *arrToPtr = arr;

return 0;
}
Q4. Write a function that takes an integer array as a parameter, calculates the sum of its
elements, and returns a pointer to the result.
Ans)
#include <stdio.h>
#include <stdlib.h>

int *sumArray(int arr[], int size) {


int sum = 0;
for (int i = 0; i < size; ++i) {
sum += arr[i];
}

int *result = malloc(sizeof(int));


*result = sum;

return result;
}

int main() {
int numbers[] = {1, 2, 3, 4, 5};
int *result = sumArray(numbers, 5);

printf("Sum: %d\n", *result);

// Don't forget to free the allocated memory


free(result);

return 0;
}

Q5. Explain Basics of structure


Ans)
#include <stdio.h>

struct Point {
int x;
int y;
};

int main() {
struct Point p1;
p1.x = 10;
p1.y = 20;
return 0;
}
Q6. Explain structure as functions and structures as pointers.
Ans)
#include <stdio.h>

struct Point {
int x;
int y;
};

// Structure as a parameter to a function


void printPoint(struct Point p) {
printf("Point: (%d, %d)\n", p.x, p.y);
}

int main() {
struct Point p1 = {10, 20};

// Passing structure to a function


printPoint(p1);

// Structure as a pointer
struct Point *ptr = &p1;

// Accessing members using a pointer


printf("Point: (%d, %d)\n", ptr->x, ptr->y);

return 0;
}

You might also like