FCS Assignment

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 38

ASSIGNMENT

Q1] Define algorithm. Explain characteristics of algorithm.

Ans. Algorithm can be defined as: “A sequence of activities to be processed for


getting desired output from a given input.”

Characteristics of Algorithm:

1) An algorithm must contain blocks that will help to solve problems more
efficiently & logically

2) Each step of an algorithm must be precisely defined..

3) It should accept a set of inputs and produce a defined output.

4) It should be independent from a computer programming language.

5) An algorithm must contain blocks that will help to solve problems more
efficiently & logically.

6) It should develop a platform for writing programs.

Q2] Explain all types of operators in detail with example.

Ans. 1) Arithmetic Operators in C:


The purpose of this operator is to perform mathematical operations like addition,
subtraction, division, multiplication etc.

Operator What it does Example


+ Addition between 2 operands. A + B = 20
− Subtraction between 2 operands. A−B=0
* Multiplication between 2 operands. A * B = 100
/ Division between 2 operands. B/A=1
% Modulus Operator and remainder of after an integer division. B%A=0
++ Increases the integer value by one. A++ = 11
-- Decreases the integer value by one. B-- = 9

2) Increment Operator in C:
Mainly used for incrementing the value of an integer. It is represented by the ‘++’
operator. X++ will increase the value of the variable x instantly. But if it is placed
after the variable then it gets increased before the execution of the next statement.

Example of C Increment Operator:

#include <stdio.h>
#include<conio.h>
int main()
{
int a = 10;
clrscr();
a++;
printf(“Value of a: %d”, a);
getch();
return 0;
}

3) Decrement Operator in C:
Mainly used for decrementing the value of an integer. It is represented by the ‘--’
operator. X-- will decrease the value of the variable x instantly. But if it is placed
after the variable then it gets decreased before the execution of the next statement.

Example of C Decrement Operator:

#include <stdio.h>
#include<conio.h>
int main()
{
int a = 10;
clrscr();
a--;
printf(“Value of a: %d”, a);
getch();
return 0;
}

4) Assignment Operators in C:
The purpose of this operator is to assign value to a variable. The most used
assignment operator is “=”. 
Operator Example
= a = b or b = a
+= a += b or a = a + b
-= a -= b or a = a - b
*= a *= b or a = a*b
/= a /= b or a = a/b
%= a %= b or a = a % b

5) Relational Operators in C:
Mainly used for checking relationships between operands. With the help of this
operator, you can check whether one operand is equal to or greater than the other
operand or not.
It returns 1 when the relation is true. And when it is false, it returns 0.

Operator What it does Example


== Equal to 5 == 5 will be 1
> Greater than 5 > 6 will be 0
< Less than 6 < 7 will be 1
>= Greater than equal to 2 >= 1 will be 1
<= Less than equal to 1 <= 2 will be 1
!= Not equal to 5 != 6 will be 1

6) Logical Operators in C:
In the C programming language, Logical operators are mostly used for decision
making. A logical operator returns either 0 or 1 whether the condition is true or
false.
Operator What it does
&& (Logical AND) True only if all conditions satisfy.
|| (Logical OR) True only if either one condition satisfies.
! (Logical Not) True only if the operand is 0.

7) Conditional Operator in C:
Also known as Ternary operator. The main purpose of conditional operators is in
decision making statements. It is similar to an if-else statement.

Syntax of a conditional operator:-

Expression1? statement1: statement2;


 Expression1 is a boolean expression, it can be either true or false.
 If the Expression1 returns true then statement1 will get executed.
 If the Expression1 returns false then statement2 will get executed.

8)  Bitwise Operator in C:
C also provides special operators for bit operation between two variables.
Operator Also known as

<< Binary Left Shift Operator

>> Binary Right Shift Operator

~ Binary Ones Complement Operator

& Binary AND Operator

^ Binary XOR Operator


| Binary OR Operator

9) Special Operators in C:
Apart from these operators, C supports special operators:-

