Fundamentals of Computer Programming 2070

Tribhuwan University
Institute of Science and Technology
2070
Bachelor Level / First Semester / Science
Computer Science and Information Technology ( CSC-102 )
( Fundamentals of Computer Programming )
Full Marks: 60
Pass Marks: 24
Time: 3 hours
Candidates are required to give their answers in their own words as far as practicable.
The figures in the margin indicate full marks.

Attempt all questions

1. What is logical error? Write flowchart and program for checking whether the number entered by the user is exactly divisible by 5 or by 11. [1+5]

OR

What is algorithm? Write an algorithm to check given number is prime or composite. [1+5]

6 marks view

2. What is operator? List any six operators used in C-programming language. Write a program to find least number between any two numbers using ternary operator. [1+2+3]

6 marks view

An operator is a symbol that operates on single or multiple data items. It is used in program to perform certain mathematical or logical manipulations.

E.g. In a simple expression 2+3, the symbol “+” is called an operator which operates on two data items 2 and 3.

C operators can be classified into following types:

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Assignment Operators
  • Increment and Decrement Operators
  • Conditional Operators

Program to find least number between any two numbers using ternary operator:

#include <stdio.h>

#include<conio.h>

int main()

{

    int n1, n2,least; 

    printf("Enter two numbers: ");

    scanf("%d%d", &n1, &n2);

    least = n1<n2 ? n1:n2;

    printf("The least number is %d",least);

    getch();

    return 0;

}

3. Define printf() function, header file and main function. Find the value of following expression. Use the value initially assigned to the variables for each expressions.   [4.5+1.5]

int a = 8, b = 5;

float x = 0.005, y = -0.01;

1) 2 * ((a / 5) + 4 * (b – 3)) % (a + b - 2));

2) (x > y) && (a > 0) || (b < 5);

3) (a > b)?a:b;

6 marks view

printf() function

printf is an output function which has been defined in stdio.h file. What ever is put inside the function printf between two double quotes is printed on the screen.

E.g. printf(“Welcome to C programming”);

    Output: Welcome to C programming

Header file

A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that comes with your compiler.

You request to use a header file in your program by including it with the C preprocessing directive #include, like you have seen inclusion of stdio.h header file, which comes along with your compiler.

main function

Every C-programs needs to have the main function. Each main function contains 2 parts.

Declaration part: The declaration part declares all the variables used in the executable part.

Executable part: There is at least one statement in the executable part. These two parts must appear between the opening and closing braces. The program execution begins at the opening brace and ends at the closing brace. The closing brace of the main function is the logical end of the program.

E.g.

int main( )

{

    int a=10;

    printf(“%d”, a);

    return 0;

}


Now,

Given,

    int a = 8, b = 5;

    float x = 0.005, y = -0.01;

1) 2 * ((a / 5) + 4 * (b – 3)) % (a + b - 2));

    = 2*((8/5)+4*(5-3))%(8+5-2)

    = 2*(1+4*2)%11

    = 2*9 % 11

    = 18 % 11

    = 7

2) (x > y) && (a > 0) || (b < 5);

    = (0.005>-0.01)&&(8>0)||(5<5)

    = (1)&&(1)||(0)

    = 1|| 0

    = 1

3) (a > b)?a:b;

    = (8>5)?8:5;

    = 8    [Using ternary principle)

4. Difference between if and switch statement. Write a program to read the marks of four subjects then find total, percentage and division according to given condition. [1+5]

Percentage                                    Division

p ≥ 80                                             Distinction

80 > p ≥ 70                                     First division

70 > p ≥ 50                                     Second division

50 > p ≥ 40                                     Third division

Otherwise Fail.

Assume each subjects carrying 100 full marks and students must secure greater or equal to 40 in each subjects for division.

6 marks view

Difference between if and switch statement

1. SWITCH statement is easier to express for lengthy conditions when compared to an IF statement which gets more complex as the number of conditions grow and the nested IF comes into play.

2. SWITCH statement allows easy proofreading while testing and removing bugs from the source code whereas IF statement makes editing difficult.

3. Expression is evaluated and SWITCH statement is run according to the result of the expression that can be integer or logical while IF statement is run only if the result of the expression is true.

