IT WORLD

Welcome To The World Of IT

Free Training Programs

Free Training For Everyone, Everywhere And Every Time

Free Source Code

A Lot Of Source Code Is Waiting For You

Free IT Document For You !

A Lot Of IT Document Is Waiting For You !!

Source Code Game

Source Code Of Some Simple Game

Showing posts with label C++. Show all posts
Showing posts with label C++. Show all posts

Saturday, April 2, 2016

Pre-Processor in C


preprocessor in c


The preprocessor in c programming tutorial is a part of the compiler which performs basic preparatory operations (conditionally compiling code, including files, etc...) in a code before the compiler starts compiling. These transformations are lexical, meaning that the output of the preprocessor is still in form of text.
The basic compilation of every C program is passed through a Preprocessor. The Preprocessor tries to find out specific instruction throughout the whole C program which are called Preprocessor directives that it can understand. Preprocessor directives always begin with the # (hash) symbol. C++ compilers use the same C preprocessor..
The preprocessor is usually use to include another file in C language:
#include <stdio.h>

int main(void)
{
printf("Hello World!\n");
return 0;
}
The preprocessor replaces the line #include <stdio.h> with the text of the file 'stdio.h', which then defines the scanf() or printf() function among other data.
Some of the advantages of preprocessor in c programming language includes:
Easier programs development
easier to read,
easier to modify
C code more transportable between different processor architectures.
Preprocessor directives:
These preprocessor directives of c programming go on only across a single line of code until a newline character is found where the preprocessor directive ends. Note that Semicolon (;) will be always absent at the end of the directives. The only way a preprocessor directive can extend through more than one line is by preceding the newline character at the end of the line by a backslash (\).
Some of the preprocessor directive in C programming language are given below:
#include
#define
#undef
#if
#ifdef
#ifndef
#error
__FILE__
__LINE__
__DATE__
__TIME__
__TIMESTAMP__
pragma
# macro operator
## macro operator
To define preprocessor directive we can use #define.
The syntax is:
#define identifier replacement
Example:

1 #define TABLE_SIZE 100
2 int table1[TABLE_SIZE];
3 int table2[TABLE_SIZE];

int table2[TABLE_SIZE];
After the preprocessing ,the preprocessor replaces TABLE_SIZE, so the code becomes equivalent to:

1 . int table1[100];
2 . int table2[100]; 

Storage Classes in C


classes in c programming
Storage classes in c programming language are classified into two main types according to storage area and their behavior, in this c programming tutorial we using this storage classes in many programs:-
1. Automatic storage class
2. Static storage class
3. register
Automatic storage class:
Automatic storage class variable in c programming language will created and destroyed automatically. In Automatic storage class, variables are stores in stack area of data segment or processor register.
Features:
Storage Memory
Scope Local / Block Scope
Life time Exists as long as Control remains in the block 
Static storage class:
Static storage class variables in c language will only exist once and throughout the c program, this storage variable will be always active. Static storage class variables are stores in static area of data-segment.
In a C programming there are four types of scopes are available such as
1. Body scope
2. Function scope
3. Program scope
4. File scope    
Static Storage Class:
The value of static variable linger until the execution of the whole c program. A static variable can be declared using static keyword as shown below:
Syntax:
static int i;
Example:
#include <stdio.h>
void Check();
int main(){
Check();
Check();
Check();
}
void Check(){
static int c=0;
printf("%d\t",c);
c+=10;
}
Output
0 10 20
Register storage class:
The keyword ‘register’ in C programming language is used to define a local variable.
Syntax
register int count;
#include<stdio.h>
#include<math.h>
int main()
{
int num1,num2;
register int sum;
printf("\nEnter the Number 1 : ");
scanf("%d",&num1);
printf("\nEnter the Number 2 : ");
scanf("%d",&num2);
sum = num1 + num2;
printf("\nSum of Numbers : %d",sum);
return(0);
}

File Handling