1. sizeof():- If you want to check the size of data types available in C then you
can do it by using sizeof() operator.

2. Reference Operator (&):– Used for returning the address of a memory


location.

3. Pointer Operator (*):– It is a pointer to a variable.

Q3] Explain control structures in detail with example.

Ans. Control structures are used to alter the flow of execution of the
program.There are three types of control structures available in C:

1) Sequence structure (straight line paths)


2) Selection structure (one or many branches)
3)Loop structure (repetition of a set of activities)

All the 3 control structures and its flow of execution is represented in the flow
charts given below.
Control statements in C to implement control structures:

The control statements are:-

 Switch
 If
 If Else
 While
 Do While
 For
As shown in the flow charts:-

 Selection structures are implemented using If , If Else and Switch statements.


 Looping structures are implemented using While, Do
While and For statements.
 Selection structures:
 
Selection structures are used to perform ‘decision making’ and then branch the
program flow based on the outcome of decision making. Selection structures are
implemented in C with If, If Else and Switch statements.

If and If Else statements are 2 way branching statements where as Switch is a multi
branching statement. 

The simple If statement:

The syntax format of a simple if statement is as shown below:

if(expression) // This expression is evaluated. If expression is TRUE, statements


inside the braces will be executed

Statement 1;

Statement 2:

Statement 1; // Program control is transferred directly to this line, if the expression


is FALSE

Statement 2;

The expression given inside the brackets after if is evaluated first. If the expression
is true, then statements inside the curly braces that follow if(expression) will be
executed. If the expression is false, the statements inside curly braces will not be
executed and program control goes directly to statements after curly braces.

The If Else statement:

Syntax format for If Else statement is shown below:

If(expression) // Expression 1 is evaluated. If TRUE, statements inside the curly


braces are executed.

{ //If FALSE program control is transferred to immediate else if statement.


Statement 1;

Statement 2;

Else if(expression 2) // If expression 1 is FALSE, expression 2 is evaluated.

Statement 1;

Statement 2;

Else if(expression 3) // If expression 2 is FALSE, expression 3 is evaluated.

Statement 1;

Statement 2;

Else // If all expressions(1,2,3) are FALSE, the statements that follow this
else(inside curly braces) is executed.

Statement 1;

Statement 2;

Other statements;

The execution begins by evaluation expression 1. If it is TRUE, then statements


inside the immediate curly braces is evaluated. If it is FALSE, program control is
transferred directly to immediate else if statement. Here expression 2 is evaluated
for TRUE or FALSE. The process continues. If all expressions inside the different
if and else if statements are FALSE, then the last else statement (without any
expression) is executed along with the statements 1 and 2 inside the curly braces of
last else statement.

Switch statement:

Switch is a multi branching control statement. Syntax for switch statement is


shown below.

Switch(expression) // Expression is evaluated. The outcome of the expression


should be an integer or a character constant.

Case value 1: // case is the keyword used to match the integer/character constant
from expression.

//value1, value2…are different possible values that can come in expression

Statement 1;

Statement 2;

Break; // break is a keyword used to break the program control from switch block.

Case value2;

Statement 1;

Statement 2;

Break;

Default; // default is a keyword used to execute a set of statements inside switch, if


no case values match the expression value.

Statement 1;

Statement 2;

Break;
}

Execution of switch statement begins by evaluating the expression inside the


switch keyword brackets. The expression should be an integer (1, 2, 100, 57 etc )
or a character constant like ‘a’, ‘b’ etc. This expression’s value is then matched
with each case values. There can be any number of case values inside a switch
statements block. If first case value is not matched with the expression value,
program control moves to next case value and so on. When a case value matches
with expression value, the statements that belong to a particular case value
are executed.

 Loop structures:

A loop structure is used to execute a certain set of actions for a predefined number
of times or until a particular condition is satisfied. There are 3 control statements
available in C to implement loop structures. While, Do while and For statements. 
The while statement:

Syntax for while loop is shown below:

while(condition)// This condition is tested for TRUE or FALSE. Statements inside