4. SWITCH allows expression to have integer based evaluation while IF statement allows both integer and character based evaluation.

5. SWITCH statement can be executed with all cases if the ‘break’ statement is not used whereas IF statement has to be true to be executed further.

Program

#include <stdio.h> int main() { int phy, chem, bio, math; float p, total;

/* Input marks of five subjects from user */ printf("Enter four subjects marks: "); scanf("%d%d%d%d", &phy, &chem, &bio, &math);

/* Calculate total */ total= (phy + chem + bio + math); printf("Total marks = %f\\n", total); /* Calculate percentage */ p = (phy + chem + bio + math) / 4.0; printf("Percentage = %f\\n", p); /* Find division according to the percentage */ if(p >= 90) { printf("Division: Distinction"); } else if(p>=70 && p<80 ) { printf("Division: First division"); } else if(p>=50 && p<70) { printf("Division: Second division"); } else if(p>=40 && p<50) { printf("Division: Third division"); } else { printf("Fail"); } return 0; }

5. Differentiate between break and continue statement. Write a program to display following output.  [2+4]

1

1 1

1 1 1

1 1 1 1

1 1 1 1 1

6 marks view

Difference between break and continue statement

BreakContinue
Break is used to break loop or iteration.Continue continues the loop or iteration.
Used with switch case loop.Not used with switch case.
Keyword used is "break".Keyword used is "continue".
Breaks loop and allows coming out from it.Allows iterating in the loop.
Control is transferred outside the loop.Control remains in the same loop.

E.g.

  1. for(i=1; i<=5 ; i++) 
  2. { 
  3. if(i==3) 
  4. break; 
  5. Printf("%d\\n",i); 
  6. } 

Output:  1, 2

E.g.

  1. For(i=1 ;i<=5; i++) 
  2. { 
  3. if(i==3)  
  4. continue; 
  5. printf("%d\\n",i); 
  6. } 

Output: 1, 2, 4, 5

Program to display given output

#include<stdio.h>

#include<conio.h>

#define n 5

int main()

{

    int i, j;

    for(i=1;i<=n;i++)

    {

        for(j=1;j<=1;j++)

        {

            printf("\\t1");

        }

        printf("\\n");

    }

    getch();

    return 0;

}

6. Write a program to input any 10 numbers then find out greatest and smallest number. [6]

6 marks view

#include<stdio.h>

int main()

{

    int a[50], i, big, small;

    int n=10;

    printf("\\n\\nEnter the %d elements of the array: \\n\\n", n);

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

        scanf("%d", &a[i]);


    big = a[0];     // initializing

    /* from 2nd element to the last element find the bigger element than big and update the value of big */

    for(i = 1; i < n; i++)

    {

        if(big < a[i])   // if larger value is encountered

        {

            big = a[i]; // update the value of big

        }

    }

    printf("\\n\\nThe largest element is: %d", big);

    small = a[0];   // initializing

    /* from 2nd element to the last element find the smaller element than small and update the value of small*/

    for(i = 1; i < n; i++)

    {

        if(small>a[i])   // if smaller value is encountered

        {

            small = a[i];   // update the value of small

        }

    }

    printf("\\n\\nThe smallest element is: %d", small);

    return 0;

}

7. Write a program to add two 3×3 matrix using function. [6]

6 marks view
#include<stdio.h>
#include<conio.h>
void show_matrix(int mat[3][3]);
void add_matrix(int matA[3][3], int matB[3][3], int matSum[3][3]);
int main()
{
 int x[3][3], y[3][3], z[3][3];
 int i, j;
 printf("\\nEnter elements of matrix 1:\\n");
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
printf("Enter elements a[%d][%d]: ", i + 1, j + 1);
scanf("%d", &x[i][j]);
}
}

printf("\\nEnter elements of matrix 2:\\n");
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
printf("Enter elements b[%d][%d]: ", i + 1, j + 1);
scanf("%d", &y[i][j]);
}
}
add_matrix(x,y,z);
 printf("\\nFirst matrix is :\\n");
 show_matrix(x);
 printf("\\nSecond matrix is :\\n");
 show_matrix(y);
 printf("\\nNew addition matrix is :\\n");
 show_matrix(z);
 getch();
 return 0;
}
void add_matrix(int matA[3][3], int matB[3][3], int matSum[3][3])
{
  int r,c;
  for(r=0; r<3; r++)
  {
    for(c=0; c<3; c++)
        matSum[r][c]=matA[r][c]+matB[r][c];
  }
}

