0% found this document useful (0 votes)
48 views3 pages

C Programs Aim Algorithm Code

Uploaded by

rrajkumar73002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views3 pages

C Programs Aim Algorithm Code

Uploaded by

rrajkumar73002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C Programs with Aim, Elaborated Algorithm, and Code

1. Fibonacci Series using for loop

Aim: To print the Fibonacci series up to n terms using a for loop in C.

Algorithm:

- Start the program.

- Declare variables: a = 0, b = 1, next, and i.

- Input the number of terms (n) from the user.

- Print the first two terms (a and b).

- Run a for loop from i = 2 to n-1:

- - Compute next = a + b

- - Print next

- - Update a = b and b = next

- End the program.

Code:
#include <stdio.h>
int main() {
int n, a = 0, b = 1, next, i;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: %d %d ", a, b);
for(i = 2; i < n; i++) {
next = a + b;
printf("%d ", next);
a = b;
b = next;
}
return 0;
}

2. Palindrome Check using while loop

Aim: To check whether a given number is a palindrome using a while loop.

Algorithm:

- Start the program.

- Input a number and store in variable num.

- Store the value of num in temp.

- Initialize reverse = 0.

- Repeat while temp != 0:


- - Extract last digit: digit = temp % 10

- - Add to reverse: reverse = reverse * 10 + digit

- - Remove last digit: temp = temp / 10

- Compare reverse with num.

- If they are equal, it's a palindrome; otherwise, it's not.

- End the program.

Code:
#include <stdio.h>
int main() {
int num, reverse = 0, temp, digit;
printf("Enter a number: ");
scanf("%d", &num);
temp = num;
while(temp != 0) {
digit = temp % 10;
reverse = reverse * 10 + digit;
temp /= 10;
}
if(num == reverse)
printf("%d is a palindrome.\n", num);
else
printf("%d is not a palindrome.\n", num);
return 0;
}

3. Sum of Natural Numbers using while loop

Aim: To calculate the sum of first n natural numbers using a while loop.

Algorithm:

- Start the program.

- Input a positive number n.

- Initialize i = 1 and sum = 0.

- While i <= n, repeat:

- - Add i to sum

- - Increment i

- Print the result.

- End the program.

Code:
#include <stdio.h>
int main() {
int n, i = 1, sum = 0;
printf("Enter a positive number: ");
scanf("%d", &n);
while(i <= n) {
sum += i;
i++;
}
printf("Sum of first %d natural numbers is %d\n", n, sum);
return 0;
}

You might also like