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

SET 2073(REGULAR)

1.Explain the generation of programming languages.distingush betn high and low level programming
language.

》The generation of programming languages can be categorized into different levels or generations, each
building upon the previous one.

• First Generation (1940s-1950s): Also known as machine languages, these languages directly
corresponded to the hardware and consisted of binary instructions. Programming was tedious
and error-prone.
• Second Generation (1950s-1960s): Assembly languages were introduced, using symbolic names
for operations and memory locations. They still closely mapped to machine instructions but
provided some level of abstraction.
• Third Generation (1960s-1970s): High-level programming languages like FORTRAN, COBOL, and
ALGOL were developed. These languages offered more abstraction and were closer to human-
readable form, making programming more efficient and portable.
• Fourth Generation (1970s-1980s): Focused on domain-specific languages (DSLs) for specialized
tasks like database management and report generation. These languages aimed to provide high-
level abstractions tailored to specific applications.
• Fifth Generation (1980s-present): While no specific language dominates this generation, it
encompasses research into artificial intelligence and logic programming languages like Prolog. It
also includes languages with advanced features like concurrency, parallelism, and distributed
computing.
• Sixth Generation (speculative): Some experts suggest that languages designed to harness
quantum computing or advanced AI capabilities could constitute the sixth generation. However,
this concept is still evolving.

High-level and low-level programming languages are terms used to describe the level of abstraction and
proximity to machine code in a programming language. Here’s the distinction between the two:

HIGH LEVEL LANGUAGES

• Abstraction: High-level languages provide a higher level of abstraction from the hardware and
are closer to human language. They allow programmers to express algorithms and solutions in a
more intuitive and readable manner.
• Portability: Programs written in high-level languages are generally more portable across different
computer architectures and platforms, as the compiler or interpreter handles the translation to
machine code.
• Efficiency: While high-level languages are easier to use and understand, they may be less
efficient in terms of execution speed and memory usage compared to low-level languages.
• Examples: Python, Java, C++, Ruby, and JavaScript are examples of high-level programming
languages.

LOW LEVEL LANGUAGES


• Proximity to hardware: Low-level languages are closer to machine code and provide finer control
over hardware resources. They allow direct manipulation of memory and hardware components.
• Efficiency: Programs written in low-level languages tend to be more efficient in terms of
execution speed and memory usage, as they offer greater control over hardware resources.
• Portability: Low-level languages are less portable, as programs written in these languages may
need significant modification to run on different architectures.
• Examples: Assembly languages and machine languages are examples of low-level programming
languages.

2.What is an algorithm and how it differs from pseudo code? Develop algorithm to find the largest
number of n numbers.

》An algorithm is a step-by-step procedure or a set of well-defined instructions designed to solve a


specific problem or accomplish a particular task. It is a precise and systematic approach to problem-
solving that outlines the logical sequence of operations needed to achieve the desired outcome.

》Pseudo code, on the other hand, is a more informal and human-readable description of an algorithm.
It uses a mix of natural language and simple code-like constructs to outline the logic of the algorithm
without adhering to the strict syntax of a specific programming language. Pseudo code serves as an
intermediate step between the abstract algorithmic idea and the actual implementation in a
programming language.

Differences between algorithms and pseudo code:

• Formality: An algorithm is a formal set of instructions, while pseudocode is a less formal,


descriptive representation of those instructions.
• Precision: Algorithms are usually more precise and specific, whereas pseudocode allows for
greater flexibility and readability.
• Syntax: Algorithms can be written using the syntax of a specific programming language or as a
high-level description. Pseudo code, however, is not tied to any particular programming
language and uses a simplified syntax.
• . Intended Audience: Algorithms are often targeted at programmers and software engineers
who are familiar with programming concepts. Pseudocode is more accessible to a wider
audience, including non-programmers.

Usage: Algorithms serve as a blueprint for implementation and are used for designing and solving
problems. Pseudocode serves as an intermediate step during the plaplanningl
3what are identifiers? List the rules to define valid C identifiers.

》Identifiers are names given to various programming elements in a computer program, such as
variables, functions, classes, and other entities. They provide a way to uniquely identify and refer to
these elements within the program. Identifiers are an essential part of programming languages and play
a crucial role in writing readable and maintainable code.

Here are some key rules and characteristics of identifiers:

• Naming Rules:

- Identifiers can include letters (both uppercase and lowercase), digits (except as the first character),
and underscores (_)They must start with a letter or an underscore.Identifiers are case-sensitive, meaning
`myVariable` and `MyVariable` would be considered different identifiers. Examples

**Valid identifiers: `counter`, `_value`, `total_sum`, `calculateTotal`, `studentInfo1`

** Invalid identifiers: `123variable` (starts with a digit), `my-variable` (contains a hyphen), `if` (reserved
keyword)