void show_matrix(int mat[3][3])
{
  int r,c;
  for(r=0; r<3; r++)
  {
    for(c=0; c<3; c++)
        printf(" %d",mat[r][c]);
    printf("\\n");
  }
}

8. What is recursion? Write a program to find the factorial of given number using recursion. [2+4]

OR

What is pointer? Write a program to sort 'n' numbers in ascending order using dynamic memory. [2+4]

6 marks view

A function that calls itself is known as a recursive function. And, this technique is known as recursion.

Program  to find the factorial of given number using recursion:

#include<stdio.h>

int fact(int);

int main()

{

    int x,n;

    printf(" Enter the Number to Find Factorial :");

    scanf("%d",&n);

    x=fact(n);

    printf(" Factorial of %d is %d",n,x);

    return 0;

}

int fact(int n)

{

    if(n==0)

        return(1);

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

}

____________________________

OR Part:

pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location.



program to sort 'n' numbers in ascending order using dynamic memory:

#include<stdio.h>

#include<stdlib.h>

int main()

{

      int *a,n,i,j,t;

      printf("How many numbers you want to be sorted: ");

      scanf("%d",&n);

      a=(int *)malloc(n *sizeof(int));

      printf("\\nEnter %d Numbers: \\n\\n",n);

      for(i=0;i<=n-1;i++)

      {

            scanf("%d", (a+i));

      }

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

      {

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

            {

                  if(*(a+i)<*(a+j))

                  {

                        t=*(a+i);

                        *(a+i)=*(a+j);

                        *(a+j)=t;

                  }

            }

      }

      printf("\\nAfter Sorting in Ascending Order: \\n");

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

      printf("\\n%d",*(a+i));

      return 0;

}

9. List any five names of graphics function. Write a program to read line of text then count no. of vowels, No. of digits and no. of spaces. [2+4]

6 marks view

Some names of graphics function:

initgraph(): it is one of the function that is used to initialize the computer in graphics mode. Its syntax is as

        initgraph(&gdriver, &gmode, "graphics driver path");

closegraph(): It is the graphical function that is used to close the graphics mode initialized by the initgraph() function.

setcolor(color): It is a function that is used to set the color of the drawing object with given color. The color is indicated by the integer from 0 to 15 ( 16 color)

lineto(x, y): draws the line from current position to (x,y) position.

clrscr(): It is used to clear the screen and locates the curser at the beginning of the screen.

cputs(string): it writes a string given to function to the user defined window screen.

putch(char) : it writes a character given to function to the user defined area of window.

line(a, b, c, d): draws line from (a,b) to (c,d).

circle(x, y, r): prints circle with center (x,y) and radius r.

rectangle(a, b, c, d): prints rectangle where (a,b) is upper left coordinate and (c,d) is lower right co-ordinates of rectangle.


Program to read line of text then count no. of vowels, No. of digits and no. of spaces:

#include <stdio.h>

void main()

{

    char str[200];

    int i, vowels=0, digits=0, spaces=0;

    printf("Enter a string\\n");

    gets(str);

    for(i=0;str[i]!='\\0';i++)

    {

        if(str[i]=='a' || str[i]=='e' || str[i]=='i' ||str[i]=='o' || str[i]=='u' || str[i]=='A' ||str[i]=='E' || str[i]=='I' || str[i]=='O' ||str[i]=='U')

        {

            vowels++;

        }

       

        else if(str[i]>='0' && str[i]<='9')

        {

            digits++;

        }

        else if (str[i]==' ')

        {

            spaces++;

        }

    }

    printf("\\nVowels = %d",vowels);

    printf("\\nDigits = %d",digits);

    printf("\\nWhite spaces = %d",spaces);

}

10. Write a program to create a file "RECORD.TXT" then store roll no, name and percentage of 10 students. [6]

6 marks view