Introduction to C Programming

C is a programming language, developed in “AT&T’s Bell Laboratories” to develop unix operating systems.It Was Written by Dennis Ritche.

 Do you know why it was named as “C”?. As many of this feature is derived from “B” Language, it was named as “C”. BCPL and CPL are the earlier ancestors of “B” Language.

We don’t like to give you more introduction and history Since it won’t be useful to improve your skills in C Programming. At the same time, it will be interesting if you know the real-time use of C Programming Language.

1.C Language is used for creating system tool that acts as a major part of Operating systems.
2.Used in Embedding Softwares.
3.Unix is Completely Developed in C Language.

EXECUTION OF C PROGRAMMING:

Before start learning Programming Language, We need to know some important topics, which should be more helpful to understand

1.Coding :

First step in Programming , we need to choose editors to code our logic.Turbo C is the simple and mostly used editor to learn C Language

2.Compiling:

Second step in execution , before to run the code , we must compile it , it converts our written code into Machine Instruction.Compiler checks for errors, if your code is error free, then it is ready to run.

3.Compile Time Error Correction:

During Compile time, Compiler compile our code , and if it finds any error or issues , It will alert the user for the error occurred at compile time.

4.Linking:

This step Links our Libraries with programs, here also editor checks for error. This error will be called as Linker error

5.Run:
After Finishing all the above step, we can see our output by executing our program. There are chances for getting error in run time also, So again we need to review the code.

Note: This tutorial is only for beginners not for an expert.

KeyWords & Tokens In C Programming

Tokens:

In C programming punctuation, KeyWords, Characters and etc are called Tokens.

 

3e868 tokens bmp 300x147

KeyWords:

Keywords are words that can not be used as a variable name, keywords meaning is already defined by the compiler.

example:

Int, float are some example for keywords,  we can not use these keywords as a variable name. Hope that you may ask what is Variable? here we have a tutorial for Variables.

There are 32 keywords in C Programming Language,Here is the list of 32 keywords

auto break case const
continue default do double
enum extern float for
goto if int long
register return short signed
sizeof static struct switch
typedef union unsigned void
volatile char else while

These KeyWords are also called as Reserved words,if you use these keywords as variable name, compiler will throw error.

DataTypes:

  In C Programming Language DataType refers to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.

example:

int a;

a is variable.

Here int is a Datatype, which tells the compiler that how much space needs for this integer variable.

Type Storage size Range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 bytes  -2,147,483,648 to 2,147,483,647
short 2 bytes -32,768 to 32,767
float 4bytes +/- 3.4e +/- 3

 

Variables & Constants

Let’s take a simple program to explain variables & constants

#include

int main()
{
printf("The number is 5 \n");

return 0;
}

This program is not such a complex one, this is same as Hello World. But the difference is, it prints as ‘The number is 5’.

Now we need to print 10 instead of 5, not at compile time, it should be at run time. And we should not edit the code again and again to get the desired output.
Hope that now you understand the requirement, just think of it. Are you ready? can we achieve this? Yes sure. So, For that we are introducing an important concept in C Programming, Can you guess that? yep, that is Variable

Variable is a container which stores the data,Variable may have different DATA TYPES (int,char, float like that).

syntax:

int numberToPrint;

numberToPrint is the name of a variable
int is DATA TYPE of a variable
This is an integer variable as its data type is int, And as it is int variable,  we can store integer values only.

Note : VARIABLE IS A NAME GIVEN TO THE MEMORY LOCATION WHERE THE ACTUAL DATA IS STORED.

Lets come back to our task, we need to change the value getting printed dynamically. We need to give input (a number that needs to be printed).
Here we add our variable into our program

#include
int main()
{
int numberToPrint;              /// Variable Declaration
printf("enter number to print \n ");
scanf("%d",&numberToPrint);           /// getting input value at run time
printf("The number is %d \n,numberToPrint");      // prints output
return 0;
}

From the above explanation , you can understand the usage of variable easily. Then Lets see how Variable works.

"VARIABLE IS A NAME GIVEN TO THE MEMORY LOCATION WHERE THE ACTUAL DATA IS STORED".

