c program – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 10 Mar 2024 17:05:13 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg c program – Programmerbay https://programmerbay.com 32 32 C Program to Sort an array using Selection Sort in Ascending Order https://programmerbay.com/program-to-sort-an-array-using-selection-sort/ https://programmerbay.com/program-to-sort-an-array-using-selection-sort/#respond Sun, 03 Mar 2024 17:20:38 +0000 https://www.programmerbay.com/?p=2879 The program sorts uses Selection Sort technique to sort the given array. There are bunch of sorting mechanisms such as Bubble sort, Insertion sort and more to achieve this functionality. In this, we’ll be only focusing Selection Sort .

Selection Sort

Selection sort is a sorting technique wherein at each iteration, a minimum element is selected from an unsorted array and compared with all other remaining elements. if an element is found that is smaller than already assumed minimum element,  swapping would be performed.

It divides an array into two parts. One that is already sorted and another one which is still unsorted that need to be arranged.

From unsorted sublist, the algorithm finds the minimum element and adds on to sorted category. It ends when we get a single consolidated sorted sublist.

Pseudocode

FOR i=0 to Array.Length
minimum = i
FOR j=0 to Array.Length
if A[min]< A[j])
Swap A[min] with A[j]
End IF
END FOR
END FOR

C program to sort an array using Selection Sort in Ascending Order

#include<conio.h>
#include<stdio.h>
#define size 5
void main()
{
int arr[size],i,j,temp,min;
printf("Please enter elements: \n "); 
for(i=0;i<=size-1;i++)
{
scanf("%d",&arr[i]);
}

for(i=0;i<=size-1;i++)
{
min= i;
for(j=0;j<=size-1;j++)
{
if(arr[min]<arr[j]){
temp = arr[j];
arr[j] =arr[min];
arr[min] = temp;
}
}
}

printf(" \n Entered Elements :");

for(i=0;i<=size-1;i++)
{
printf("\n %d ",arr[i]);
} 
getch();

}

Output:

Screenshot from 2024 03 10 22 22 03

 

How does Selection Sort work?

Screenshot from 2024 03 10 22 28 33

 

Lastly, it is an inefficient algorithm for the large dataset as it requires O(n2) comparisons in all cases worst, average and best case. It is simple and occasionally has an upper hand over other complicated algorithms.

]]>
https://programmerbay.com/program-to-sort-an-array-using-selection-sort/feed/ 0
C Program to Draw a Hut https://programmerbay.com/c-program-to-draw-a-hut/ https://programmerbay.com/c-program-to-draw-a-hut/#respond Thu, 29 Feb 2024 17:23:26 +0000 https://www.programmerbay.com/?p=1886 C supports a header file named “graphics.h” which enables us to draw various figures. In this, we’ll be using line and rectangle function of that particular header file to draw a hut.

C Program to draw a hut in computer graphics

Program:

#include<graphics.h>
#include<stdio.h>
#include<conio.h>
void main(){
int gd=DETECT,gm;
initgraph(&gd,&gm,"C:\\TURBOC3\\BGI");
printf("\t\t ********* HUT ********");
line(150,100,50,200);
line(150,100,350,100); 
line(150,100,300,200);
line(300,200,500,200);
line(350,100,500,200);
line(50,200,300,200);
rectangle(50,400,300,200);
rectangle(300,200,500,400);
rectangle(130,250,230,400);

getch();
closegraph();

}

Output:

Hut

]]>
https://programmerbay.com/c-program-to-draw-a-hut/feed/ 0
C Program to draw Bezier Curve using 4 control points https://programmerbay.com/c-program-to-draw-bezier-curve-using-4-control-points/ https://programmerbay.com/c-program-to-draw-bezier-curve-using-4-control-points/#respond Sat, 24 Feb 2024 16:41:31 +0000 https://www.programmerbay.com/?p=2143 Bezier Curve is one of the Curve representation which uses control points to draw a curve. It is always determined on the number of control points that require to draw it. It follows Bernstein polynomial as the basis function.

