C Programming Lab Manual – 15

Write a C program to Display Fibonacci Series Up to n Terms.

Function Main
    Declare Integer i
    Declare Integer n
    Declare Integer t1
    Declare Integer t2
    Assign t1 = 0
    Assign t2 = 1
    Declare Integer nextTerm
    Assign nextTerm = t1 + t2
    Output "Enter the number of terms: "
    Input n
    Output "Fibonacci Series: " &t1
    Output ", " &t2
    For i = 3 to n
        Output ", " &nextTerm
        Assign t1 = t2
        Assign t2 = nextTerm
        Assign nextTerm = t1 + t2
    End
End

#include <stdio.h>
int main() {

  int i, n;
  int t1 = 0, t2 = 1;
  int nextTerm = t1 + t2;
  printf("Enter the number of terms: ");
  scanf("%d", &n);

  printf("Fibonacci Series: %d, %d, ", t1, t2);

  for (i = 3; i <= n; ++i) {
    printf("%d, ", nextTerm);
    t1 = t2;
    t2 = nextTerm;
    nextTerm = t1 + t2;
  }

  return 0;
}

Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

C Programming Lab Manual – 14

Write a C program to Find the Factorial of a Number.

Function Main
    Declare Integer n
    Declare Integer i
    Declare Integer fact
    Assign fact = 1
    Output "Enter an integer: "
    Input n
    If (n<0)
        Output "Error! Factorial of a negative number doesn't exist."
    Else
        For i = 1 to n
            Assign fact = fact * i
        End
        Output "Factorial is " &fact
    End
End

#include <stdio.h>
int main() {
    int n, i;
    int fact = 1;
    printf("Enter an integer: ");
    scanf("%d", &n);

    if (n < 0)
        printf("Error! Factorial of a negative number doesn't exist.");
    else {
        for (i = 1; i <= n; ++i) {
            fact *= i;
        }
        printf("Factorial is %d",fact);
    }

    return 0;
}

Enter an integer: 5
Factorial is 120 

C Programming Lab Manual – 13

Write a C program to Reverse a Number.

Function Main
    Declare Integer n
    Declare Integer reverse
    Assign reverse = 0
    Declare Integer remainder
    Output "Enter an integer:  "
    Input n
    While (n!=0)
        Assign remainder = n % 10
        Assign reverse = reverse * 10 + remainder
        Assign n = n / 10
    End
    Output " Reversed number = " &reverse
End
#include <stdio.h>

int main() {

  int n, reverse = 0, remainder;

  printf("Enter an integer: ");
  scanf("%d", &n);

  while (n != 0) {
    remainder = n % 10;
    reverse = reverse * 10 + remainder;
    n /= 10;
  }

  printf("Reversed number = %d", reverse);

  return 0;
}

Enter an integer: 1234
Reversed number = 4321