Introduction
The purpose of this post is to introduce elementary idea of C - Programming language to the readers. This post requires no earlier experience of any programming language.
The post has been written keeping the audiences in mind who need to know what C programming language is and what are the different features available. It will help the elementary school students who need to prepare some type of reports for their annual/half-yearly report on a technical topic like this one.
This post will try to highlight the basic features of C. The post is not trying to teach the basic working knowledge of this programming language.
1. Overview of C:
C is a powerful structured programming language developed by Dennis Ritchie. It supports functions that enable easy maintainability of code, by breaking a large file
into smaller modules.
2. Program structure:
A sample C Program template can be as simple as below. The famous “Hello World”
is the famous program among the people interested to learn this language.
#include<stdio.h>
int
main()
{
--other statements
}
3. Header files:
The files that are specified in the include section above, are called as header files. These are precompiled files that have several commonly used functions defined in these files. The functions available in the header files are used by a program by supplying few or no parameters.
Like any other file, these header files contains an the file extension ‘.h’. The main program (not the header files) created in the C language are stored in the file system as physical file. These files must have a file name with file extension as ‘.c’. So if you see a file having an extension '.c' then you should understand that is program source code written in the C.
4. Main function:
There must be at least one function in any C source code. This is called as Main() and is a mandetory requirement of C language. This is the entry point of any C program.From main() function the code execution flows as per the programmer’s chosen custom functions. There may or may not be other functions written by user in a program.
5. The First program: Famous “Hello World”
#include<stdio.h>
int
main()
{
printf(“Hello”);
return 0;
}
This program prints Hello on the screen when we execute it.
6. Running a C Program:
You need a C programming language compiler and the code editor at least. The famous ones are listed below
• If you are working on Windows Operating system, you can download either c-tool or the whole C IDE from the link below. IDE is a helpful set of tool where there is no need to shift between multiple windows during program developement.
• If you are working on Linux Operating system, then you can download or configure the operating system components to include all the required C tools from the installation source like the DVD/CD.
• Type the above program and save it. With the help of whatever editor you are using compile the program – This will generate an exe file (executable). If you are using and IDE, it will automatically compile, link and run the program for you (actually the exe created out of compilation will run and not the .c file). The you can see the o/p in a blank screen (in most of IDE) whic is called as DOS command prompt.
7. Comments in C:
C programming language provides two distinct type of code commenting options. Code commenting is required and considered as a very good habit for developers because it gives an adecaute logical information about a code section to the person who is reading for the first time.
• Single line comment
– // (double slash).
– Termination of comment is by pressing
enter key.
• Multi line comment looks like as below
/*
This is a comment to tell the reader that we can write multiline comments as in this section. More than one line commenting is possible in C just like these lines.
*/
Multiline comments helps expediting in writing comment which are more than a line.
8. Data types in C:
Any programming language needs to deal with different type of data. C may be handling some mathematical calculation based code, which demands C to work with data like integer values, decimal values. At the same time C may be handling some description about a product details. In this case it will be handling data like customer name, product name, etc. These type of description is nothing but demands C to handle data which are charachter in nature. So C must have pre-defined type of data which it can handle. It has the following type of data defination standards i.e. data types.
• Primitive data types
– int, float, double, char.
• Aggregate data types
– Arrays come under this category.
– Arrays can contain a collection of int or float or char or double type of data.
• User defined data types
– Instead of using the data types available in C, the developer can also define his/her own data type. This type of data is required when we need to store and manipulate the complex type of data, for example the student’s information.
– Structures and enum data type fall under this category.
9. Variables:
Variables are the temporary place in the computer memory which actually stores the data (any type of data as defined in the above sections). The value in variables may change during the program execution life time,
How to Declare a variable
<<Data type>> <<variable name>>;
Example: int a;
How to Define a variable
<<varname>>=<<value>>;
a=10;
How to use a variable
<<varname>>
a=a+1;//increments the value of a by 1.
We can also declare and define a variable in single shot like this.
int a=10;
10. Variable names - Rules:
• Should not be a reserved word like int, char etc.
• Should start with a letter or an underscore (_).
• Can contain letters, numbers or underscore.
• No other special characters are allowed including space.
• Variable names are case-sensitive
– A and a are different.
11. Input and Output:
• Input
– scanf(“%d”,&a);
– Gets an integer value from the user and stores it under the name “a”
• Output
– printf(“%d”,a);
– Prints the value present in variable on the screen.
Format specifier
• %d is the format specifier. This informs to the compiler that the incoming value is an integer value.
• Other data types can be specified as follows:
• %c – character
• %f – float
• %lf – double
• %s – character array (string)
• Printf and scanf are defined under the header file stdio.h
12. For loops:
For loop is used when a set of work has to be repeated multiple time. The syntax offor loop is below
for (initialisation;condition checking;increment)
{
set of statements
}
A Program which print Hello 10 times can be similar like one below.
for(I=0;I<10;I++)
{
printf(“Hello”);
}
13. While loop:
The while loop is used to perform some set of tasks which need to be repeated until the parent condition holds true. The syntax for while loop,
while(condn)
{
statements;
}
Eg:
a=10;
while(a !=
0)
{
printf(“%d”,a);
a--;
}
Output:
10987654321
14. Do While loop:
The do while is similar to the while loop except that predecided set of task is performed without checking any condition for the first time. The syntax of do whileloop is described below.
do
{
set of
statements
}while(condn);
Eg:
i=10;
do
{
printf(“%d”,i);
i--;
}while(i!=0)
Output:
10987654321
While – Entry controlled loop. Do While – Exit controlled loop.
15. Conditional statements:
If you want to do some set of task only once but again based on some condition which hold true, then use the IF statement as illustrated below.
if
(condition)
{
stmt 1; //Executes if Condition is true.
}
else
{
stmt 2; //Executes if condition is false.
}
switch(var)
{
case
1: //if var=1 this case executes.
stmt;
break;
case
2: //if var=2 this case executes.
stmt;
break;
default: //if var is something else this will
execute.
stmt;
}
16. Operators:
• Arithmetic (+,-,*,/,%).
• Relational (<,>,<=,>=,==,!=).
• Logical (&&,||,!).
• Bitwise (&,|).
• Assignment (=).
• Compound assignment (+=,*=,-=,/=,%=,&=,|=).
• Shift (right shift >>, left shift <<).
17. String functions:
• strlen(str) – To find length of string str .
• strrev(str) – Reverses the string str as rts .
• strcat(str1,str2) – Appends str2 to str1 and returns str1.
• strcpy(st1,st2) – copies the content of st2 to st1.
• strcmp(s1,s2) – Compares the two string s1 and s2.
• strcmpi(s1,s2) – Case insensitive comparison of strings.
String.h header file must be included before any of the above string functions is used in the code.
18. Numeric functions:
• pow(n,x) – evaluates n^x.
• ceil(1.3) – Returns 2
• floor(1.3) – Returns 1
• abs(num) – Returns absolute value
• log(x) - Logarithmic value
• sin(x)
• cos(x)
• tan(x)
Header file to be included math.h
19. Procedures:
• Procedure is a function whose return type is void.
• Functions will have return types int, char, double, float or even structs and arrays.
• Return type is the data type of the value that is returned to the calling point after the called function execution completes.
20. Functions and Parameters:
Functions are the small unit of a program which has some set of instruction which needs to be done as a single unit of work. Each function can do its pre-decided work based on some value which is passed to it. The values which are passed to the function called as parameters. Find below some illustrations as below.
Declaration
section
<<Returntype>>
funname(parameter list);
Definition
section
<<Returntype>>
funname(parameter list)
{
body of the
function
}
Function
Call
Funname(parameter);
Example
function
#include<stdio.h>
void
fun(int a); //declaration.
int
main()
{
fun(10); //Call.
}
void
fun(int x) //definition.
{
printf(“%d”,x);
}
21. Actual and Formal parameters:
• Actual parameters are those that are used during a function call.
• Formal parameters are those that are used in function definition and function declaration.
22. Arrays:
• Arrays fall under aggregate data type.
• Aggregate – More than 1.
• Arrays are collection of data that belong to same data type.
• Arrays are collection of homogeneous data.
• Array elements can be accessed by its position in the array called as index.
• Array index starts with zero.
• The last index in an array is num – 1 where num is the no of elements in a array.
• int a[5] is an array that stores 5 integers.
• a[0] is the first element where as a[4] is the fifth element.
• We can also have arrays with more than one dimension.
• float a[5][5] is a two-dimensional array. It can store 5x5 = 25 floating point
numbers.
• The bounds are a[0][0] to a[4][4].
23. Structures :
• Structures are user defined data types.
• It is a collection of heterogeneous data.
• It can have integer, float, double or character data in it.
• We can also have array of structures.
struct
<<structname>>
{
members;
}element;
We can access element.members;
struct
Person
{
int id;
char name[5];
}P1;
P1.id = 1;
P1.name = “vasu”;
For assigning more values we need to create an array of structure element like this
Struct
Person
{
Int id;
Char name[5];
}P[10];
P[0].id = 1;
P[0].name = “saran”;
P[1].id = 2;
P[1].name = “arya”;
And
so on till P[9].
24. Type def:
The typedef operator is used for creating alias of a data type. For example I have this statement, I can use integer in place of int i.e instead of declaring int a;, I can use integer a; This is applied for structures too.
typedef int integer;
typedef struct student
{
int id;
Char name[10];
}s;
Now I can put
s s1,s2;
Instead of struct student s1,s2; //In case typedef is missed in struct definition as below
struct student
{
int id;
char name[10];
};
25. Pointers:
• Pointer is a special variable that stores address of another variable. Addresses are
integers. Hence pointer stores integer data. Size of pointer = size of int.
• Pointer that stores address of integer variable is called as integer pointer and is declared as int *ip;
Examples
int a;
a=10; //a stores 10
int *ip ;
ip = &a; //ip stores address of a (say 1000)
ip : fetches 1000
*ip : fetches 10
* Is called as dereferencing operator
26. Call by Value:
• Calling a function with parameters passed as values
int a=10;
void fun(int a)
fun(a); {
defn;
}
Here fun(a) is a call by value. Any change done with in the function is local to it and will not be effected outside the function.
27. Call by reference:
• Calling a function by passing pointers as parameters (address of variables is passed instead of variables).
int a=1;
void fun(int *x)
fun(&a); {
defn;
}
Any change done to variable a will affect outside the function also.
28. Example program – Call by value:
#include<stdio.h>
void
main()
{
int a=10;
printf(“%d”,a); a=10
fun(a);
printf(“%d”,a); a=10
}
void fun(int x)
{
printf(“%d”,x) x=10
x++;
printf(“%d”,x); x=11
}
Explanation
29. Example Program – Call by reference:
#include<stdio.h>
void
main()
{
int a=10;
printf(“%d”,a); a=10
fun(a);
printf(“%d”,a); a=11
}
void fun(int x)
{
printf(“%d”,x) x=10
x++;
printf(“%d”,x); x=11
}
Explanation
30. Conclusion:
• Call by value: Copying value of variable in another variable. So any change made in the copy will not affect the original place.
• Call by reference: Creating link for the parameter to the original location. Since the address is same, changes to the parameter will refer to original location and the value will be over written.
.
[About the Author: Pratima Gutal is an engineering student in the IT department of College of Engineering Pandharpur, Maharashtra, India. Contact Pratima at her email-id pratima.gutal@gmail.com. If you have any concern, question or objection about this article please feel free to contact her.]