curly braces are executed as long as condition is TRUE
{
statement 1;
statement 2;
statement 3;
}

The condition is checked for TRUE first. If it is TRUE then all statements inside
curly braces are executed . Then program control comes back to check the
condition has changed or to check if it is still TRUE. The statements inside braces
are executed repeatedly, as long as  the condition is TRUE. When the condition
turns FALSE, program control exits from while loop.

Note:- while is an entry controlled loop. Statement inside braces are allowed to


execute only if condition inside while is TRUE.

The do while statement:

Syntax for do while loop is shown below:

do
{
statement 1;
statement 2;
statement 3;
}
while(condition);

Unlike while, do while is an exit controlled loop. Here the set of statements inside
braces are executed first. The condition inside while is checked only after finishing
the first time execution of statements inside braces. If the condition is TRUE, then
statements are executed again. This process continues as long as condition is
TRUE. Program control exits the loop once the condition turns FALSE.
The For statement:

Syntax of for statement is shown below:

For(initialization statements; test conditions; iteration statements)

{
Statement 1;

Statement 2;

Statement 3;
}

 The for statement is an entry controlled loop.

 The difference between while and for is in the number of repetitions.

 The for loop is used when an action is to be executed for a predefined


number of times.

 The while loop is used when the number of repetitions is not predefined.

Q4] Define function. Explain types of functions with example.

Ans. A function is a self-contained block of statements that perform a coherent


task of some kind. Every C program can be thought of as a collection of these
functions.
Functions accept data, process it, and return a result. Functions are written
primarily to support the concept of reusability.
Once a function is written, it can be called easily, without having to write the
same code again and again. Different functional languages use different syntax to
write a function.

Types of function:

There are two types of function in C programming:

1. Standard library functions.


2. User-defined functions.

Standard library functions:

The standard library functions are built-in functions in C programming.These


functions are defined in header files. For example,

 The printf() is a standard library function to send formatted output to the screen


(display output on the screen). This function is defined in the stdio.h header file.
Hence, to use the printf() function, we need to include the stdio.h header file
using #include <stdio.h>.
 The sqrt() function calculates the square root of a number. The function is defined
in the math.h header file.  

User-defined function:

You can also create functions as per your need. Such functions created by the user
are known as user-defined functions.

The execution of a C program begins from the main() function.


When the compiler encounters functionName();, control of the program jumps to
void functionName() and, the compiler starts executing the codes
inside functionName().
The control of the program jumps back to the main() function once code inside the
function definition is executed.

Advantages of user-defined function:

1. The program will be easier to understand, maintain and debug.

2. Reusable codes that can be used in other programs.

3. A large program can be divided into smaller modules. Hence, a large project can
be divided among many programmers.

Q5] Write a short note on:

i) Pointers

Ans. Pointers can be used to make a function return more than one value
simultaneously.

Pointer Notation:

Consider the declaration,

int i = 30 ;

This declaration tells the C compiler to:

(a) Reserve space in memory to hold the integer value.

(b) Associate the name i with this memory location.

(c) Store the value 3 at this location.

Applications of Pointers:

1. Pointers have a number of useful applications.


2. Pointer Enables us to access a variable that is defined outside the function.
3. Pointers can be used to pass information back and forth between a function
and its reference point.
4. Pointer reduces the length and complexity of a program.
5. Pointers sometimes also increases the execution speed.
6. Pointers are used for Allocating memory dynamically.

ii) Types of array

Ans. Arrays can of following types:

1. One dimensional (1-D) arrays or Linear arrays.

2. Multi dimensional arrays:

(a) Two dimensional (2-D) arrays or Matrix arrays.

(b) Three dimensional arrays.

1. One dimensional (1-D) arrays or Linear arrays:

In it each element is represented by a single subscript. The elements are stored in


consecutive memory locations. E.g. B[1], B[2],….., B[N].

2. Multi dimensional arrays:

(a) Two dimensional (2-D) arrays or Matrix arrays:

In it each element is represented by two subscripts. Thus a two dimensional m x n


