Cpro
Cpro
Cpro
h>
int main()
{
int n, c, k, space = 1;
printf("Enter number of rows\n");
scanf("%d", &n);
space = n - 1;
for (k = 1; k <= n; k++)
{
for (c = 1; c <= space; c++)
printf(" ");
space--;
for (c = 1; c <= 2*k-1; c++)
printf("*");
printf("\n");
}
space = 1;
for (k = 1; k <= n - 1; k++)
{
for (c = 1; c <= space; c++)
printf(" ");
space++;
for (c = 1 ; c <= 2*(n-k)-1; c++)
printf("*");
printf("\n");
}
return 0;
}
C program examples
Example 1 - C hello world program
/* A very simple c program printing a string on screen*/
#include <stdio.h>
main()
{
printf("Hello World\n");
return 0;
}
return 0;
Output:
Enter a number
5
Number entered by you is 5
Example 3 - using if else control instructions
#include <stdio.h>
main()
{
int x = 1;
if ( x == 1 )
printf("x is equal to one.\n");
else
Output:
x is equal to one.
Example 4 - loop example
#include <stdio.h>
main()
{
int value = 1;
while(value<=3)
{
printf("Value is %d\n", value);
value++;
}
return 0;
}
Output:
Value is 1
Value is 2
Value is 3
Example 5 - c program for prime number
#include <stdio.h>
main()
{
int n, c;
printf("Enter a number\n");
scanf("%d", &n);
if ( n == 2 )
printf("Prime number.\n");
else
{
for ( c = 2 ; c <= n - 1 ; c++ )
{
if ( n % c == 0 )
break;
}
if ( c != n )
printf("Not prime.\n");
else
printf("Prime number.\n");
}
return 0;
}
return 0;
Above c program prints the number and all arguments which are passed to it.
Example 7 - Array program
#include <stdio.h>
main()
{
int array[100], n, c;
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
printf("Array elements entered by you are:\n");
for ( c = 0 ; c < n ; c++ )
printf("array[%d] = %d\n", c, array[c]);
return 0;
}
main()
{
printf("Main function.\n");
my_function();
printf("Back in function main.\n");
}
return 0;
void my_function()
{
printf("Welcome to my function. Feel at home.\n");
}
printf("%f\n", variable.constant);
printf("%s\n", variable.pointer);
return 0;
}
closegraph( );
return 0;
}
getch();
return 0;
Above source code includes a header file <conio.h> and uses function getch, but this file
is Borland specific so it works in turbo c compiler but not in GCC. So the code for GCC
should be like
#include <stdio.h>
int main()
{
int c;
/* for loop */
for ( c = 1 ; c <= 10 ; c++ )
printf("%d\n", c);
return 0;
}
If using GCC then save the code in a file say numbers.c, to compile the program open
the terminal and enter command gcc numbers.c, this will compile the program and to
execute the program enter command ./a.out, do not use quotes while executing
commands.