Programming Basics-Additional Questions & Answers

Embed Size (px)

Citation preview

  • 8/12/2019 Programming Basics-Additional Questions & Answers

    1/8

    Nicholas, MIS 07-015

    rogramming Fundamentals

    What is memory allocation? Classify it in brief.

    Memory allocation is the act of managing computer memory. The C language supports 2 kinds

    of memory allocation. They are:

    Static Allocation:Static memory allocation refers to the process of allocating memoryat compile-time before the associated program is executed. Static memory allocation is

    used when we know the memory requirement in advance. Static allocation happens

    when we declare a static or global variable. Each static of global variable defines one

    block of space, of a fixed size. The space is allocated once, when the program is started

    and is never freed.

    Dynamic allocation: Dynamic memory allocation refers to the process of allocatingmemory at run. Sometimes we have to work with data which are dynamic in nature,

    when the number of data is not fixed. So our initial judgment of the memory size, if itswrong, may cause failure of the program or wastage of memory space. This allocation

    technique allows a program to obtain more memory space, while running or to release

    space when no space is required.

    Dynamic memory allocation uses 4 functions to declare memory for the variables. They are:

    Functions Task Syntax

    malloc ( ) Stands for Memory Allocation;reserves a block of memory of fixed

    size and returns a void pointer if the

    space is insufficient

    ptr=(cast_type*)malloc (byte_size)

    ptr= (int*)malloc (100* size of (int))

    calloc ( ) Stands for Contiguous Allocation;allocates multiple blocks of memory

    each of same size and sets all bytes to

    zero

    ptr=(cast_type*)calloc(n,element_size)

    ptr=(cast_type*)calloc(25,size of(float))

    free ( ) de-allocates the previously allocated

    memory

    free (ptr)

    realloc ( ) modifies the size of previously

    allocated memory

    realloc (ptr, new_size)

    How a program/instruction is executed? Describe in brief.

    Instruction execution cycle refers to the five sequential steps, which are followed to execute

    program/instruction. The steps are:

    1. Fetch Instruction:At the 1ststep, the control fetches the instruction, copy it from thememory into the CPU and increment the program counter if necessary.

    2. Decode Instruction:At the 2ndstep, the control determines the type of instruction, bypassing the necessary control signals to the ALU, indicating the operations to beperformed.

  • 8/12/2019 Programming Basics-Additional Questions & Answers

    2/8

    Nicholas, MIS 07-015

    rogramming Fundamentals

    3. Fetch Operands: At the 3rd step, the operands have to be fetched from the memory.Operands are the objects on which the operation is made. For example: in the

    expression- 5+x; x and 5 are operands and the + (addition) is the operations.

    4.

    Execute Instruction:At the 4th

    step, the instructions are executed by the CPU.

    5. Store Result: This is the last step of the of the instruction cycle. After successfullyexecuting the instructions, the results are stored in the memory to display or retrieve

    later. The execution cycle continues until all the instructions are executed.

    What is Global variable & local Variable? What is scope of the variable?

    Global variable:A global variable is a variable declared in the main body of the source code,

    outside all functions. Global variable is declared at the start of the program, their

    global scope means they can be used in any procedure or subroutine in the program.

    Local Variable:a local variable is a variable declared within the body of a function or a block.

    Their local scope means they can only be used within the subroutine or program block they

    were declared in.

    Scope of the variable:Scope of the variable refers to the area of variables where it can work,

    according to their nature of declaration -global or local.

    Global variables can be referred from anywhere in the code, even inside functions, whenever it

    is after its declaration. The scope of local variables is limited to the block enclosed in braces

    ({}) where they are declared. For example, if they are declared at the beginning of the body of a

    function (like in function main) their scope is between its declaration point and the end of that

    function.

    Example of Global and Local variables and their scope:

    #inclue

    int add ( )

    {

    return A+B;

    }

    int main ( )

    {

    A=5;

    B=7;

    answer= add ();printf (%d\n, answer);

    return 0;

    }

    int A;

    int B;

    int answer;

    Global variable A & B has been

    declared at the start of the

    program. They have been used in

    add ( ) and main ( ) function.

    Local variable answer has been

    declared under main ( ) function.

    Thats why, the scope of the

    variable answer is limited to the

    main () function.

  • 8/12/2019 Programming Basics-Additional Questions & Answers

    3/8

    Nicholas, MIS 07-015

    rogramming Fundamentals

    What is a recursive function? What are its properties?

    A recursive function is a function that calls itself during its execution.

    At first recursion may seem like a never ending loop, or like a dog chasing its tail. It can never

    catch it. So too it seems our function will never finish. This might be true in some cases, but inpractice we can check to see if a certain condition is true and in that case exit (return from) our

    function. The case in which we end our recursion is called a base case. Additionally, just as in a

    loop, we must change some value and incrementally advance closer to our base case.

    Example:

    Undefined if n1

    5!= 5 X 4!

    = 5 X 4 X 3!

    = 5 X 4 X 3 X 2!

    = 5 X 4 X 3 X 2 X 1!(base case is found)

    = 5 X 4 X 3 X 2 X 1(returns 1, according to our condition)

    = 120 (recursion stops and shows the final answer)

    Properties of a recursive function:

    Every recursion should have the following characteristics:

    1. Recursive functions always call themselves at some point.2. Recursive functions must have at least one base case which we have a solution for and a

    return value. Sometimes there is more than one base case, and return value must be

    defined for each base case. Base cases are the conditions that stop the function being

    called yet again.

    3. The recursive calls must converge on the base case condition, i.e. each call must benearer the base case condition than the previous one.

    4. Forgetting the base case might lead to infinite recursion and cause the program fail,hang the overall system etc.

    What is Binary Search? How does it work?

    Binary search locates the position of an item in a sorted array. The elements of the array must

    be sorted in ascending or descending order, before binary search can work on them. If the

    array is not sorted, the binary search cannot be applied and therefore it may not provide the

    right answer. Suppose we have a sorted list L and in this list we are searching for a value X. The

    binary search will be conducted by:

    1.

    Compare X to the middle value (M) in L.2. if X = M we are done.

    The factorial of n, written as n! is equal to the product of n(n-1)(n-

    2)...(1).To find factorial of n, we can write n(n-1)!. Thus, the

    method "recurses" to find the factorial of (n-1), and then

    multiplies whatever it got by n to give a final answer. Of course, to

    find the factorial of (n-1), it'll first calculate the factorial of (n-2),and so on. The base case would be when n is 0 or 1, in which case

    it knows to return 1 since 0! = 1! = 1.

  • 8/12/2019 Programming Basics-Additional Questions & Answers

    4/8

  • 8/12/2019 Programming Basics-Additional Questions & Answers

    5/8

    Nicholas, MIS 07-015

    rogramming Fundamentals

    The complexity of bubble sort:

    f (n)= total number of comparisons to sort n data items using bubble sort

    = (n-1) + (n-2) + (n-3) + ..+ 1

    1stpass 2ndpass 3rdpass (n-1)th pass

    = (n (n-1))/ 2

    = O (n2) [Big O of n2]

    Program coding-Binary Search Program coding-Linear search

    #include

    main()

    {

    int n,i,a[100],item,loc,left,right,mid;

    scanf("%d",&n);

    for(i=0;i right)printf("\n\nItem %d NOT found.",item);

    else

    printf("\n\nItem %d found at %d",item,mid+1);

    }

    #include

    main()

    {

    int n,i,a[100],item,loc;

    scanf("%d",&n);

    for(i=0;i

  • 8/12/2019 Programming Basics-Additional Questions & Answers

    6/8

    Nicholas, MIS 07-015

    rogramming Fundamentals

    Find the factorial of a number n

    Algorithm Program Coding

    fact (n)

    {

    1. if (n=1 or 0)2. return 1;

    3. else

    4. return n* fact (n-1);

    }

    #include

    int fact(int n)

    {

    if( (n==0) || (n==1) )return 1;

    else

    return n * fact(n-1);

    }

    main()

    {

    int n,f;

    scanf("%d",&n);

    f = fact(n);printf("\n\nFactorial of %d = %d ",n,f);

    }

    What is Fibonacci sequence?

    The Fibonacci sequence is the series of numbers:

    0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,...

    The next number is found by adding up the two numbers before it. The 2 is found by adding the two numbers before it (1+1) Similarly, the 3 is found by adding the two numbers before it (1+2), And the 5 is (2+3), And so on!

    Rule of Fibonacci series:

    First, the terms are numbered from 0 onwards like this:

    n = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...xn= 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 ...

    Example: the 8thterm is

    the 7thterm plus the 6thterm:

    x8= x7+ x6

    So term number 6 is called x6(which equals 8).

  • 8/12/2019 Programming Basics-Additional Questions & Answers

    7/8

    Nicholas, MIS 07-015

    rogramming Fundamentals

    The Rule is xn= xn-1+ xn-2where:

    xnis term number "n" xn-1is the previous term (n-1) xn-2is the term before that (n-2)

    Algorithm Program Coding

    Fibo (n)

    {

    1. if (n=1 or 2)

    2. return 1;

    3. else

    4. return fibo (n-1)+ fibo (n-2);

    }

    #include

    int fibo(int n)

    {

    if( (n==1) || (n==2) )

    return 1;

    else

    return fibo(n-1)+ fibo(n-2);

    }

    main()

    {

    int n,f;

    scanf("%d",&n);

    f = fibo(n);

    printf("\n\n%d (st/nd/rd/th) Fibonacci

    number = %d ",n,f);

    }

    Find whether a number is prime or not prime

    Algorithm Program Coding

    prime ( )

    {

    1. input n;

    2. m= sqrt (n);

    3. for ( i=2; i

  • 8/12/2019 Programming Basics-Additional Questions & Answers

    8/8

    Nicholas, MIS 07-015

    i F d t l

    What is Tower of Hanoi? Describe the rule.

    The Tower of Hanoiis a mathematical game or puzzle. It consists of three rods, and a number

    of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a

    neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical

    shape.

    The objective of the puzzle is to move the entire stack to another rod (sourceto destination

    using the auxiliaryrod), obeying the following simple rules:

    1. Only one disk may be moved at a time.2. Each move consists of taking the upper disk from one of the stacks and placing it on top

    of another stack.

    3. No disk may be placed on top of a smaller disk.With three disks, the puzzle can be solved in seven moves. The minimum number of moves

    required to solve a Tower of Hanoi puzzle is 2n- 1, where nis the number of disks

    Algorithm Program Coding

    tower ( )

    {

    1. if( n> 1)

    2. tower(n-1,s,d,a);

    3. printf("\n %c --> %c",s,d);

    4. if( n > 1 )5. tower(n-1,a,s,d);

    }

    #include

    int tower(int n, char s, char a, char d)

    {

    if( n> 1)

    tower(n-1,s,d,a);

    printf("\n %c --> %c",s,d);if( n > 1 )

    tower(n-1,a,s,d);

    }

    main()

    {

    int n,f;

    scanf("%d",&n);

    tower(n, 'S', 'A', 'D');

    }