#include <stdio.h>
int main()
{
int num;
printf("Enter the no. whose multiplication table you want :");
scanf("%d", &num);
for (int i = 1; i <= 10; i++)
{
printf("%d X %d = %d\n", num, i, num * i);
}
return 0;
}
#include <stdio.h>
int main()
{
int num, sum = 0;
printf("Enter the number : ");
scanf("%d", &num);
for (int i = 1; i <= num; i++)
{
sum += i;
}
printf("The sum till %d is = %d", num, sum);
return 0;
}
O(n)
This did the job but its not a efficient way to do it as it have to iterate over
every single element but we don't want that. And also when n → ⧝ this algorithm
will be slow.
we are going to achieve this using a formula and then the time complexity will be O(1).
#include <stdio.h>
int main()
{
int num, sum = 0;
printf("Enter the number : ");
scanf("%d", &num);
sum = ((num * num + num) / 2);
printf("The sum till %d is = %d", num, sum);
return 0;
}
#include <stdio.h>
int largest(int arr[], int size)
{
int max = arr[0];
for (int i = 0; i < size; i++)
{
if (arr[i] > max)
max = arr[i];
}
return max;
}
int main()
{
int arr[] = {1, 4, 6, 3, 47, 1000, 77, 56, 345, 56, 678};
int size = sizeof(arr) / sizeof(int);
printf("The largest number is : %d", largest(arr, size));
return 0;
}
Prime numbers: whose factors are 1 and the number itself.
#include <stdio.h>
#include <math.h>
int main()
{
int num = 31, isPrime = 1;
for (int i = 2; i < sqrt(num); i++)
{
if (num % i == 0)
{
isPrime = 0;
}
}
if (isPrime)
{
printf("%d is a prime number\n", num);
}
else
{
printf("%d is not a prime number", num);
}
return 0;
}
#include <stdio.h>
int main()
{
int num = 7;
int i = 0;
int arr[10];
while (num > 0)
{
arr[i] = num % 2;
num /= 2;
i++;
}
for(int j = i-1; j >=0; j--){
printf("%d ",arr[j]);
}
return 0;
}
#include <stdio.h>
int main()
{
int num = 14459;
int digits = 0;
int temp = num;
num = 0;
while (temp)
{
num*=10;
num += temp % 10;
temp /= 10;
}
printf("The reversed number is %d",num);
return 0;
}
#include <stdio.h>
int main()
{
int num = 5;
long factorial = 1;
if(num==0 || num==1)
{
printf("1");
} else
{
while (num>1)
{
factorial *= (long) (num);
num--;
}
}
printf("Factorial = %ld",factorial);
return 0;
}
#include <stdio.h>
int factorialRecursive(int n)
{
if (n == 0 || n == 1)
{
return 1;
}
while (n > 1)
{
return n * factorialRecursive(n - 1);
}
}
int main()
{
int n;
printf("Enter the value of number for factorial calculation\n");
scanf("%d", &n);
int factorial = factorialRecursive(n);
printf("The value of factorial is %d\n", factorial);
return 0;
}