file-handling-in-c-language
We regularly utilize files for putting away data which can be handled by our projects. In this c programming tutorialwe are using file structure in our c programs. With a specific end goal to store data forever and recover it we have to utilize files.
Files in C programming are not only used for data reading but also for data writing, manipulation and many more option thanks to C programming built in functions. Our C programs are also stored in files.
Note : Stdio.h library should be added in order to use file handling functions such as basic input output functions in C programming language.
Following are the file handling function that could be used in C programming language
Functions Used In C Programming with Description 
fopen() --- New file creation or open an existing file in c programming.
fclose() --- Close a file in c programming.
getc() ---- Read character from a file.
putc() ---- Writes a character to a file.
fscanf() --- Reads specific set of data from a file.
fprintf() -- Writing specific set of data to a file.
getw() --- Reads an integer from a file.
putw() --- Writes an integer to a file.
fseek() --- Setting the location to required point.
ftell() ---- returns current location in the file.
rewind --- Set the location to the beginning of point in c programming.

Modes of operation in c:


Reading (r)
This is used when a file is used for writing
#include <stdio.h> // library
void main()
{
FILE *fopen(), *fp;
int c;
fp = fopen("prog.c","r");
c = getc(fp) ;
while (c!= EOF)
{
putchar(c);
c = getc(fp);
}
fclose(fp);
}
Writing (w)
This is used when a file is opened for writing
FILE *fp;
file = fopen("file.txt","w"); /*Create a file and add text*/
Appending (a)
This is used when a file is opened for appending
FILE *fp
file = fopen("file.txt","a");
fprintf(fp,"%s","This is just an example :)"); /*append some text*/

String handling in C

C programming string handling specifies a set of functions that implement operations on strings in the C standard library. C programmer can perform numerous operations such as string copying, strings concatenation, strings tokenization and string searching.
A string in c programming tutorial is represented as a one dimensional array of character type. Example: char sentence [10]; this in an array that can store a string of size 10.
Suppose a programmer want to store names of months, then declare name as char months [11][ ]. Note that the second square bracket is kept empty if the length of string is not specified.
If the declaration is char months [12][30], 12 names of months each with a maximum word length of 30 can be stored. The name of the months can be identified by month[0], month[1], month[2],…….., name[11]. These names of the months are read by the command
For( i=0; i<12,i++)
Scanf( “%d[^\n]”, name(i));
Initialization of strings in c language
In C programming language, a string can be initialized in a number of ways such as
char c[]="abcd";
OR,
char c[5]="abcd";
OR,
char c[]={'a','b','c','d','\0'};
OR;
char c[5]={'a','b','c','d','\0'};
string handling in c
C Programming supports a wide range of functions that can be used specifically for strings:
strcpy(s1, s2); Copy string s2 into string s1.
strcat(s1, s2); Concatenates string s2 at the end of string s1.
strlen(s1); Determines the length of string s1.
strcmp(s1, s2); Returns 0 if string s1 and string s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
strchr(s1, ch); Determines a pointer of first occurrence of character in string s1.
strstr(s1, s2); Determines a pointer of first occurrence of string s2 in string s1. 

Pointers in C


A pointer in c programming is a variable which contains the address of another variable in memory. We can have a pointer to any type of variable. The unary operator “&“gives the ``address of a variable'' where as the dereference operator * gives the ``contents of an object pointed to by a pointer''. In this c programming tutorial we use pointer concept in many programs.

How to use Pointers?


Pointers in c language are very essential for performing certain operations i.e. Gives direct access to variable address. Pointers can be used for that purpose as follows:
First define a pointer variable in c language
Assign the address of a variable to a that pointer variable
Finally Access the value by address available in the pointer variable by using unary operator * that returns the value of the variable located at the address specified by its operand. 
pointers example in c programming
Consider above Diagram :
i  refers to specific memory location in c, suppose it refers to address 65624(random address in system memory) and the Value stored in variable ‘i’ is 5. This address of the variable ‘i’ is stored in another integer variable whose name is ‘j’ and which is refered by address 65522.
Thus we can write as:
i=5;
int *j;
j = &i;
output:
j = 5;
Here j is not ordinary variable , It is special variable and called pointer variable as it stores the address of the another ordinary variable in c programming language.
Following example further clarifies the concept:
Example:
int *array_ptr = array;
printf("Ist element: %i\n", *(array_ptr++));
printf("2nd element: %i\n", *(array_ptr++));
printf("3rd element: %i\n", *array_ptr);
Example Output:
Ist element:100 2nd element: 200 3rd element: 300