Can you understand the meaning of that Line above?
Lets say,
int a;
Now, we have declared a variable.
Compiler checks the data type of that variable and allocates memory depending on that data type.
Initially no value is assigned to that variable , so the garbage will persist in that memory location.
Now, we are assigning a value to that variable like below

a = 10;

instead of garbage value, 10 is stored in that memory location.
Again, i am going to change the value of that variable like below,

a = 5;

Now, 10 is replaced by 5, but the memory address is same.Hope you understand the definition of variable:
To print the address of a variable , you can use like this ‘&var_name’.

Now lets back to our task.Now you can understand the program and you can enter your desired number at run time using scanf() function. It gets input and assign it in address of that variable.
printf() function prints the number what we have entered.

Memory Space will be created as datatype says,

int           4 bytes
short         2 bytes
char          1 byte
float         4 bytes
double        8 bytes
bool          1 byte

lets consider variable declaration as below

int numberToPrint  = 100;
Since its data type is int , it allocates 2 bytes in memory ,

Note:

  1. Variable name must begin with letter or underscore.
  2. Variables are case-sensitive
  3. They can be constructed with digits, letters.
  4. No special symbols are allowed other than underscore.

Lvalues and Rvalues in C:

There are two kinds of expressions in C:
lvalue : An expression that is a lvalue may appear as either the left-hand or right-hand side of an assignment.

rvalue : An expression that is a rvalue may appear on the right- but not left-hand side of an assignment.

Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side.
int var = 100;

Constants:

The constant refer to a fixed value and the program can not alter it during its execution. These are fixed values and called as literals.
The constants are treated just like regular variables except that their values cannot be modified after their declaration.

Types of constants:

  • integer constants.
  • float constants.
  • character constants.
  • string constants.

Declaration:

const int a = 10;

In the above line, value of ‘a’ can not be changed during run time, since it is readonly.

 

DataTypes in C

Variables are basic and important concept before Datatypes, if you have not been gone through variables, please click here to know about variables in C. We know that variable should be declared before using it. Data types are the keywords, which are used for assigning a type to the variable.

The size of variable and constant are identified by data type.Data types are classified into two types.

Fundamental data type:

  • integer data type.
  • floating data type.
  • character data type.

Derived Data type:

  • Arrays
  • Structures
  • Enumeration.
  • Pointers.

syntax:
data_type variable_name;

example:
int a;
here, int is a  data type
a is the variable name

Integer data type:

“int” is a keyword used to refer integer data type.it allows a variable to store numeric values. int allocates 2 bytes of memory for that variable.

int a = 1;

It can store a value from -32768 to 32767.

long int data type allocates 4 bytes in memory,it can store value from -2,147,483,648 to +2,147,483,647.

Floating data type:

floating data type consists of a float and double.

“float” is a key word used to refer float data type. It allows a variable to store decimal numbers. Float allocates 4 bytes of memory for that variable.

float a = 1.5;

the range for the double data type is from 1E-37 to 1E+37.

Character data type:

“char” keyword is used to refer character data type, it allows to store only one character, Default storage size for character data type is 1 byte.

char variable_name= ‘A’;

note:sizeof() used to find the memory space for all data types.

Qualifiers:

Qualifiers alter the meaning of fundamental data types.There are three Qualifiers in C

sign Qualifiers:

Whether a variable can hold only positive values or both, can be specified by sign qualifiers.

signed‘ and ‘unsigned‘ are sign QualThe default is signed Qualifier.

example: unsigned int a;

here variable a can store only positive numbers.

size Qualifier:

These keywords are to alter the size of fundamental keywords. ‘long’ and ‘short’ are two keywords.

The size of ‘int’ variable is 2 bytes, if we want to store large values, ‘we will use ‘long’ (like long int a )

short can be used for the smaller size of a variable.

Constant Qualifiers:

if a variable has const as a prefix , then the value of that variable can not be changed.

const int a = 10;

Enumerator data type:

Enumeration data type consists of named integer constants as a list.
It starts with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in the list.
Enum syntax in C:
enum identifier {

enumerator-list

};

