Sunday, August 7, 2011

C Programming: Writing My First Program in C. How to Write Simple Program in C.

In stead of going through different parts of C programming like Data Type, Variables, Functions, Arrays directly, I first Write a simple program and explain how it works so that you get basic concept of writing C program and compile it. I explain line by line code to make you better understand so read the explanation carefully.

1: //simple C program
2: #include<stdio.h>
3: #include<math.h>
4: 
5: int main(){
6:     float data1;
7:     float data2;
8:     float sum;
9:     float powersum;
10: 
11:     printf("Enter First Data: ");
12:     scanf("%f",&data1);
13:     printf("Enter Second Data: ");
14:     scanf("%f",&data2);
15: 
16:     sum = data1 + data2;
17:     powersum = pow(data1,2) + pow(data2,2);
18: 
19:     printf("\nThe Sum of Numbers is: %f ",sum);
20:     printf("\nThe powersum of Number is: %f",powersum);
21: 
22:     return 0;
23: }
24: 



Line 1: It is the simple comment that helps in understanding the code. It is neglected by compiler.

Line 2: <stdio.h> is a C library which includes various inputs and output operations needed while programming. printf() and scanf() are also included in stdio.h

Line 3: It is also library that has various math functions like pow().

Line 5: It is the main function. Execution of program starts from here. The int before main() indicates it returns a integer type. I will explain in detail in Functions tutorial. ISO requires int before main() function.

Line 6,7,8,9: They locates 4 memory spaces for float data type. It is same as labeling the memory. The value received by these variable stored in allocated memory locations.

Line 11: It is very important functions which will print the argument inside () to the output device. This code prints “Enter first number” to output window.

Line 12: It takes the input from user and keeps it in respective variables. It takes the Floating type data from keyboard and assign it to variable data1.

Line 16: It assigns the sum of data1 and data2 to sum variable.

Line 19, 20: The display the result of sum and powersum to output device.

Line 22: It indicates the successful termination of program. If you forgot to write it compiler automatically added it and compiles. The value other than zero indicates unsuccessful termination.  

To Compile above code Copy and Paste it to your text are of Code::Blocks or any other IDE. Then go to Build menu and click on Build and Run option. The following output window will be displayed.

simpleoutput

No comments:

Post a Comment