Must Read [  What is Bezier Curve ?  ]

C Program to draw a Bezier curve

Program:

#include<graphics.h>
#include<math.h>
#include<conio.h>
#include<stdio.h>
void main()
{
int x[4],y[4],i;
double put_x,put_y,t;
int gr=DETECT,gm;
initgraph(&gr,&gm,"C:\\TURBOC3\\BGI");
printf("\n****** Bezier Curve ***********");
printf("\n Please enter x and y coordinates ");
for(i=0;i<4;i++)                 
{
scanf("%d%d",&x[i],&y[i]);
putpixel(x[i],y[i],3);                // Control Points
}

for(t=0.0;t<=1.0;t=t+0.001)             // t always lies between 0 and 1
{
put_x = pow(1-t,3)*x[0] + 3*t*pow(1-t,2)*x[1] + 3*t*t*(1-t)*x[2] + pow(t,3)*x[3]; // Formula to draw curve
put_y =  pow(1-t,3)*y[0] + 3*t*pow(1-t,2)*y[1] + 3*t*t*(1-t)*y[2] + pow(t,3)*y[3];
putpixel(put_x,put_y, WHITE);            // putting pixel 
}
getch();
closegraph();
}

 

Output:

bezier curve

 

]]>
https://programmerbay.com/c-program-to-draw-bezier-curve-using-4-control-points/feed/ 0
C Program to Calculate Average, Geometric and Harmonic Mean https://programmerbay.com/c-program-that-calculates-the-average-geometric-and-harmonic-mean/ https://programmerbay.com/c-program-that-calculates-the-average-geometric-and-harmonic-mean/#respond Thu, 25 Aug 2022 07:05:22 +0000 https://programmerbay.com/?p=5357 The C programs calculate geometric mean, average mean, and harmonic mean using their respective formulas. It simply applies these formula on the given input to calculate and print the result.

In this, we are using following formula directly in the code:

Geometric Mean :Geometric meanAverage : arthimatic meanHarmonic mean :Harmonic mean

Example 1. Program to calculate arithmetic mean in C

Program:

#include<stdio.h>


int main ()
{
  int i, size;
  float arr[10], arithmeticMean;
  float sum = 0;
  printf ("Please enter the number of elements = ");
  scanf ("%d", &size);
  printf ("Now, enter the elements \n");
  for (i = 0; i < size; i++)
    {
      printf ("Element %d : ", i + 1);
      scanf ("%f", &arr[i]);
    }
    
  for (i = 0; i < size; i++)
    {
      sum = sum + arr[i];
    }
    
  arithmeticMean = (float) (sum / size);

  printf
    ("\n Average or Arithmetic Mean = %.2f", arithmeticMean);

  return 0;
}

Output

Please enter the number of elements = 9
Now, enter the elements 
Element 1 : 1
Element 2 : 2
Element 3 : 3
Element 4 : 4 
Element 5 : 5
Element 6 : 6
Element 7 : 7
Element 8 : 8
Element 9 : 9

 Average or Arithmetic Mean = 5.00

Example 2. Program to calculate Harmonic mean in C

Program:

#include<stdio.h>


int main (){
  int i, size;
  float arr[10], oneNthValue = 0;
  float harmonicMean;
  printf ("Please enter the number of elements = ");
  scanf ("%d", &size);
  printf ("Now, enter the elements \n");
  for (i = 0; i < size; i++) {
      printf ("Element %d : ", i + 1);
      scanf ("%f", &arr[i]);
    }

  for (i = 0; i < size; i++) {
      oneNthValue = oneNthValue + 1 / arr[i];
    }

  harmonicMean = (float) size / oneNthValue;

  printf ("\n Harmonic mean= %.2f ", harmonicMean);

  return 0;
}

Output:

Please enter the number of elements = 5
Now, enter the elements 
Element 1 : 2
Element 2 : 4
Element 3 : 6
Element 4 : 8
Element 5 : 10

 Harmonic mean= 4.38

Example 3. Program to calculate Geometric mean in C

Program: 

#include<stdio.h>
#include<math.h>


int main ()
{
  int i, size;
  double product = 1, root;
  float arr[10], oneNthValue = 0;
  float geometricMean;
  printf ("Please enter the number of elements = ");
  scanf ("%d", &size);
  printf ("Now, enter the elements \n");
  for (i = 0; i < size; i++)
    {
      printf ("Element %d : ", i + 1);
      scanf ("%f", &arr[i]);
    }
    
  for (i = 0; i < size; i++)
    {
      product = (double) product *arr[i];
    }
    
  root = (double) 1 / size;
  geometricMean = (float) pow (product, root);

  printf("Geometric mean = %.2f", geometricMean);

  return 0;
}

Output:

Please enter the number of elements = 5
Now, enter the elements 
Element 1 : 12
Element 2 : 23
Element 3 : 14
Element 4 : 11
Element 5 : 17
Geometric mean = 14.85

Write a program that reads a series of n numbers and calculates the average, geometric and harmonic mean of n elements in an array in C 

Program:

#include<stdio.h>
#include<math.h>

/*
C program to calculate arithmetic mean, harmonic mean and geometric mean

*/
int main ()
{
  int i, size;
  double product = 1, root;
  float arr[10], oneNthValue = 0;
  float harmonicMean, averageMean, geometricMean;
  float sum = 0;
  printf ("Please enter the number of elements = ");
  scanf ("%d", &size);
  printf ("Now, enter the elements \n");
  for (i = 0; i < size; i++)
    {
      printf ("Element %d : ", i + 1);
      scanf ("%f", &arr[i]);
    }
    
  for (i = 0; i < size; i++)
    {
      oneNthValue = oneNthValue + 1 / arr[i];
      sum = sum + arr[i];
      product = (double) product *arr[i];
    }
    
  root = (double) 1 / size;
  harmonicMean = (float) size / oneNthValue;
  averageMean = (float) (sum / size);
  geometricMean = (float) pow (product, root);

  printf
    ("\n Harmonic mean= %.2f \n Arithmetic mean = %.2f \n Geometric mean = %.2f",
     harmonicMean, averageMean, geometricMean);

  return 0;
}

 

Output:

Please enter the number of elements = 5 
Now, enter the elements 
Element 1 : 21 
Element 2 : 3 
Element 3 : 45 
Element 4 : 76 
Element 5 : 89 
Harmonic mean= 11.69 
Arithmetic mean = 46.80 
Geometric mean = 28.61

Explanation:

  1. Getting input array  from a user
  2. Then, applying formula on the given set of elements , that would output average, geometric and harmonic mean

]]>
https://programmerbay.com/c-program-that-calculates-the-average-geometric-and-harmonic-mean/feed/ 0
C Program for Translation of a Triangle https://programmerbay.com/c-program-for-translation-of-a-triangle/ https://programmerbay.com/c-program-for-translation-of-a-triangle/#respond Fri, 19 Aug 2022 14:44:00 +0000 https://www.programmerbay.com/?p=1843 triangle

A Triangle is made up of three vertices or points in which three line segments are joined together.

Here is the snippet.

Program for Translation of a Triangle in C

Program:

/* translation */
#include<conio.h>
#include<graphics.h>
#include<stdio.h>
void main()
{
int gd=DETECT,gm;
int x,y,x1,y1,x2,y2,tx,ty;
clrscr();
initgraph(&gd,&gm,"C:\\TURBOC3\\BGI");
printf("\n Please enter first coordinate of the triangle= ");
scanf("%d %d", &x,&y);
printf("\n Enter second coordinate of the trinagle = ");
scanf("%d %d",&x1,&y1);
printf("\n Enter third coordinate of the triangle = ");
scanf("%d %d",&x2,&y2);
printf("\n\t\t********** TRIANGLE before & after translation ***********");
line(x,y,x1,y1);
line(x1,y1,x2,y2);
line(x2,y2,x,y);
printf("\n Now enter the translation vector = ");
scanf("%d %d",&tx,&ty);

setcolor(RED);
line(x+tx,y+ty,x1+tx,y1+ty);
line(x1+tx,y1+ty,x2+tx,y2+ty);
line(x2+tx,y2+ty,x+tx,y+ty);
getch();
closegraph();
}

 

 

Output:

triangle translation

]]>
https://programmerbay.com/c-program-for-translation-of-a-triangle/feed/ 0
C Program for 2D Translation https://programmerbay.com/c-program-for-2d-translation/ https://programmerbay.com/c-program-for-2d-translation/#respond Fri, 19 Aug 2022 09:55:19 +0000 https://www.programmerbay.com/?p=1837 2D Translation can be defined as a way of shifting an object from one point to another in a straight path. Here is the C program for demonstrating 2D translation

Must Read: What is 2D Translation?

Program to show the translation of a line

Program:

#include<conio.h>
#include<graphics.h>
#include<stdio.h>
void main()
{
int gd=DETECT,gm;
// declaring two array
// Translation vector already initialized
int l[2][2],v[2]={10,15},i=0,j;
clrscr();
initgraph(&gd,&gm,"C:\\TURBOC3\\BGI");
printf("Enter the initial and final coordinates of a line ");

// Getting input from user, having 2D array where 1st row represents initial point
// And Second row represents final coordinate
while(i<2)
{
printf("x%d and y%d = ",i,i);
j=0;
scanf("%d",&l[i][j]);
scanf("%d",&l[i][j+1]);
i++;
}
// Line before translation
line(l[0][0],l[0][1],l[1][0],l[1][1]);
setcolor(BLUE);
// Line after translation
line(l[0][0]+v[0],l[0][1]+v[1],l[1][0]+v[0],l[1][1]+v[1]); // Adding Translation vector in it to change the position
getch();
closegraph();
}

 

Output:

translation using array

 

 

Related post with Example:

2D Translation: Positioning of an Object

]]>
https://programmerbay.com/c-program-for-2d-translation/feed/ 0
C Program to Draw Chess Board https://programmerbay.com/program-to-draw-a-chess-board-in-c/ https://programmerbay.com/program-to-draw-a-chess-board-in-c/#respond Fri, 12 Aug 2022 07:47:11 +0000 https://www.programmerbay.com/?p=2108 C supports a special header file named graphics.h that provides various functions through which one can draw different shapes such as line, circle, triangle, and more. And with the combination of these functions, we can create objects like a hut, joker, cap, and more.

The program draws a Chess board with the help of graphic libraries. It uses rectangle(), setcolor(), floodfill and setfillstyle() functions to draw this object.

C program to Draw Chess Board

 Program:

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main(){
int gr=DETECT,gm;
int row,col,x=50,y=50,flag=0;
initgraph(&gr,&gm,"C:\\TURBOC3\\BGI");
printf("\t*********** CHESS BOARD **************\n");
for(row=0;row<8;row++)
{

for(col=1;col<=8;col++){
if(flag==0){
setcolor(YELLOW);
setfillstyle(SOLID_FILL,BLACK);
rectangle(x,y,x+50,y+50);
floodfill(x+1,y+1,YELLOW);
flag=1;
}
else
{
setcolor(YELLOW);
setfillstyle(SOLID_FILL,WHITE);
rectangle(x,y,x+50,y+50);
floodfill(x+1,y+1,YELLOW);
flag=0;
}
x=x+50;
}
if(flag==0)
flag=1;
else
flag=0;
delay(100);
x=50;
y=50+y;
}
getch();
closegraph();
}

 

Output:

chessboard

]]>
https://programmerbay.com/program-to-draw-a-chess-board-in-c/feed/ 0
C Program to Show a Man Walking in Rain https://programmerbay.com/program-for-man-walking-in-rain/ https://programmerbay.com/program-for-man-walking-in-rain/#respond Thu, 11 Aug 2022 17:21:02 +0000 https://www.programmerbay.com/?p=2101 Using translation transformation,  an illusion of moving object can be achieved.  Here’s the simple code to show a man is walking in the rain.

C program for a man walking in the rain

Program:

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<stdlib.h>
void main(){
int gr=DETECT,gm;
int i,x,y,j;
initgraph(&gr,&gm,"C:\\TURBOC3\\BGI");

// man
for(j=1;j<600;j=j+5)
{
line(0,400,800,400);
circle(30+j,280,20); //head
line(30+j,300,30+j,350); //body
line(30+j,330,70+j,330); //hand
if(j%2==0){
line(30+j,350,25+j,400); //left leg
line(30+j,350,10+j,400); // right
}
else{
line(30+j,350,35+j,400); //transition
delay(20);
}
//umbrela
line(70+j,250,70+j,330);
pieslice(70+j,250,180,0,80);
// rain
for(i=0;i<300;i++)
{
x=random(800);
y=random(800);
outtextxy(x,y,"/");
}
delay(170);
cleardevice();
}
getch();
closegraph();
}

 

Output

]]>
https://programmerbay.com/program-for-man-walking-in-rain/feed/ 0
C Program to Find the Greatest of Three Numbers https://programmerbay.com/c-program-to-find-the-greatest-of-three-numbers/ https://programmerbay.com/c-program-to-find-the-greatest-of-three-numbers/#respond Wed, 10 Aug 2022 06:44:13 +0000 https://www.programmerbay.com/?p=2368 The program determines greatest among three numbers based on the conditional statements. It simply uses greater than (>) and smaller than (<)  comparison operators to find greatest number. There are two ways to achieve this functionality. First one is by using if-else statement and other is using ternary operator.

Approach To Find Greatest of Three :

It is required to find the largest numbers among three numbers. The solution is quite easy and simple :

  • Get three numbers from the user as input
  • Check the first number whether it is greater than the second one or not
  • Similarly, check again the same number with the third one
  • If a number is greater than the rest,
  • The number would be qualified as greatest among all

C program to find greatest among three

C program to find the greatest of three numbers using If-else statement

In case of if-else statement, we have used nested if-else condition to find greatest of three numbers in the below C program.

Program:

#include <stdio.h>

int main ()
{
  int num, num1, num2;
  printf ("Please enter first number : ");
  scanf ("%d", &num);

  printf ("Please enter second number : ");
  scanf ("%d", &num1);

  printf ("Please enter third number : ");
  scanf ("%d", &num2);

  printf ("\n******* Finding Greatest ******* \n");
  if (num > num1)
    {
      if (num > num2)
  {
    printf ("\n%d is Greatest \n", num);
  }
      else
  {
    printf ("\n%d is Greatest \n", num2);
  }
    }
  else if (num1 > num2)
    {
      printf ("\n%d is Greatest \n", num1);
    }
  else
    {
      printf ("\n%d is Greatest \n", num2);
    }
  return 0;
}

Output:

Please enter first number : 4                                                                                            Please enter second number : 76                                                                                          Please enter third number : 43                                                                                                                                                                                                                    ******* Finding Greatest *******                                                                                                                                                                                                                 
 76 is Greatest

Explanation:

1) Taking three variables named num,num1,num2 assigned with 4,20,5 values respectively
2) if ‘num’ is greater than num1 and num2 then it would be printed as the largest number
3) if ‘num’ is smaller than num1, ‘else-if’ block would be executed that check if num1 is greater than ‘num’ or not

4) if it returns false, in that case, ”else’ block would be executed and “num2” become the greatest

C program to find the greatest of three numbers using ternary operator

program :