example:
enum fruits
{
apple,
orange,
Mango
};
apple = 0,orange =1,Mango =2.

Next chapters will give you more concepts about decision-making, where we can apply data types in examples

Operators

Operators are a symbol that operates on a value or variable,

for example, let’s have a look at this expression 3 + 2 is equal to 5, here + is an operator that operates on 3 and 2, So + is an operator to perform addition

and 3, 2 are called as operands.C Language supports the following type of operators.

  • Arithmetic operators
  • Logical (&) Relational operators
  • Bitwise operators
  • Assignment operators
  • Special operators
  • Conditional operator

Arithmetic Operators:

C Programming Language supports following arithmetic operators

Operators Description
+ Performs addition or unary plus
Subtraction or unary minus
* Multiplication
/ Division (quotient after division)
% Modulo Division (Remainder After Division)
++ increments operands by 1 (Increment operator)
Decrements operands  by 1 (Decrement Operator)

Let’s see a sample program

#include int main()
{
int a=3,b=4,c;

     c=a+b;                        /******** + operator******** adds a and b /

     printf("a+b=%d\n",c);

     c=a-b;                         /******** - operator ******** subtracts a and b/

     printf("a-b=%d\n",c);

     c=a*b;                         /////////////// * operator ////////////// multiplies a and b/

     printf("a*b=%d\n",c);

     c=a/b;                         /******* / operator******** Divides a and b/

     printf("a/b=%d\n",c);

    c=a%b;                        /******* % operator ****** gives remainder after division/

   printf("Remainder when a divided by b=%d\n",c); 

    a++;                        /******** ++ operator ****** increments a by 1/

    printf("after increment a value=%d\n",a);

     b--;                         /******** -- operator ******** Decrements by 1/

    printf("after increment b value=%d\n",b);

   return 0;

}

 Output

a+b=7
a-b=-1
a*b=12
a/b=0
Remainder when a divided by b=3
after increment a value = 4
after decrement b value = 3

there is a usage difference between increment (++) operator and  (–) Decrement operator and these operators can be used as prefix or postfix, like below
let a is variable
a++;
++a;
a–;
–a;
When ++ is used as a refix, ++a will increment the value of a by 1 and then return it, if ++ is used as postfix(a++), operator will return the value of operand first and then increment it.

Logical (&) Relational operators:

Relational operators always checks relationship between two operands, it always gives binary result like 1 or 0 always,

example : a > b , where >  is relational operator , if a is greater than b , it gives 1 else 0.

Logical operators are used to combine expressions containing relation operators.

example : (a > b) && (a > c),where && is Logical operator.

C supports following Relational and logical operators

Operator Meaning Example
>  greater than  1 > 2 return false
< Less than  1 < 2 return true
>= Greater than or equal to  1>= 2 return false
<= Less than or equal to  1 <= 2 return false
== equal to  2 == 2 return true
!= not equal to  1 != 2 return true
&& Logical And  if a=2 b = 1 (a > b) &&(a< 10) return true
both expression a > b and a < 10 should be true,
|| Logical Or if a=2 b = 1 (a > b)  || (a> 10) return true.
either expression should be true,Since  a>b is true
above expression gives result true.
! Logical not if a =10 , !(a==10) return false.

Conditional operator:

Conditional operator consists two symbol ? and :  and it takes three operands

example: Let a = 10;

c = (a>5) ? 15 : 5

if a is greater than 5, it results 15  else 5, in our example a = 10, c = 15.

Bitwise Operator:

Bitwise operator works in bit level programming, it works on each bit.

Operators Meaning
& Bitwise AND
! Bitwise OR
~ Complement
^ Exclusive OR
<< Left shift
>> Right Shift

Special Characters:

Comma operator:

Comma operators are used to link related expressions together, example int a, b;

The size of Operator:

It is a unary operator which is used finding the size of a data type, constant, arrays, structure etc.

For example:

sizeof(int) gives size of an integer data type as 4 bytes.

Assignment Operator:

Assignment operators have two values L value and R value, it is used to assign the value to variable,most common assignment operator is =

example:

a = 10     10 is assigned to a

a = b    value of b assigned to a

Operator Example Meaning
+ a=b a=b
+= a+=b a= a+b
*= a*=b a=a*b
-= a-=b a=a-b
/= a/=b a=a/b

Decision Making

Decision making in a programming language is an important concept Since sometimes we want to execute part of the statements among many statements when certain condition meets.

C programming language supports 4 types of Decision making Control statements

  1. if statement
  2. if else statement
  3. nested if else statement
  4. Switch statement

Another concept is there in C Programming that is Loop which is also related to decision-making, we will have a look at in next chapter.

if Statement:

In this type, if the condition is true , then the respective block of the code will be executed.

syntax:

if(condition)

{

statements

}

if non zero number is placed inside if condition means , then the statement gets satisfied and returns”TRUE”

8993d if2bstatement bmp 213x300

void  main()
{
int a=40,b=20;
if (a > b)
{
printf("a is greater than b");
}
}

output:

a is greater than b

if else Statement:

Group of statements will be executed , if condition is satisfied . If condition is not satisfied, then else part of that conditions will be executed.

syntax:

if(condition)

{

    statements to be executed if condition is true.

}

else

{

    statements to be executed, if condition is false

}

8cff4 if else2bstatement bmp 275x300

program:

void  main()
{
int a=40,b=20;
if (a < b)
{
printf("a is less than b");
}

else

{

    printf("a is greater than or equal to b");

}

}

output:

a is greater than or equal to b.

nested if else statement:

if… else can be used in nested forms when serious of decisions are involved.

syntax:

if (condition)
statements to be executed if test expression is true;
else if(condition)
statements to be executed if test expressions 1 is true;
else if (condition)
. . .
else
statements to be executed if all test expressions are false;

program:

void  main()
{
int a=40,b=20;
if (a == b)
{
printf("a is equal to b");
}

else if( a > b)

{

    printf("a is greater than  b");

}

else

{

printf("a is less than b");

}

}

output:

a is greater than  b

switch.. case statement:

switch .. case is similar to nested if else statement, but the problem is , when we use multiple nested if else, it will increase the complexity of program.

syntax:

switch (expression)
{
case constant1:
statements  to be executed if expression equals to constant1;
break;
case constant2:
statements  to be executed if expression equals to constant3;
break;
. . .
default:
statements  to be executed if expression doesn't match to any cases;
}

expression may be a number or a character .

switch case checks the  value of expression or variable against the list of cases .When the match is found,  block of the code is executed associated with that case.

Break statement takes the control out from the case.

Break statement is optional. If we forget to add break statement in a case, then the following cases also will be executed.

program:

# include
int main()
{
char operator;
int num1 = 10,num2 = 10;
operator='+';
switch(operator)
{
case '+':
printf("num1+num2=%d",num1+num2);
break;
case '-':
printf("num1-num2=%d",num1-num2);
break;
case '*':
printf("num1*num2=%d",num1*num2);
break;
case '/':
printf("num2/num1=%d",num1/num2);
break;
default:
/* if operator is other than +, -, * or /, error message is shown */
printf(Error! operator is not correct");
break;
}
return 0;
}