Function in C


What are functions in C programming language?


In C programming language, functions are specific block of code that perform a number of predefined instruction to complete a particular task. In C programming User can either use the built-in library functions or can create its own custom functions which generally requires a prototype (function declaration) in start of the c program.
In C language, function calling is done by writing function name with opening and closing round brackets followed with semicolon. E.g. display ();
Category of Functions in C Language:
There are basically four categories of function in C programming language.

Type 1: Obtaining Parameter and Returning a Value

int addnum (int num1, int num2)
{
return num1 + num2;
}

Type 2: Obtaining Parameter but No Returning Value

void add(int num1, int num2)
{
printf("%d", num1+num2);
}

Type 3: Not Obtaining Parameter but Returning a Value

int add()
{
int num1, int num2;
num1 = 1;
num2 = 2;
return num1 + num2;
}

Type 4: Not Obtaining Parameter and No Returning Value

void add()
{
int num1, int num2;
num1 = 1;
num2 = 2;
printf("Result : %d",num1+num 2);;
}

Parameters in C functions


Below are the two ways used for passing parameter in C programming Language:
Pass by Value in c
In this type, a copy of the data is made and stored by way of the name of the parameter. The value is directly passed into the function. Any changes to the parameter have NO effect on data in the calling function.
Pass by Reference in c
A reference parameter "refers" to the original data in the calling function. Here the address of the value is passed into the function. Any changes to parameter will affect the original parameter.

passing  by value example. (Notice no &) 
   