• Reserved Keywords:

- Certain words are reserved by programming languages for specific purposes (e.g., control structures,
data types, etc.). These words cannot be used as identifiers.

• Meaningful Names:

- Choosing descriptive and meaningful names for identifiers enhances code readability and
maintainability. For example, `totalAmount` is more meaningful than `x`.

• Camel Case and Snake Case:

- Camel case: Capitalize each word except the first, e.g., `my_variable_name`.

- Snake case: Use underscores between words, e.g., `my_variable_name`.

• Length Limitations:

- Different programming languages have varying limits on identifier lengths. It’s a good practice to keep
identifiers

4.what are the difference betn global and local function, variables and data types,and
operators,*operators using in c programming languages? Explain with examples the differences
between global and local functions, variables and data types, and operators and pointers (operators
using pointers) in the C programming language.

Global and Local Functions:


• Global Function: A global function is a function that is defined outside of any other function. It
can be called from any part of the program, including other files (when properly declared).
• Local Function:A local function is a function that is defined within another function. It can only
be called within the scope of the function where it is defined.

Global and Local Variables:

• Global Variable: A global variable is a variable declared outside of any function. It has a global
scope and can be accessed from any part of the program.
• Local Variable:A local variable is a variable declared within a function. It has a local scope and
can only be accessed within the function where it is defined.

Data Types

• Data types: Data types in C specify the type of data that a variable can hold. Examples include
int, float, char, etc.
• Global Data Types: Data types are not affected by whether they are used in global or local scope.
The same data types can be used in both contexts.

Operators and *Operators Using Pointers:

• Operators: Operators in C perform operations on variables and values. Examples include +


(addition), - (subtraction), * (multiplication), / (division), etc.
• Operators Using Pointers: Pointers are variables that store memory addresses. Operators like *
(dereference) and & (address-of) are used with pointers. For example, `*ptr` dereferences a
pointer, and `&var` gets the address of a variable.

5a.Difference between pass by value and pass by reference .

• Pass by Value:

In pass by value, a copy of the actual parameter’s value is passed to the function. Any modifications
made to the parameter within the function do not affect the original value outside the function.

• Key Points:

- The function receives a copy of the value, and changes within the function do not affect the original
variable.

- Typically used for simple data types like integers, floats, characters.

- Inefficient for large data structures, as copying the entire value consumes memory and time.
**Example