array A has m rows and n columns and contains m*n elements. It is also called
matrix array because in it the elements form a matrix. E.g. B [2] [3] has 2 rows and
3 columns and 2*3 = 6 number of elements.

(b) Three dimensional arrays:

In it each element is represented by three subscripts. Thus a three dimensional m x


n x l array A contains m*n*l elements. E.g. A [2] [3] [2] has 2*3*2 = 12 elements.

iii) Pointer Array


Ans. In computer programming, an array of pointers is an indexed set of
variables, where the variables are pointers (referencing a location in memory).

Pointers are an important tool in computer science for creating, using, and
destroying all types of data structures. An array of pointers is useful for the same
reason that all arrays are useful: it allows you to numerically index a large set of
variables.

Below is an array of pointers in C that points each pointer in one array to an integer
in another array. The value of each integer is printed by dereferencing the pointers.
In other words, this code prints the value in memory of where the pointers point.

#include <stdio.h>

const int B= 8;

int main ()

/* first, declare and set an array of five integers: */

int A[] = {5, 10, 20, 40, 80,100,120,150};

/* next, declare an array of five pointers-to-integers: */

int i, *C[B];

for ( i = 0; i < B; i++)

/* for indices 1 through 5, set a pointer to point to a corresponding integer: */

C[i] = &B[i];

for ( i = 0; i < A; i++)

{
/* print the values of the integers pointed to by the pointer: */

printf("B[%d] = %d\n", i, *C[i] );

return 0;

Q6] Define structure. Explain concept of array of structure with suitable


example.

Ans. A structure is a collection of variables of same or different datatypes. It is


useful in storing or using information’s or databases.
Example: An employee’s record must show its salary, position, experience, etc. It
all can be stored in one single variable using structures.
struct employee

char A[20];

int id;

float salary , experience;

};

Structure written inside another structure is called as nesting of two structures.


Nested Structures are allowed in C Programming Language. We can write one
Structure inside another structure as member of another structure.

Array of structures in C language:


An array of structure in C programming is a collection of different datatype
variables, grouped together under a single name.
General form of structure declaration:
The structural declaration is as follows:-
struct tagname
{
datatype 1;
datatype 2;
datatype n;
};
Here, struct is the keyword, tagname specifies name of structure.
member1, member2 specifies the data items that make up structure.
The most common use of structure in C programming is an array of structures. To
declare an array of structure, first the structure must be defined and then an array
variable of that type should be defined.
For Example − struct book B[10]; //10 elements in an array of structures of type
‘book’.

Example:
The following program shows the usage of array of structures:
#include <stdio.h>
#include <string.h>
#include<conio.h>
struct student
{
int ID;
char NAME[30];
float percentage;
};
int main()
{
int i;
struct student record[2];
// 1st student's record
record[0].ID=1;
strcpy(record[0].NAME, "Bhanu");
record[0].percentage = 86.5;
// 2nd student's record
record[1].ID=2;
strcpy(record[1].NAME, "Priya");
record[1].percentage = 90.5;
// 3rd student's record
record[2].ID=3;
strcpy(record[2].NAME, "Hari");
record[2].percentage = 81.5;
for(i=0; i<3; i++)
{
printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].ID);
printf(" Name is: %s \n", record[i].NAME);
printf(" Percentage is: %f\n\n",record[i].percentage);
}
getch();
return 0;
}
Q7] Explain File Descriptor and Storage Allocator in detail.

Ans. . File Descriptor:

A file descriptor is a number that uniquely identifies an open file in a computer's


operating system. It describes a data resource, and how that resource may be
accessed .When a program asks to open a file — or another data resource, like a
network socket — the kernel:

1. Grants access.

2. Creates an entry in the global file table.

3. Provides the software with the location of that entry.

The descriptor is identified by a unique non-negative integer, such as 0, 34, or 767.


At least one file descriptor exists for every open file on the system.

File descriptors were first used in Unix, and are used by modern operating systems
including Linux, macOS, and BSD. In Microsoft Windows, file descriptors are
known as file handles.