void
doit( int  x )
{
x = 100;
Passing by reference example (Notice no “&“sign) 
   
void
doit( int & x )
{
x = 100; 
        } 

Array in C


An array in C programming language is an identifier which is used for storing large set of data with a common name. Note that a variable can store only a single data.
Arrays are of two types:
array types in c programming
1 . One-dimensional arrays
2 . Multidimensional arrays
One dimensional arrays :
Definition: Arrays are defined like the variables with an exception that each array name must be accompanied by the size (i.e. the max number of data it can store).For a one dimensional array the size is specified in a square bracket immediately after the array`s name as shown below. In this c programming tutorial we use both types of arrays in our c programs.
Datatype array name[size];
So far, weve been declaring simple variables: the declaration int i; declares a single variable, named i, of datatype int. It is also possible to declare an array of several elements.
The declaration int a[100]; declares an array in c language( for which 100 size of memory is kept reserved for it), named a, consisting of hundred elements, each element will be of type int. in Other words , an array simply is a variable that can hold more than one value.
Examples :
int x[100];
float mark[50];
char name[30];
the declaration int x[100] allows process to creates 100 memory cells starting from x[0],x[1],x[2],………,x[99].
One-dimensional arrays initialization in C programming
int weekdays[7]={1,2,3,4,5,6,7};
Multidimensional Arrays in c language:
Miltidimensional arrays contains two portions rows and columns such as
Datatype array name[rows][column];
Multidimensional arrays initialization:
int c[2][3]={{1,3,0}, {-1,5,9}};

Loop in C


In C programming language, a loop is a sequence of instruction s that is executed repeatedly until a certain condition is satisfied. Mostly, a specific process is done, such as getting data and changing it, and then some prescribed condition is checked such as whether a counter has reached a prescribed number. Here in this C programming tutorial we use almost all types of loops in our programs.
Below flowchart describes the working of a typical loop in C programming.
loop example in c programming
C programming language provides the following types of loop to handle looping requirements.
WHILE LOOP IN C
while a given condition is true, a statement or group of statements is executed continuously in c language. Initial condition is always checked before executing the loop body as shown below.
while loop in c program
FOR LOOP IN C LANGUAGE
A variable which is initialized to a prescribed value is compared with a condition, if true then body of the loop is executed and variable is incremented the loop will continue to go no until it reached the prescribed value. for loop structure is like initialization, condition and finally increment. For loop is one of the best used loop in C programming.
for loop in c programming
DO WHILE LOOP IN C PROGRAMMING LANGUAGE
In C language, do while loop, the condition is checked after executing the loop body. It is just like the while loop the difference is condition is checked only at end, as it is called as exit controlled loop.
do while loop in c language
NESTED LOOPS IN C
In nested loops, a loop is used with in another loop which makes a nested structure of loops in C language, C programming language provides this capabilities.
nested loop in c programming
BREAK STATEMENT IN C PROGRAM
If test condition returns true, Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. Break is used to exit a loop in C language.
break statement in c programming
CONTINUE STATEMENT IN C LANGUAGE
Causes the loop to jump over the remaining portion of its body and immediately retest its condition prior to reiterating.
continue statement in c language
GOTO STATEMENT IN C PROGRAMMING
Jumps over and Transfers control to the labeled statement. Due to compiler issues it is not recommended to use these statements
goto statement in c programming

Decision Making In C programming Language



Decision making structures are one the tools which gives C language its power. In these structure the programmer specifically defines one or more conditions what he wants to be evaluated or tested by the c program, given a statement or statements to be executed if the condition is becomes true, and optionally, other statements to be executed if the condition is false. In this C programming tutorial we using almost all decision making structures in the programs.
The generic form of a typical decision making structure in c language found in most of the programming language
When a programmer execute the c program, the statements are executed in sequence i.e. top to bottom order in which they appear in the C program. Usually Programmer may need a C language statement or a set of statements to be executed for a fixed no of times or until a condition becomes true moreover if a programmer may want to skip some statements based on testing a condition in C programming language. For all these we use conditional statements. Conditional statements are of two types
1 . Branching in C programming Language
2 . Looping in C programming
Branching:
If refers to execute one of several possible options depending on the outcome of a logic, which is carried at some specific point within a c program.
:Example:
Nested if-else statement
if – else statement with in other if – else statement. Such statements are called nested if statements in c programming language.
if (expression1)
{
Execute if expression1 is true;
}
else if( expression2)
{
Execute if expression1 is false and 2 is true;
}
else if (expression 3)
{
Execute if text expression1 and 2 are false and 3 is true;
}

Else
{
Execute if all of the expressions are false;
}
Looping: 
Looping in C programming language is used when one wants to execute a group of instructions repeatedly, a fixed no of times or until a specified condition is satisfied.
Example:
For (Age=0; Age<60; Age++)
{
Code to be executed;
}

Operators in C programming language


The symbols which are used to perform Athematic (mathematical), logical, rational operations in a C language are calledC operators.
Operator consists of following types:
Athematic Operators:
addition is denoted by a + sign. We use addition to add two variables.
subtraction is denoted by a - sign
multiplication is denoted by a * sign
division is denoted by a / sign
modulus (remainder) % : mod operator in c programming languageis used to find the remainder of some division.
Relational Operators:
Relational operators in c language is used to relate one operand with the other. the relational operators are : < Specifies that left-hand operand is less than right-operand
<= Specifies that left-hand operand is less than or equal to right-hand operand
> Specifies left-hand operand is greater than right-hand operand
>= Specifies that left-hand operand is greater than or equal to right-hand operand
== Specifies that left-hand operand is equal to right-hand operand
!= Specifies that left-hand operand is not equal to right-hand operand 
Logical Operators:
C programming language provides the following binary logical operators for program:
&& : Operation AND : returns true if both operands are true
|| : Operation OR : returns true if a single operand or both operands are true
^^ : Operation XOR : returns true if exactly one operand is true
binary operator:
C language provides the following binary logical operators for program:
& : Performs AND operation
| : Performs OR operation
^ : Performs XOR operation
<< : Performs Shift operation i.e. left shifting left hand operand by the number of bits specified by the right-hand operand
>> : Performs Shift operation i.e. right shifting-left hand operand by the number of bits specified by the right-hand operand.
The shift operators are used to move bits left or right in a given integer value specified. Shifting left will consume empty bit positions on the right-hand side of the result producing zeroes
Assignment Operators:
C programming language provides the following binary logical operators for program:
= : Equates left-hand operand equal to the right-hand expression value
+= : Increments the left-hand operand specified by right-hand expression value
-= : Decrements the left-hand operand specified by right-hand expression value
*= : Multiply the left-hand operand specified by right-hand expression value
/= : Divide the left-hand operand specified by right-hand expression value
%= : Modulo the left-hand operand specified by right-hand expression value
|= : Performs Bitwise OR operation between the left-hand operand with the right-hand expression value
&= : Performs Bitwise AND operation between the left-hand operand with the right-hand expression value
^= : Performs Bitwise XOR operation between the left-hand operand with the right-hand expression value 

Variables & Constants in C


In C programming language, a constant is an identifier which contains a specific value The value cannot be altered during normal c program execution as the value is constant.
Example
const float PI = 3.1415927; // (Pi is a constant)
for(int i=0;i<10,i++) // i is a variable
Floating-point constants
Floating point constants in C programming tutorial are the type of numeric constants that can either take decimal point or exponent form.
Example:
-2.0
0.0000234
-0.22E-5
Integer constants
Integer constants in C language are the type of numeric constants (constant associated with number) which do not have any fractional part or exponential part.
Three types of integer constants are available in C programming language:
Decimal constant (base 10)
E.g. Decimal numbers: 0 1 2 3 4 5 6 7 8 9
Octal constant (base 8)
E.g. Octal numbers: 0 1 2 3 4 5 6 7
Hexadecimal constant (base 16)
E.g. Hexadecimal numbers: 0 1 2 3 4 5 6 7 8 9 A B C D E F.
Character constants
Character constants in C language are the type of constant which use single quotation around characters. For example: 'l', o', 'v', 'e' etc.
Variables:
An identifier which holds the value that can be altered during normal program execution is called variable. Variables can be visualize as memory location in computer's memory to store data. In other words, Variable names are just the symbolic representation of a memory location.
In C programming following basic variable types are available:
char : This is an integer type. Consume 1 bytes of memory location
int : Contains decimal point free integer value. Consume 4 bytes of memory
float : Single precision floating point value. Consume 4 bytes of memory
double : Double precision floating point value. Consume 8 bytes of memory
void : Represents the absence of type.
The C programming language also gives supports for two important kind of variables which could be used for the dynamic allocation of memory.
Static variable:
static int shared = 3; //shared is of static type variable
Static variable is defined outside all blocks and has static. Always declared outside of main block.
global variable:
global variable in C language is a type of variable which has global scope, In other words, global variable is accessible throughout the program, unless the programmer hides it.
#include <stdio.h>
static int shared = 3; //note declaration of variable just after the library
main()
{
}

Data Types in C and Description


Basic data types Of C language:

integer type
This type is used to define integer numbers. It is denoted as "int" in the C programs in this c programming tutorial
{
int number;
number = 5;
}
Floating-point types.
This type is used to define decimal numbers. It will be denoted as "float" in the c language
{
float Miles;
Miles = 5.6;
}
Boolean type
The Boolean type is used to define a variable that consists of only two values true or false
{
bool b = getc(stdin) == 't' ? true : false;
}

double - data type
Double in c language is used to define BIG decimal point numbers. The memory reserved for this datatype is twice as compared to int datatype. Likely to be 8 bytes.
{
double Atoms;
Atoms = 2500000;
}

char - data type
char data type defines characters in a c program.

{
char alphabet;
alphabet = 'x';
}
Enumerated types in C language:
They are also arithmetic types and they are used to define variables that can only be assigned certain discrete integer values throughout the c program.
The type void:
The type specified void returns no value, meaning no value is available. It is used mainly in functions which returning null or no value.
Derived types in C programming:
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types. Which will be detailed in the next chapters

Program to write a text to a file in C


We will write a program in C that will accept a string from the user and write the string in a file. In this program, we will use fopen function in order to open a file. We will also use fputs function which will write a string to a file.


Below is the program:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<stdio.h>
#include<conio.h>
int main()
{
char *str;
FILE *fp;
//Open the file in write mode
fp = fopen("write.txt", "w");
printf("Enter a string: ");
gets(str);
        
        //write string in a file
fputs(str, fp);
getch();
}