output:

num1+num2=20;

goto statement:

goto statements is used to transfer the normal flow of a program to the specified label in the program.

Syntax:
{
…….
go to label;
…….
…….
Label:
Statements;
}

Loops

In decision making, we are executing a block of code only one time when certain condition meets. We might come across a situation to execute a block of code n number of times. Loop control statements in C are used to perform looping operations until the given condition is true. Control comes out from the loop statements when the condition becomes false.

There are 3 types of loop control statements in C language. They are,

  1. for
  2. while
  3. do-while
b82c1 loop bmp 253x300

for loop:

Execute a sequence of statements multiple times and abbreviate the code that manages the loop variable.It is entry controlled loop.

syntax:

for(initialization;condition;increment)

{

………. body……….

}

program:

#include
int main ()
{
for(int i = 0 ; i < 5 ;i++ )
{
printf(“i = %d\n”,i);
}
return 0;
}

output:

i=0

i=1

i=2

i=3

i=4

While loop

Repeats a statement or group of statements un till a given condition is true. It tests the condition before executing the loop body.

syntax:

initialization;

while(condition)

{

…….

increment;

}

program:

#include
int main ()
{

int i =0;
while(i < 5)
{
printf(“i = %d\n”,i);

i++;
}
return 0;
}

output:

i=0

