C Program Examples
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; }
Output of above program: "Hello World" Example 2 - c program to take input from user using scanf
#include <stdio.h> main() { int number; printf("Enter an integer\n"); scanf("%d",&number); printf("Integer entered by you is %d\n", number); 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 printf("For comparison use == as = is the assignment operator.\n"); return 0; }
printf("Number of command line arguments passed: %d\n", argc); for ( c = 0 ; c < argc ; c++) printf("%d. Command line argument passed is %s\n", c+1, argv[c]); 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() { // Single line comment in c source code printf("Writing comments is very useful.\n"); /* * Multiline comment syntax * Comments help us to understand code later easily. * Will you write comments while developing programs ? */ printf("Good luck c programmer.\n"); 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>
main() { int c; /* for loop */ for ( c = 1 ; c <= 10 ; c++ ) printf("%d\n", c); return 0; }