Storage Allocator:

The different ways to allocate memory are:

1. Static storage allocation


2. Stack storage allocation
3. Heap storage allocation

Static storage allocation:


 In static allocation, names are bound to storage locations.
 If memory is created at compile time then the memory will be created in
static area and only once.
 Static allocation supports the dynamic data structure that means memory is
created only at compile time and deallocated after program completion.
 The drawback with static storage allocation is that the size and position of
data objects should be known at compile time.
 Another drawback is restriction of the recursion procedure.
Stack Storage Allocation:
 In static storage allocation, storage is organized as a stack.
 An activation record is pushed into the stack when activation begins and it is
popped when the activation end.
 Activation record contains the locals so that they are bound to fresh storage
in each activation record. The value of locals is deleted when the activation
ends.
 It works on the basis of last-in-first-out (LIFO) and this allocation supports
the recursion process.

Heap Storage Allocation:

 Heap allocation is the most flexible allocation scheme.


 Allocation and deallocation of memory can be done at any time and at any
place depending upon the user's requirement.
 Heap allocation is used to allocate memory to the variables dynamically and
when the variables are no more used then claim it back.
 Heap storage allocation supports the recursion process.

The dynamic allocation is as follows:


LABORATORY EXERCISES

Q1] Algorithm and flowcharts for small programs.

Ans. a) To compute the GCD of two numbers.

Algorithm:

1. Read two input values using input function


2. Convert them into integers
3. Define a function to compute GCD

a. Find smallest among two inputs

b. Set the smallest

c. Divide both inputs by the numbers from 1 to smallest+1.

If the remainders of both divisions are zero. Assign that number to


gcd.

d. Return the gcd.

4. Call the function with two inputs


5. Display the result

FLOW CHART:
b) To find the area of circle.

ALGORITHM:

Step 1: Start
Step 2: Input radius
Step 3: let pi = 3.14
Step 4: area = pi * radius * radius
Step 6: print area
Step 7: stop

FLOWCHART:
c) To find the circumference of circle.

ALGORITHM:

Step 1: Start
Step 2: input radius
Step 3: let pi = 3.14
Step 5: circumference = 2 * radius * pi
Step 6: print circumference
Step 7: Stop

FLOWCHART:
Q2] Structured code writing with:

1) Small but tricky codes.

a) Designated initializers to set values of Structure members:

#include <stdio.h>
#include<conio.h>
struct numbers
{
   int A,B;
};
int main ()
{
struct numbers s1 ,s2;
s1.A=35;
s1.B=40;
s2.B=55;
clrscr();
printf ("\t1: %d, 2: %d\n", s1.A, s1.B);
printf ("\t1: %d", s2.B);
getch();
return 0;
}

OUTPUT:
b) Store Information in structure and display it:

#include <stdio.h>
#include <conio.h>
struct student
{
   char FirstName[50];
   float Marks;
};
int main()
{
   int i;
   struct student s[3];
   printf("Enter information of students:\n");
   for (i = 0; i < 3; i++)
   {

      printf("\nFor roll number%d, \n", i + 1);


      printf("Enter first name: ");
      scanf("%s", &s[i].FirstName);
      printf("Enter marks: ");
      scanf("%f", &s[i].Marks);
   }
   printf("Displaying Information:\n\n");
   for (i = 0; i < 3; i++)
   {
      printf("\nRoll number: %d\n", i + 1);
      printf("First name: ");
      puts(s[i].FirstName);
      printf("Marks: %.1f", s[i].Marks);
      printf("\n");
   }
   getch();
   return 0;
}

OUTPUT:

2) Proper parameter passing.

In C Programming Language, there are two methods to pass parameters from


calling function to called function and they are as follows...

 Call by Reference
 Call by Value

CALL BY VALUE:

#include <stdio.h>
#include <conio.h>

int swap(int a, int b)