Void modifyValue(int x) {

X = x * 2; // Changes to ‘x’ within the function do not affect the original variable.

Int main() {

Int num = 5;

modifyValue(num);

Return 0;

• Pass by Reference:

In pass by reference, a reference to the actual parameter is passed to the function. Any changes made to
the parameter within the function directly affect the original value outside the function.

• Key Points:

- The function receives a reference (or pointer) to the variable, allowing direct manipulation.

- Typically used for large data structures or when you want to modify the original value.

- More memory-efficient than pass by value for large data structures.

**Example (C++)**

Void modifyReference(int &x) {

X = x * 2;

Int main() {

Int num = 5;

modifyReference(num);

Return 0;

5b.Explain the significance of user defined function with examples.


》》User-defined functions play a crucial role in programming by allowing developers to modularize their
code, improve code reusability, and enhance readability. They help break down complex tasks into
smaller, manageable pieces of code. Let’s explore the significance of user-defined functions with some
examples:

• Modularization and Reusability:

User-defined functions enable code to be organized into separate modules. This makes it easier to
understand and maintain the codebase. Functions can be reused across different parts of the program or
even in different programs, promoting code reusability.

**2. Abstraction and Encapsulation:**

Functions abstract away the details of how a specific task is accomplished, allowing the caller to focus on
using the function rather than understanding its implementation. This promotes encapsulation and
reduces the complexity for the caller.

**3. Readability and Maintainability:**

Functions break down complex logic into smaller, manageable units. This improves code readability by
making each function focus on a specific task. It also makes code maintenance easier, as changes to a
specific function don’t necessarily impact other parts of the code.

Example:

User-defined function to check if a number is prime

Int isPrime(int num) {

If (num <= 1) {

Return 0;

For (int i = 2; i * i <= num; ++i) {

If (num % i == 0) {

Return 0;

Return 1;
}

Int number = 17;

If (isPrime(number)) {

Printf(“%d is prime.\n”, number);

} else {

Printf(“%d is not prime.\n”, number);

User-defined functions contribute significantly to code organization, reusability, and maintainability,


making them an essential concept in programming. They allow developers to write cleaner, more
efficient, and easier-to-understand code.

6write a program to read a string and check whether its alphabet or not.use user defined function to
accomplished the task.

#include <stdio.h>

Bool isAlphabetic(const char *str) {

While (*str) {

If (!((*str >= ‘a’ && *str <= ‘z’) || (*str >= ‘A’ && *str <= ‘Z’))) {

Return false;

Str++;

Return true;

Int main() {

Char input[100];
// Read a string from the user

Printf(“Enter a string: “);

Scanf(“%99s”, input);

// Check if the string is alphabetic

If (isAlphabetic(input)) {

Printf(“The string contains only alphabetic characters.\n”);

} else {

Printf(“The string contains non-alphabetic characters.\n”);

Return 0;

```

b.Explain how 2d array is passed to function

》》Passing a 2D array to a function in C involves understanding how C stores a 2D array in memory as a


contiguous block and how pointers are used to navigate through it.

• Passing a 2D Array to a Function:

When you pass a 2D array to a function, you are essentially passing a pointer to the first element of the
array (which is itself an array). The function receives this pointer and can use it to access elements of the
2D arrays.

Syntax

Void functionName(dataType arrayName[][cols], int rows, int cols) {

To display the largest and smallest elements of a 2D array:

#include <stdio.h>
Void findLargestAndSmallest(int arr[][3], int rows, int cols, int *largest, int *smallest) {

*largest = arr[0][0];

*smallest = arr[0][0];

For (int i = 0; i < rows; i++) {

For (int j = 0; j < cols; j++) {

If (arr[i][j] > *largest) {

*largest = arr[i][j];

If (arr[i][j] < *smallest) {

*smallest = arr[i][j];

Int main() {

Int rows, cols;

Printf(“Enter number of rows and columns: “);

Scanf(“%d %d”, &rows, &cols);

Int arr[rows][cols];

Printf(“Enter elements of the 2D array:\n”);

For (int i = 0; i < rows; i++) {

For (int j = 0; j < cols; j++) {

Scanf(“%d”, &arr[i][j]);

Int largest, smallest;

findLargestAndSmallest(arr, rows, cols, &largest, &smallest);


printf(“Largest element: %d\n”, largest);

printf(“Smallest element: %d\n”, smallest);

return 0;

8.What is nested structure? Write a program in c to read name age salary of 10 diff employees as the
three member of structures named as employee .sort this data in salary basis using user defined
function and display sorted data from main function

》》A nested structure in C is a structure that is a member of another structure. It allows you to create
more complex data structures by combining multiple structures together. Each structure within the
nested structure can have its own members and

#include <stdio.h>

#include <string.h>

#define NUM_EMPLOYEES 10

Struct Employee {

Char name[50];

Int age;

Float salary;

};

Void swap(struct Employee *a, struct Employee *b) {

Struct Employee temp = *a;

*a = *b;

*b = temp;

Void sortBySalary(struct Employee arr[], int n) {

For (int i = 0; i < n – 1; i++) {

For (int j = 0; j < n – i – 1; j++) {

If (arr[j].salary > arr[j + 1].salary) {

Swap(&arr[j], &arr[j + 1]);


}

Int main() {

Struct

For (int i = 0; i < NUM_EMPLOYEES; i++) {

Printf(“Enter details for employee %d:\n”, i + 1);

Printf(“Name: “);

Scanf(“%s”, employees[i].name);

Printf(“Age: “);

Scanf(“%d”, &employees[i].age);

Printf(“Salary: “);

Scanf(“%f”, &employees[i].salary);

sortBySalary(employees, NUM_EMPLOYEES);

Printf(“\nSorted employee data by salary:\n”);

For (int i = 0; i < NUM_EMPLOYEES; i++) {

Printf(“Employee %d:\n”, i + 1);

Printf(“Name: %s\n”, employees[i].name);

Printf(“Age: %d\n”, employees[i].age);

Printf(“Salary: %.2f\n\n”, employees[i].salary);

Return 0;
8.write a program in c language to compute the cosine series.

》》#include <stdio.h>

#include <math.h>

Double computeCosine(double x, int terms) {

Double result = 1.0;

Int sign = -1;

For (int i = 2; i <= 2 * terms; i += 2) {

Result += (sign * pow(x, i)) / factorial(i);

Sign *= -1;

Return result;

Int factorial(int n) {

If (n == 0 || n == 1) {

Return 1;

} else {

Return n * factorial(n – 1);

Int main() {

Double angle;

Int numTerms;

Printf(“Enter the angle in radians: “);

Scanf(“%lf”, &angle);

Printf(“Enter the number of terms in the series: “);

Scanf(“%d”, &numTerms);

Double cosineValue = computeCosine(angle, numTerms);


Printf(“Cosine of %.2f radians using %d terms: %.6f\n”, angle, numTerms, cosineValue);

Return 0;

9. Wap to open a file name INVENTORY and stores and stores in it for maximum 1000 data of
item_name,number , price and quantity. Extend the program to read this data from above given file
name and display the inventory table with the value of each item

#include <stdio.h>

struct Item {

char item_name[50];

int number;

float price;

int quantity;

};

void writeToFile(struct Item items[], int count) {

FILE *file = fopen("INVENTORY", "wb");

if (file == NULL) {

printf("Error opening file for writing.\n");

exit(1);

fwrite(items, sizeof(struct Item), count, file);

fclose(file);

void readFromFile(struct Item items[], int count) {

FILE *file = fopen("INVENTORY", "rb");

if (file == NULL) {

printf("Error opening file for reading.\n");

exit(1);
}

fread(items, sizeof(struct Item), count, file);

fclose(file);

int main() {

struct Item inventory[1000];

int numItems;

printf("Enter the number of items (up to 1000): ");

scanf("%d", &numItems);

if (numItems > 1000) {

printf("Number of items exceeds limit.\n");

return 1;

for (int i = 0; i < numItems; i++) {

printf("Enter details for item %d:\n", i + 1);

printf("Item Name: ");

scanf("%s", inventory[i].item_name);

printf("Number: ");

scanf("%d", &inventory[i].number);

printf("Price: ");

scanf("%f", &inventory[i].price);

printf("Quantity: ");

scanf("%d", &inventory[i].quantity);

writeToFile(inventory, numItems);

printf("Data written to file.\n");

readFromFile(inventory, numItems);

printf("\nInventory Table:\n");

printf("----------------------------------------------------\n");
printf("%-15s %-10s %-10s %-10s %-10s\n", "Item Name", "Number", "Price", "Quantity", "Value");

printf("----------------------------------------------------\n");

float totalValue = 0;

for (int i = 0; i < numItems; i++) {

float value = inventory[i].price * inventory[i].quantity;

totalValue += value;

printf("%-15s %-10d %-10.2f %-10d %-10.2f\n",

inventory[i].item_name, inventory[i].number, inventory[i].price,

inventory[i].quantity, value);

printf("----------------------------------------------------\n");

printf("Total Value: %.2f\n", totalValue);

return 0;

10a.Compared unconditional goto and computed goto in for tan with syntax.

》In Fortran, both “unconditional goto” and “computed goto” are control flow constructs used for
transferring control from one part of the program to another. However, they have distinct syntax and
purposes. Let’s explore both of them:

• Unconditional Goto:

The “unconditional goto” is a basic form of a jump statement that transfers control to a specified label
unconditionally. It is widely considered a bad practice in modern programming because it can lead to
spaghetti code and make the program difficult to understand and maintain.

Syntax:

```fortran

GOTO label

```

Here, `label` is the label to which control will be transferred.

Example:

```fortran
PROGRAM UnconditionalGotoExample

INTEGER :: num

READ(*, *) num

IF (num > 0) THEN

GOTO 10

END IF

GOTO 20

PRINT *, “Number is positive”

GOTO 30

PRINT *, “Number is non-positive”

PRINT *, “Program completed”

END PROGRAM

**Computed Goto:**

The “computed goto” is more structured and controlled compared to the “unconditional goto.” It allows
you to transfer control based on the value of an expression to different labels. This is typically achieved
using a SELECT CASE construct.

Syntax:

```fortran

GOTO (label1, label2, ..., labelN), expression

```

Here, `label1`, `label2`, ..., `labelN` are labels to which control will be transferred based on the value of
`expression`.

Example:

```fortran

PROGRAM ComputedGotoExample

INTEGER :: num

READ(*, *) num

SELECT CASE (num)

CASE (1)
GOTO 10

CASE (2)

GOTO 20

CASE DEFAULT

GOTO 30

END SELECT

PRINT *, “Number is 1”

GOTO 40

PRINT *, “Number is 2”

GOTO 40

PRINT *, “Number is neither 1 nor 2”

PRINT*, “Program completed”

END PROGRAM

10b. Write a program in fortan to read an array containing n elements ,sort this data in ascending order
and display the results.

IMPLICIT NONE

INTEGER, PARAMETER :: maxElements = 100

INTEGER :: n, i, j, temp

INTEGER :: array(maxElements)

WRITE(*, *) “Enter the number of elements (1 to”, maxElements, “): “

READ(*, *) n

IF (n <= 0 .OR. n > maxElements) THEN

WRITE(*, *) “Invalid number of elements.”

STOP

END IF

DO i = 1, n
WRITE(*, *) “Enter element”, i, “: “

READ(*, *) array(i)

END DO

DO i = 1, n – 1

DO j = 1, n – i

IF (array(j) > array(j + 1)) THEN

! Swap elements

Temp = array(j)

Array(j) = array(j + 1)

Array(j + 1) = temp

END IF

END DO

END DO

! Display the sorted array

WRITE(*, *) “Sorted array in ascending order:”

DO i = 1, n

WRITE(*, *) array(i)

END DO

END PROGRAM

You might also like