i=1

i=2

i=3

i=4

do…while statement:

Like a while statement, except that it tests the condition at the end of the loop body.It is exit controlled loop.Condition will be executed at least once,since condition checks at last.

syntax:

initialization;

do{

…..

increment;

}while(condition);

Arrays

In this tutorial, we are going to talk about arrays. C programming language provides a special data structure called the array. An array lets you declare and work with a collection of values of the same data type.
Let’s say you want to declare 5 integers and assume that we don’t have array concepts. We will write like below.

int a,b,c,d,e;

now you want to declare 1000 variables of same data type.Are you ready to type a thousand variables like above?  With the help of array, we can easily declare our 5 variable like this.

int a[5];

Array classified into two categories.

  1. Single Dimensional Array
  2. Multi-Dimensional Array.

Declaration:

syntax:

data_type variable_name[array_size];

This type of array is called as single dimensional array.

Array size should be an integer and greater than zero.

Initializing Arrays:

You can declare an array one by one or in a statement.

int age[3];

age[0] = 10;

age[1] = 20;

age[2] = 30;

(OR)

int age[3] = {10,20,30};  // the number of values inside the {,} can not be greater than array size declared with in [].

(OR)

int age[] = {10,20,30};

program:

#include
int main ()
{
int age[ 5 ]; /* age is an array of 5 integers */
int i,j;
/* initialize age */
for ( i = 0; i < 5; i++ )
{
age[ i ] = i + 10;

}
/* output each array element's value */
for (j = 0; j < 5; j++ )
{
printf("age[%d] = %d\n", j, age[j] );
}
return 0;
}

output:

age[0] = 10
age[1] = 11
age[2] = 12
age[3] = 13
age[4] = 14

Multi-Dimensional Array:

C programming allows multi-Dimensional array,

syntax:

data_type variable_name[size1][size2]……[size_n];

To understand easily lets take Two Dimensional array. It can be illustrated in matrix like this image

7d7d2 two array bmp 300x150

Declaration:

int a[2][3];  // 2 rows 3 columns

Initialization:

int a[2][3] = { 0,1,2  /* row 1*/

3,4,5} /* row 2*/

program:

#include
int main()
{
int a[2][2], i , j;
for (i = 0; i < 2; i++)
{
for ( j = 0; j < 2; j++)
{
a[i][j] = i+j;
printf("a[%d][%d] = %d \n", i, j, a[i][j]);
}
}
return 0;
}

output:

a[0][0] = 0;

a[0][1] = 1;

a[1][0] = 1;

a[1][1] = 2;

Passing Arrays as Function Arguments:

We can pass arrays as arguments to a function as follows.

void myFunction(int param[])
{
.
.
}

program:

#include

/* function declaration */
int getTotal(int arr[], int size);

int main ()
{
/* an int array with 5 elements */
int values[5] = {10, 2, 3, 5, 50};
int  sum;

/* pass pointer to the array as an argument */
sum = getTotal(values,5 ) ;

/* output the returned value */
printf( "Total value is: %f ", sum );

return 0;
}

int  getTotal(int arr[], int size)
{
int    i;
int  sum;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
return sum;
}

 

Functions – C Programming

A function is a group of statements that together performs a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.

You can divide up your code into separate functions for better understanding and readability. Dividing up your code among different functions is up to you, but logically the division usually is to each function will perform a specific task.
A function declaration tells the compiler about a function’s name, return type, and para meters. A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. Few example for built-in functions are strcat(), memcpy(), function strcat() is to concatenated two strings, function memcpy() is to copy one memory location to another location and many more functions.

syntax:
return_type function_name( arguments )
{
body of the function
}

Parts of a function:

Return Type:

A function may return a value or may not. The return_type is the data type of the value that function returns. Some functions perform the desired operations without returning a value. In this case, the return_type should be void.

Function Name:

This is the actual name of the function. The function name and the parameter list together constitute the function signature.

Arguments:
An Argument is like a placeholder. When a function is invoked, you pass a value as the Argument. This value is referred as actual parameter or argument. The Argument list refers to the type, order, and number of the parameters a function has.
Arguments are optional; that is, a function may contain parameters or not.

Function Body:

The function body contains a collection of statements that describes what the function does.
Example:
Hope you understand , now lets write a simple function for sum of two numbers. This function has two numbers as arguments ,and result should be returned,

int sumOfTwoNumbers(int num1,int num2)
{
int sum = num1+num2;
return sum;                  // return value.
}

Function Declaration:

A function declaration tells the compiler about a function name and how to invoke the function name.

syntax:

return_type function_name( arguments );

example:
int sumOfTwoNumbers(int num1,int num2);

Function calling:

We know what is function, and how to declare it , now we need to know , how can we use this function to achieve our desired task.

To invoke a function, you will have to call the function to perform the defined task . When a program calls a function, program control is transferred to the called function. A called function performs a defined task un till return statement is executed or its function-ending closing brace is reached, and it returns the program control back to the main program.

To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you have to store the returned value.

example :

To invoke our sum of two number function

int sum = sumOfTwoNumbers(10,20);

So, result 30 is stored in sum as returned value.

Program:

void main()

{

int num1 = 10,num2=20;

int sum = sumOfTwoNumbers(num1,num2);

printf("sum = %d",sum);

}

int sumOfTwoNumbers(int num1,int num2)
{
int sum = num1+num2;
return sum;                  // return value.
}

Function arguments:

Arguments  can behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.

While calling a function, there are two ways to pass the arguments to a function:

  1. Call by value
  2. Call by reference

Call by value:


This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
Program:
void swap(int x, int y)
{
int z;
z = x;
x = y;
y = z;
printf("Swapped values are a = %d and b = %d", x, y);
}

void main()
{
int a = 1, b = 2;
printf("Original values are a = %d and b = %d", a, b);
swap(a, b);
printf("The values after swap are a = %d and b = %d", a, b);
}

Output:
Original Values are a = 1 and b = 2
Swapped values are a = 2 and b = 1
The values after swap are a = 1 and b = 2

Call by Reference:

This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
program:
void swap(int *x, int *y)
{
int z;
z = *x;
*x = *y;
*y = z;
printf("Swapped values are a = %d and b = %d", *x, *y);
}
void main()
{
int a = 1, b = 2;
printf("Original values are a = %d and b = %d", a, b);
swap(&a, &b);
printf("The values after swap are a = %d and b = %d", a, b);
}

Output:
Original Values are a = 1 and b = 2
Swapped values are a = 2 and b = 1
The values after swap are a = 2 and b = 1

Structure

A structure is a derived data type in C. It is used to group different data types under the same name together.

syntax:

struct structure_name{

data_type1 variable_name1;

data_type2 variable_name2;

…….

…..

};

Are you confused? you could create a structure called the customer, which contains a customer name, and customer contact number.

struct customer
{
char *name;
int number;
};

Note the semicolon; behind the last curly bracket.

you have created a new data type now called the customer. To access this data type, you have to create a variable of the type customer.

struct customer customer1;

To access the members of a structure, you must use dot(“.”) operator like this,

customer1.name = “john”;

customer1.number = 123456789;

program:

#include
struct customer
{
char *name;
int number;
};

int main()
{
struct customer customer1;
customer1.name = "John";
customer1.number = 123456789;
printf("Name: %s\n", customer1.name);
printf("Telephone number: %d\n", customer1.number);
return 0;
}

output:

Name: John

Telephone Number: 123456789

Pointers to Structs:

Sometimes it is useful to assign a pointer to a structure. Declaring pointers to structures is basically the same as declaring a normal pointer.
struct customer *customer1;
To reference, you can use the infix operator: ->.
printf(“%s\n”, customer1->name)