{
   int C;

   C = a;
   a = b;
   b = C;
   printf("\nAfter swap: A= %d\nB = %d", a, b);
   return 0;
}
int main()
{
   int A, B; // function declaration
   printf("Enter values for a and b\n");
   scanf("%d%d", &A, &B);

   printf("\n\nBefore swapping: a = %d and b = %d\n", A, B);

   swap(A, B); // calling function

   return 0;
}
OUTPUT:

CALL BY REFRENCE:

#include <stdio.h>

int change(int *a)


{
   *a = 555;
   return 0;
}

int main()
{
   int a = 55;
   printf("the value of a is %d\n", a);
   change(&a);
   printf("now the value of a is %d\n", a);
   return 0;
}
OUTPUT:

3) Command line arguments.

#include <stdio.h>

int main(int argc, char const *argv[])


{
   printf("The value of argc is %d\n", argc);
   for (int i = 0; i < argc; i++)
   {
      printf("This argument at index number %d
has a value of %s \n", i, argv[i]);
   }
   return 0;
}

OUTPUT:
4) Variable Parameter.

#include <stdarg.h>
#include <stdio.h>
int min(int arg_count, ...)
{
    int i;
int min, a;
 va_list ap;
  va_start(ap, arg_count);
 min = va_arg(ap, int);
for(i = 2; i <= arg_count; i++)
        if((a = va_arg(ap, int)) < min)
            min = a;
    va_end(ap);
   return min;
}
  int main()
{
    int count = 5;
    printf("Minimum value is %d", min(count, 12,
67, 6, 7, 100));
    return 0;
}

OUTPUT:

5) Pointer to Functions.
#include <stdio.h>
#include <conio.h>
void fun(int a)
{
    printf("\n\tValue of a is %d", a);
}
int main()
{
    void (*fun_ptr)(int) = &fun;
    (*fun_ptr)(20);
 return 0;
}

OUTPUT:

6) User defined header.


void add(int a, int b)
{
    printf("Added value is= %d\n",a+b);
}
void multiply(int a, int b)
{
    printf("Multiplied value is= %d\n",a*b);
}

#include <stdio.h>
#include "myhead.h"
int main()
{
    add(4, 6);
   
 
    /*This calls add function written in myhead.h  
      and therefore no compilation error.*/
    multiply(5, 5);
 
    // Same for the multiply function in myhead.h
    printf("BYE!See you Soon");
    return 0;
}

OUTPUT:

7) Make file utility.

Misc.h
#ifndef MISC_H
    #define MISC_H
   
    /*function declaration.*/
    void myFunc(void);
   
#endif

Main.c
#include <stdio.h>
#include "misc.h"

/*function definition*/
void myFunc(void)
{
    printf("Body of myFunc function.\n");
}

int main()
{
    printf("Hello, World.\n");
    myFunc();
    fflush(stdout);

    return 0;
}

OUTPUT:
8) Multi file program and user defined libraries.

#include <stdio.h>
#include <math.h>
int main()
{
    float num, root;
    printf("Enter a number: ");
    scanf("%f", &num);

    // Computes the square root of num and stores in root.


    root = sqrt(num);
    printf("Square root of %.2f = %.2f", num, root);
    return 0;
}

OUTPUT:

9) Interesting substring matching/ searching programs.

#include <stdio.h>
#include <string.h>

int main()
{
    char str[] = "finding first and last occurrence of a character is amazing";
    char alpha[] = "abcdefghi";

    printf("String to search: %s\n", str);


    printf("Length of string: %d\n", strlen(str));
    printf("Char: first last\n");

    for (int i = 0; i < strlen(alpha); i++)


    {
        char *position_ptr = strchr(str, alpha[i]);
        char *r_position_ptr = strrchr(str, alpha[i]);
        int position = (position_ptr == NULL ? -1 : position_ptr - str);
        int r_position = (r_position_ptr == NULL ? -1 : r_position_ptr - str);

        printf("%4c: %4d %4d\n", alpha[i], position, r_position);


    }

    return 0;
}

OUTPUT:

MINI PROJECT

You might also like