#include <stdio.h>

int main ()
{
  int num, num1, num2;
  printf ("Please enter first number : ");
  scanf ("%d", &num);

  printf ("Please enter second number : ");
  scanf ("%d", &num1);

  printf ("Please enter third number : ");
  scanf ("%d", &num2);

  printf ("\n******* Finding Greatest ******* \n");
  (num > num1) ? ( (num > num2)? printf ("\n%d is Greatest \n", num): printf ("\n%d is Greatest \n", num2) ) :   ( (num1 > num2) ? printf ("\n%d is Greatest \n", num1): printf ("\n%d is Greatest \n", num2));

  return 0;
}

Output :

Please enter first number : 4                                                                                            Please enter second number : 87                                                                                          Please enter third number : 109                                                                                                                                                                                                                   ******* Finding Greatest *******                                                                                                                                                                                                      
            109 is Greatest

In the above example, we used ternary operator with same approach to find greatest number.

]]>
https://programmerbay.com/c-program-to-find-the-greatest-of-three-numbers/feed/ 0
Program to Find Diameter, Circumference and Area of Circle in C https://programmerbay.com/c-program-to-find-area-circumference-of-a-circle/ https://programmerbay.com/c-program-to-find-area-circumference-of-a-circle/#respond Fri, 05 Aug 2022 07:19:51 +0000 https://programmerbay.com/?p=5360 The program calculates diameter, circumference, and area of a circle by simply using formula. The explanation is given below.

A circle can be defined as a collection of points that are equidistant from each other. One can calculate its area and circumference using radius or diameter.

Formula to Calculate Diameter, Circumference, and Area of a circle 

Circle

Diameter = Line that goes through the center and touches boundary as initial and end points.

Radius = Diameter/2

Area of Circle = π * r 2

Circumference of Circle = 2*π *r

 

Example 1. Program to Find Diameter, Circumference and Area of Circle in C

In the below code, we have declared a macro named pi and used it for circumference and area calculation.

Program:

#include<stdio.h>
#define pi 3.14159
int main()
{
float radius, diameter, area, crcmfrnce;
printf("Please enter the radius of the Circle = ");
scanf("%f",&radius);
diameter = 2 * radius;
crcmfrnce = 2*pi*radius;
area  = pi*radius*radius;
printf("\n\t Diameter of the circle = %.1fm \n\t Circumference of the circle = %.2fm \n\t  Area of the circle = %.2fsq.m\n",diameter,crcmfrnce,area);
return 0;
}

Output:

Please enter the radius of the Circle = 3

         Diameter of the circle = 6.0m 
         Circumference of the circle = 18.85m 
         Area of the circle = 28.27sq.m


Explanation:

  1. Getting input as a radius  from a user
  2. Then, applying formula π r 2 for area and  2π r for circumference on it , that would give area and circumference
  3. Lastly, printing the output on to the screen

Example 2. Program to Find Diameter, Circumference and Area of Circle in C  Using Math.h library.

Math.h header file consists various predefined mathematical functions. In this case, we have used its M_PI constant and pow() method to calculate circumference and area of a circle.

Program: 

#include<stdio.h>
#include<math.h>
int main()
{
float radius, diameter, area, crcmfrnce;
printf("Please enter the radius of the Circle = ");
scanf("%f",&radius);
diameter = 2 * radius;
crcmfrnce = 2*M_PI*radius;
area  = M_PI * pow(radius,2);
printf("\n\t Diameter of the circle = %.1fm \n\t Circumference of the circle = %.2fm \n\t  Area of the circle = %.2fsq.m\n",diameter,crcmfrnce,area);
return 0;
}

Output: 

Please enter the radius of the Circle = 2

   Diameter of the circle = 4.0m 
   Circumference of the circle = 12.57m 
    Area of the circle = 12.57sq.m

 

]]>
https://programmerbay.com/c-program-to-find-area-circumference-of-a-circle/feed/ 0