Sample C programs
26. Program to Display "Hello, World!"
Ans:
#include <stdio.h>
int main()
{
// printf() displays the
string inside quotation
printf("C
Programming");
return 0;
}
27. Program to Add Two Integers
Ans:
#include <stdio.h>
int main()
{
int firstNumber,
secondNumber, sumOfTwoNumbers;
printf("Enter two integers: ");
// Two integers entered by
user is stored using scanf() function
scanf("%d
%d",&firstNumber, &secondNumber);
// sum of two numbers in
stored in variable sumOfTwoNumbers
sumOfTwoNumbers = firstNumber
+ secondNumber;
// Displays sum
printf("%d + %d =
%d", firstNumber, secondNumber, sumOfTwoNumbers);
return 0;
}
28. Program to Swap Numbers Using Temporary Variable
Ans:
#include <stdio.h>
int main()
{
double firstNumber,
secondNumber, temporaryVariable;
printf("Enter first
number: ");
scanf("%lf",
&firstNumber);
printf("Enter second
number: ");
scanf("%lf",&secondNumber);
// Value of firstNumber is
assigned to temporaryVariable
temporaryVariable =
firstNumber;
// Value of secondNumber is
assigned to firstNumber
firstNumber = secondNumber;
// Value of
temporaryVariable (which contains the initial value of firstNumber) is assigned
to secondNumber
secondNumber =
temporaryVariable;
printf("\nAfter
swapping, firstNumber = %.2lf\n", firstNumber);
printf("After
swapping, secondNumber = %.2lf", secondNumber);
return 0;
}
29. Program to find Factorial of a Number
Ans:
#include <stdio.h>
int main()
{
int n, i;
unsigned long long factorial
= 1;
printf("Enter an
integer: ");
scanf("%d",&n);
// show error if the user
enters a negative integer
if (n < 0)
printf("Error!
Factorial of a negative number doesn't exist.");
else
{
for(i=1; i<=n; ++i)
{
factorial *= i; // factorial = factorial*i;
}
printf("Factorial of
%d = %llu", n, factorial);
}
return 0;
}
30. Program to find Fibonacci Series up to n number of terms
Ans:
#include <stdio.h>
int main()
{
int i, n, t1 = 0, t2 = 1,
nextTerm = 0;
printf("Enter the number
of terms: ");
scanf("%d",&n);
// displays the first two
terms which is always 0 and 1
printf("Fibonacci
Series: %d, %d, ", t1, t2);
// i = 3 because the first
two terms are already dislpayed
for (i=3; i <= n; ++i)
{
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
printf("%d,
",nextTerm);
}
return 0;
}
EmoticonEmoticon