ad728

Monday, September 26, 2016

C Programming

Include Header File Section

C program depends upon some header files for function definition that are used in program.
Each header file by default is extended with .h. The header file should be included using # include directive as given here.
Global Declaration
This section declares some variables that are used in more than one function. These variables
are known as global variables. This section must be declared outside of all the functions.Function Main
Every program written in C language must contain main () function. The function main() is
a starting point of every C program. The execution of the program always begins with the function main ().
Declaration Part
The declaration part declares the entire variables that are used in executable part. The initialisations of variables are also done in this section. Initialisation means providing initial value
to the variables.


Executable Part
This part contains the statements following the declaration of the variables. This part conatins a set of statements or a single statement. These statements are enclosed between the braces.
Identifiers


Identifiers are names of variables, functions, and arrays. They are user-defined names,
consisting sequence of letters and digits, with the letter as the first character.Variable
It is a data name used for storing a data value. Its value may be changed during the program
execution. The value of variables keeps on changing during the execution of a program.Scope
Scope of variable tells compiler the visibility of variable in the blocktypedef
It is used to create new data type. But it is commonly used to change existing data type with another name.
Syntax:
typedef [data_type] synonym;
OR
typedef [data_type] new_data_type;
Example:
typedef int integer;
integer rno;
Keyword 
C Keyword
Auto
Double
Int
Struct
Break
Else
Long
Switch
Case
Enum
Register
Typedef
Char
Extern
Return
Union
Const
Float
Short
Unsigned
Continue
For
Signed
Void
Default
Goto
Sizeof
Volatile
Do
If
Static
While






Operators
Type of Operator
Symbolic representtion
Arithmetic operators
+, -, *, /, %
Relational operators
  >, <, ==, >=, <=, !=  
Logical operators
&&, ||, !=
  Increment and decrement operator   
++ and --
Assignment operator
=
Bitwise operator
&, |, ^, >>, <<, ~
Comma operator
,
Conditional operator
  Condition ? True Statement  False Statement
Qualifier
Qualifier is an extra name given to either variables or functions , showing an extra quality or extra meaning for that variable or function.
1.Size qualifiers- It tells the size of basic data type. E.g. short, long
short int
2. Sign qualifiers- It tells the sign of the variable +ive or -ive E.g. signed , unsigned
3. Constant qualifiers/modifier - It can be declared with keyword const. An object declared by const cannot be modified.
const int i=10;
float const f=0.0f;
unsigned const long double ld=3.14L;
Example
void main()
{
const int a=5;
a++;
printf(“%d”,a);
}
output : compiler error, cannot modify const variable.
4. Volatile qualifiers- A variable is declared volatile when it’s value is changed external source from outside the program. “volatile” keyword is used.
(There is another type qualifier near, far, huge, which qualify only pointer type data type ,interrupt is also qualifier of data)
Storage Class
A storage class is an attribute that tells us where the variable would be stored,
what will be the initial value of the variable if no value is assigned to that variable,
life time of the variable and scope of the variable.
Scope:-  Scope of variable tells compiler the visibility of variable in the block
There are four storage classes in C:
1) Automatic storage class
2) Register storage class
3) Static storage class
4) External storage class
Automatic storage class:
keyword - ‘auto’.
variable declared stored in the memory.
Default - garbage value.
Scope - local to the block in which the variable is defined.
Variable is alive till the control remains within the block in which the variable id defined.
Example
#include<conio.h> #include<stdio.h> void main(){ auto num = 10; { auto num = 60; printf(“%d",num); } printf(“ %d",num); } Output: 60 10
Register storage class:
keyword -‘register’.
Variable declared stored in the CPU register.
Default - garbage value.
Scope of  variable - local to the block 
- The variable is stored in CPU register, it takes very less time to access that variable. Hence it becomes very time efficient.
- It is not necessary that variable declared as register would be stored in CPU registers. The number of CPU registers is limited. If the CPU register is busy doing some other task then variable might act as automatic variable
- Unary operator[&] is not associated with it because value is not stored in ram.
- If we store same variable in the register memory than we can access that memory location directly without using the Address operator
Example
#include<conio.h> #include<stdio.h> void main(){ register int a; printf(“%d",a); } Output: 7247 //the output is garbage value.
Static storage class:
keyword - ‘static’.
variable declared stored in the memory.
Default - zero.
Scope- local to the block in which the variable is defined.
Life of variable persists between different function calls.
Example
#include <stdio.h> void Check(); int main(){ Check(); Check(); Check(); } void Check(){ static int c=0; printf("%d",c); c+=5; } Output- 0 5 10
External storage class:
keyword - ‘extern’.
Variable declared stored in the memory.
Default - zero.
Scope - global.
-Variable is alive as long as the program’s execution doesn’t come to an end.
-External variable can be declared outside all the functions or inside function using ‘extern’ keyword.
Example
#include <stdio.h> void Check(); extern int a=5; /* a is global variable because it is outside every function */ int main(){ a+=4; Check(); return 0; } void Check(){ ++a; /* ----- Variable a is not declared in this function but,
works in any function as they are global variable ------- */ printf("a=%d ",a); } Output : a=10
Conditional Operator ( ? : )
Syntax: conditional_expression ? expression_if_true : expression_if_false
Nesting of conditional operator
Syntax : conditional_expression_1 ?(conditional_expression_2 ?expression_true_conditional_2 :expression_false_conditional_2 ) :expression_false_conditional_1
Example :-
int  x = 5 ,  y= 6;
int a = x > y ? x : y ;
a= x if x > y otherwise a = y
we can also assign a string using conditional operator.
Decision Making(if, if_else, nested if_else, else_if ladder)
1.  if
if ( test expression )
{
  statement_block;
}
2.  if_else
if ( test expression )
{
  statement_block;
}
else
{
  statement_block;
}
3.  nested if_else
if ( test expression )
{
  if (   test expression )
   {
     statement_block;
   }
   else
    {
     statement_block;
    }
}
else
{
  if (   test expression )
   {
     statement_block;
   }
   else
    {
     statement_block;
    }
}
4.  Else_if ladder
if ( test expression )
{
  statement_block;
}
else if ( test expression )
{
  statement_block;
}
else if ( test expression )
{
  statement_block;
}
else
{
  statement_block;
}
Switch Statement
switch ( expression )
{
case value 1:
  statement_block-1;
  break;
case value 2:
  statement_block-1;
  break;
.....
default:
  default_block;
  break;
}
/* If value of expression is equal to any value for example value1 then statement block 1 will be executed if the value is not matched with any value then default statement block will be executed*/
Some Rules for switch statement:
- expression must be an integral value.
- cases must have different value
- break statement should be there for terminate the case statement block.
- default case is optional.
Looping
For loop
It is an entry control loop .
for ( initialization ;  test_condition ;  increment/decrement  )
{
body_of_loop;
}
Example:
for ( i = 1 ; i <= 3 ; i++ )
{
printf(“%d “,i ) ;
}
Output: 1 2 3
Step 1 :  i is integer and it is initialized by 1
Step 2 :  Controllers of compiler now check the condition if i<=3 then it will come to the body of loop then it will print value of "i “  i.e.  1 and then controllers will come to the part of increment and will increase the value of “i” . Here i++ means i=i+1 . We can also use i=i+5 or i=i*2 or whatever we want.
Step 3 :  Now the value of i = 1+1= 2 and it will check the condition that i<=3
Step 4 :  Condition is true again and it will print the value of “i” i.e. 2 and it will now go to the increment part again and increase the value of “i” and again check the condition.
Step 5 :  3<=3  the condition is again true and it will print the value of   “i”  i.e.  3 and then it will again increase the value of “i”
Step 6 :  4<=3 the condition is false now and the loop will terminate.
Nested for loop
for ( initialization  ;  test_condition;   increment/decrement  )
{
for (  initialization ;  test_condition;  increment/decrement )
  {
      //body_of_loop
  }
//statements;
}
Try it :
1.
for ( i=0 ;  ;  i++ )
{
  printf (" Hello ");
  if ( i > 4)
   break;
}
2.
for ( i = 0 ;  ; )
{
  printf (" Hello " );
  i++;
  if(i>4)
  break;
}
3.
for ( ;  ;  )
{
  printf (" Hello");
}

While loop
It is exit control loop.
Syntax:
while ( test_condition )
{
  body of loop;
}
How it is used:
initialization;
while ( test_condition )
{
   body of loop;
   increment/decrement/other_change;
}
Try it
1.
while ( 0 )
{
   printf ( "Hello World ");
}
2.
while ( 1 )
{
    printf ( "Hello World " );
}

Do While loop
Syntax:
do
{
   body of loop;
} while ( test_condition ) ;
Note :  Semicolon must be there after while (   test _condition )
Switch Statement
switch ( expression )
{
case value 1:
  statement_block-1;
  break;
case value 2:
  statement_block-1;
  break;
.....
default:
  default_block;
  break;
}
/* If value of expression is equal to any value for example value1 then statement block 1 will be executed if the value is not matched with any value then default statement block will be executed*/
Some Rules for switch statement:
- expression must be an integral value.
- cases must have different value
- break statement should be there for terminate the case statement block.
- default case is optional.
Looping
For loop
It is an entry control loop .
for ( initialization ;  test_condition ;  increment/decrement  )
{
body_of_loop;
}
Example:
for ( i = 1 ; i <= 3 ; i++ )
{
printf(“%d “,i ) ;
}
Output: 1 2 3
Step 1 :  i is integer and it is initialized by 1
Step 2 :  Controllers of compiler now check the condition if i<=3 then it will come to the body of loop then it will print value of "i “  i.e.  1 and then controllers will come to the part of increment and will increase the value of “i” . Here i++ means i=i+1 . We can also use i=i+5 or i=i*2 or whatever we want.
Step 3 :  Now the value of i = 1+1= 2 and it will check the condition that i<=3
Step 4 :  Condition is true again and it will print the value of “i” i.e. 2 and it will now go to the increment part again and increase the value of “i” and again check the condition.
Step 5 :  3<=3  the condition is again true and it will print the value of   “i”  i.e.  3 and then it will again increase the value of “i”
Step 6 :  4<=3 the condition is false now and the loop will terminate.
Nested for loop
for ( initialization  ;  test_condition;   increment/decrement  )
{
for (  initialization ;  test_condition;  increment/decrement )
  {
      //body_of_loop
  }
//statements;
}
Try it :
1.
for ( i=0 ;  ;  i++ )
{
  printf (" Hello ");
  if ( i > 4)
   break;
}
2.
for ( i = 0 ;  ; )
{
  printf (" Hello " );
  i++;
  if(i>4)
  break;
}
3.
for ( ;  ;  )
{
  printf (" Hello");
}

While loop
It is exit control loop.
Syntax:
while ( test_condition )
{
  body of loop;
}
How it is used:
initialization;
while ( test_condition )
{
   body of loop;
   increment/decrement/other_change;
}
Try it
1.
while ( 0 )
{
   printf ( "Hello World ");
}
2.
while ( 1 )
{
    printf ( "Hello World " );
}

Do While loop
Syntax:
do
{
   body of loop;
} while ( test_condition ) ;
Note :  Semicolon must be there after while (   test _condition )
Array
It is the ability to use a single variable to represent a collection of items and to refer an item by using variable name and it’s index.
Declaration of 1-D Array:
data_type  variable_name[ size ] ; 
Example : int arr [10] ;
Initialization of 1-D Array
data_type  variable_name [size] = { value_1, value_2...,value_size };
Example : int arr [3] = { 1, 2, 3} ;
int arr [ ]  = { 1,2,3 };  // a[0]=1 , a[1]=2 , a[2]=3
char name [ ] = { ‘S’,’A’,’N’,’J’,’A’,’Y’,’’};
char name[ ] = “Sanjay Sharma”;
int arr [4] = { 1,2 }; // partially initialization , remaining initialized by 0 for int
char name [10 ] = { ‘S’,’N’,’J’,’’}; //size is 10 but 4 are initialized. remaining are NULL for char
Declaration of 2-D Array
data_type   variable_name [row_size ] [column_size ];
Example: int arr[4][4];
Initialization of 2-D Array
Example: int arr[2][2] = {1,2,3,4};
int arr[2][2]= { { 1,2 } ,{ 3, 4} };
Row
Col
1th
2th
0th
1
2
1th
3
4
int num [ ][ 2 ] = { 1,2,3,4 }; // It is correct
int num [2][ ] = { 1,2,3,4 }; // It is not correct

Character Array or String
Initializing and Declaring String
char string [10] ;
char name [ ] = { ‘S’,’A’,’N’,’J’,’A’,’Y’,’’};
char name[ ] = “Sanjay Sharma”;
Note: 
- If we have two variables char array type means string char s1[10] and char s2[10] we cannot copy these char type array directly as s1=s2;
-  is null character. It should be last element of character type array because it tells the compile that the string has come to it’s end because in C Language there is no array boundation.
Reading String From User
scanf (“%s”,string);
Note: scanf function terminates the input when input is whitespace
Example: 
if user entered a name SANJAY SHARMA
and we print it using printf (“%s”,string) then SANJAY will be printed.
The solution is scanf (“%[^ ]”,string); here [^ ]tells the compiler to do not terminate the input till new line ( ) entered.
Other solution is gets function which can get a string with white space from user. For using gets() we have to include string.h header file.
Exmaple: gets (string);
Call by value vs 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.
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.
Types of Function
1. No argument No return type
void printdata ( )
{
printf (“ Hello ”);
}
2. With Argument No Return Value
void printdata (int i)
{
printf (“%d”,i);
}
3. No Argument With Return Value
int checkdata ( )
{
return 2;
}
4. Argument With Return Value
int sendvalue( int i)
{
return i;
}

Recursion:
It is the process of calling a function by itself , until some specified condition is satisfied. It is used for repetitive computation ( like finding factorial of a number) in which each action is stated in term of previous result.
return type Function ()
{
//body
Function()
}
Example:
#include<stdio.h> long int factorial(int n); void main() { int n; long int m; scanf("%d",&n); m=factorial(n); printf(" factorial is %d", m); } long int factorial(int n) { if (n<=1) return(1); else return (n*factorial(n-1)); }
Structure
Structure is user defined data type, which can store the different data type variable together
Syntax:
struct [structure tag]
{
   member definition;
   member definition;
...
} variables_name;
Example
struct book
{
  char  name[50] ;
  char  author[50] ;
  int  id ;
} b ;

Union
A union is a user defined data type that enables to store different data types in the same memory location. We can define a union with many members,
but only one member can contain a value at any given time.
The memory required to store a union variable is the memory required for largest element of an union
Syntax:
union [union tag]
{
member definition ;
member definition ;
...
} variables_name ;
Example
union book
{
  char  name[50] ;
  char  author[50] ;
  int  id ;
} b ;
Difference between Structure and Union
Structure
Union
1.The keyword  struct is used to define a structure
1. The keyword union is used to define a union.
2. When a variable is associated with a structure, the compiler allocates the memory for each member. The size of structure is greater than or equal to the sum of  sizes of its members. The smaller members may end with unused slack bytes.
2. When a variable is associated with a union, the  compiler allocates the  memory by considering the size of the largest memory. So, size of union is equal to the size of largest member.
3. Each member within a structure is assigned unique storage area of location.
3. Memory allocated is shared by individual members of union.
4. The address of each member will be in ascending order This indicates that memory for each member will start at different offset values.
4. The address is same for all the members of a union. This indicates that every member begins at the same offset value.
5 Altering the value of a member will not affect other members of the structure.
5. Altering the value of any of the member will alter other member values.
6. Individual member can be accessed at a time
6. Only one member can be accessed at a time.
7. Several members of a structure can initialize at once.
7. Only the first member of a union can be initialized.
Pointer
Pointer is a user defined data type which creates special types of variables which can hold the address of primitive data type
like char, int, float, double or user defined data type like function, pointer etc. or derived data type like array, structure, union, enum.
Pointers are used in C program to access the memory and manipulate the address
Declaration of Pointer
Dereference operator(*) are used to identify an operator as a pointer.
Syntax:
data_type  * pointer_variable_name;
Example:  int  *ptr;
Explanation :
int a=5;
int  *ptr;
ptr=&a;
ptr is a pointer which is storing the address of “a” variable.
Pointer to Pointer
int  *ptr1;
int  **ptr2;
ptr1=&a;
ptr2=&pt1;
Notes:
* is known as indirection operator which gives content of any variable.& is known as reference operator which gives address where variable has stored in memory.* and & operators always cancel to each other i.e. *&p=pBut it is not right to write: &*p=p.The value of null pointer is 0.If pointer is assigned to NULL, it means it is pointing to nothing.
Generic pointer
void pointer in c is known as generic pointer. Literal meaning of generic pointer is a pointer which can point type of data.
Example:  void  *ptr;
#include<stdio.h> int main() { char c='A'; int i=4; void *p; char *q=&c; int *r=&i; p=q; printf("%c",*(char *)p); p=r; printf("%d",*(int *)p); return 0; }
Wild pointer:
A pointer in c which has not been initialized is known as wild pointer.
Example: #include<stdio.h> int main() { int *ptr; printf("%u ",ptr); printf("%d",*ptr); return 0; } Output: Any address Garbage value
Here ptr is wild pointer because it has not been initialized.
Note :  There is difference between the NULL pointer and wild pointer. Null pointer points the base address of segment while
wild pointer doesn’t point any specific memory location.
Dangling pointer:
If any pointer is pointing the memory address of any variable but variable has deleted from that memory location while pointer
is still pointing such memory location. Such pointer is known as dangling pointer and this problem is known as dangling pointer
problem. In other word we can say a pointer whose pointing object has been deleted is called dangling pointer.
#include<stdio.h> int *callme(); void main() { int *ptr; ptr=callme(); fflush(stdin); printf("%d",*ptr); } int * callme() { int x=5; ++x; return &x; }
Output: Garbage value
Note: In some compiler you may get warning message returning address of local variable or temporary
Explanation: Variable x is local variable. Its scope and lifetime is within the function call hence after returning address of x variable
x became dead and pointer is still pointing ptr is still pointing to that location.
Solution of this problemMake the variable x is as static variable.
#include<stdio.h>
int *callme();
void main(){
int *ptr;
ptr = callme();
fflush(stdin);
printf("%d",*ptr);
}
int * call(){
static int x=5;
++x;
return &x;
}
Output: 6

NULL pointer:
Literal meaning of NULL pointer is a pointer which is pointing to nothing. NULL pointer points the base address of segment.
NULL is macro constant which has been defined in the heard file stdio.h, alloc.h, mem.h, stddef.h and stdlib.h as
#define NULL 0
Examples of NULL pointer:
1. int  *ptr=(char *)0;
2. float  *ptr=(float *)0;
3. char  *ptr=(char *)0;
4. double  *ptr=(double *)0;
5. char  *ptr=’’;
6. int  *ptr=NULL;
Example:
#include <stdio.h> int main() { if(!NULL) printf("In if part"); else printf("In else part"); return 0; } Output: In if part
Explanation:
!NULL = !0 = 1
In if condition any non zero number mean true.
Structure
Structure is user defined data type, which can store the different data type variable together
Syntax:
struct [structure tag]
{
   member definition;
   member definition;
...
} variables_name;
Example
struct book
{
  char  name[50] ;
  char  author[50] ;
  int  id ;
} b ;

Union
A union is a user defined data type that enables to store different data types in the same memory location. We can define a union with many members,
but only one member can contain a value at any given time.
The memory required to store a union variable is the memory required for largest element of an union
Syntax:
union [union tag]
{
member definition ;
member definition ;
...
} variables_name ;
Example
union book
{
  char  name[50] ;
  char  author[50] ;
  int  id ;
} b ;
Difference between Structure and Union
Structure
Union
1.The keyword  struct is used to define a structure
1. The keyword union is used to define a union.
2. When a variable is associated with a structure, the compiler allocates the memory for each member. The size of structure is greater than or equal to the sum of  sizes of its members. The smaller members may end with unused slack bytes.
2. When a variable is associated with a union, the  compiler allocates the  memory by considering the size of the largest memory. So, size of union is equal to the size of largest member.
3. Each member within a structure is assigned unique storage area of location.
3. Memory allocated is shared by individual members of union.
4. The address of each member will be in ascending order This indicates that memory for each member will start at different offset values.
4. The address is same for all the members of a union. This indicates that every member begins at the same offset value.
5 Altering the value of a member will not affect other members of the structure.
5. Altering the value of any of the member will alter other member values.
6. Individual member can be accessed at a time
6. Only one member can be accessed at a time.
7. Several members of a structure can initialize at once.
7. Only the first member of a union can be initialized.
Pointer
Pointer is a user defined data type which creates special types of variables which can hold the address of primitive data type
like char, int, float, double or user defined data type like function, pointer etc. or derived data type like array, structure, union, enum.
Pointers are used in C program to access the memory and manipulate the address
Declaration of Pointer
Dereference operator(*) are used to identify an operator as a pointer.
Syntax:
data_type  * pointer_variable_name;
Example:  int  *ptr;
Explanation :
int a=5;
int  *ptr;
ptr=&a;
ptr is a pointer which is storing the address of “a” variable.
Pointer to Pointer
int  *ptr1;
int  **ptr2;
ptr1=&a;
ptr2=&pt1;
Notes:
* is known as indirection operator which gives content of any variable.& is known as reference operator which gives address where variable has stored in memory.* and & operators always cancel to each other i.e. *&p=pBut it is not right to write: &*p=p.The value of null pointer is 0.If pointer is assigned to NULL, it means it is pointing to nothing.
Generic pointer
void pointer in c is known as generic pointer. Literal meaning of generic pointer is a pointer which can point type of data.
Example:  void  *ptr;
#include<stdio.h> int main() { char c='A'; int i=4; void *p; char *q=&c; int *r=&i; p=q; printf("%c",*(char *)p); p=r; printf("%d",*(int *)p); return 0; }
Wild pointer:
A pointer in c which has not been initialized is known as wild pointer.
Example: #include<stdio.h> int main() { int *ptr; printf("%u ",ptr); printf("%d",*ptr); return 0; } Output: Any address Garbage value
Here ptr is wild pointer because it has not been initialized.
Note :  There is difference between the NULL pointer and wild pointer. Null pointer points the base address of segment while
wild pointer doesn’t point any specific memory location.
Dangling pointer:
If any pointer is pointing the memory address of any variable but variable has deleted from that memory location while pointer
is still pointing such memory location. Such pointer is known as dangling pointer and this problem is known as dangling pointer
problem. In other word we can say a pointer whose pointing object has been deleted is called dangling pointer.
#include<stdio.h> int *callme(); void main() { int *ptr; ptr=callme(); fflush(stdin); printf("%d",*ptr); } int * callme() { int x=5; ++x; return &x; }
Output: Garbage value
Note: In some compiler you may get warning message returning address of local variable or temporary
Explanation: Variable x is local variable. Its scope and lifetime is within the function call hence after returning address of x variable
x became dead and pointer is still pointing ptr is still pointing to that location.
Solution of this problemMake the variable x is as static variable.
#include<stdio.h>
int *callme();
void main(){
int *ptr;
ptr = callme();
fflush(stdin);
printf("%d",*ptr);
}
int * call(){
static int x=5;
++x;
return &x;
}
Output: 6

NULL pointer:
Literal meaning of NULL pointer is a pointer which is pointing to nothing. NULL pointer points the base address of segment.
NULL is macro constant which has been defined in the heard file stdio.h, alloc.h, mem.h, stddef.h and stdlib.h as
#define NULL 0
Examples of NULL pointer:
1. int  *ptr=(char *)0;
2. float  *ptr=(float *)0;
3. char  *ptr=(char *)0;
4. double  *ptr=(double *)0;
5. char  *ptr=’’;
6. int  *ptr=NULL;
Example:
#include <stdio.h> int main() { if(!NULL) printf("In if part"); else printf("In else part"); return 0; } Output: In if part
Explanation:
!NULL = !0 = 1
In if condition any non zero number mean true.
Dynamic Memory Allocation
Allocate the memory at run time is called Dynamic memory allocation.
Although, C language inherently does not has any technique to allocated memory dynamically, there are 4 library functions under "stdlib.h" for dynamic memory allocation.
malloc () :  Allocates requested size of bytes and returns a pointer first byte of allocated space
calloc():  Allocates space for an array elements, initializes to zero and then returns a pointer to memory
free ():  free or dellocate the previously allocated space
realloc () :  Reallocate or change the size of previously allocated space
/*read n numbers and find their sum*/ #include<stdio.h> void main() { int *x, n, i, sum=0; printf(" Enter number of numbers"); scanf("%d", &n); x=(int *)malloc(n * sizeof(int)); for(i=1;i<=n,++i) { scanf("%d", x+i); sum +=*(x+i); } printf(" The sum is %d ", sum); }
File Handling
Data Files are used to store data on the memory device permanently and to access whenever is required. There are two types of data files
1. Stream Oriented data files    : Stream oriented data files are either text files or unformatted files.
2. System Oriented data files  :  System oriented data files are more closely related to computer’s operating system and more complicated to work with.
 Opening and Closing data files
The first step is to create a buffer area where information is stored temporarily before passing to computer memory. It is done by writing.
FILE *fp;
- Here fp is the pointer variable  to indicate the beginning of the buffer area and called stream pointer
- The next step is to open a data file specifying the type or mode i.e. read only file , write only file , read /write file. This is done by using the library function fopen.
The syntax is
fp = fopen( filename , mode ) ;
the mode can be--
‘r’ ( to open an existing file for reading only)‘w’ ( to open a new file for writing only. If file with filename exists, it will be destroyed and a new file is created in its place)‘a’ ( to open an existing file for appending. If the file name does not exist a new file with that file name will be created)‘r+’ ( to open an existing file for both reading and writing)‘w+’ ( to open a new  file for reading and writing. If the file exists with that name, it will be destroyed and a new one will be created with that name)‘a+’ ( to open an existing file for reading and writing. If the file does not exist a new file will be created).
For writing formatted data to a file we use the function fprintf.
The syntax is fprintf( fp,”conversion string”, value ); 
Example to write the name “Sanjay” to the file named ‘st.dat’
FILE *fp; 
fp=fopen("st.dat","w"); 
fprintf(fp,”%[^ ]”,”Sanjay”);
The last step is to close the file after the desired manipulation. This is done by the library function fclose. Syntax is:
fclose(fp);
functions:
fclose (ptr) ;
fclose( ) function returns zero on success, or EOF if there is an error in closing the file.
Reading from a File
Once the file has been opened for reading using fopen( ), as we have seen, the file’s contents are brought into buffer and a pointer is set up that points to the first character in the buffer.
To read the file’s contents from memory there exists a function called fgetc ( ). This can be used in our program as-
ch = fgetc ( fp ) ;
The fgetc ( ) function reads a character from the input file referenced by fp.
str=fgets( ) it allows to read a string from a stream.
fscanf (FILE *fp, const char *format, ...)
function to read strings from a file but it stops reading after the first space character encounters.
example: fscanf(fp,"%s",str)
Writing a file
fputc ( argument_char , fp ) ;
fputc() writes the character value of the argument to the output stream referenced by ptr.
fputs( argument_string, fp );
fputs() writes the string in argument to the output stream referenced by ptr.
Share:

Thursday, September 22, 2016

AIDE Tutorial - 23.1 Option menu 2

Create a new folder in resource name it my_menu



my_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
   
    <item
        android:id="@+id/item1"
        android:title="Setting"/>
   
<item
        android:id="@+id/item2"
        android:title="Help"/>

<item
        android:id="@+id/item3"
        android:title="About"/>

<item
        android:id="@+id/item4"
        android:title="Exit"/>
</menu>



Then Go to MainActivity.java

package com.kc.optionmenu2;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;

public class MainActivity extends Activity
{
    @Override

    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater men= getMenuInflater();
men.inflate(R.menu.my_menu,menu);

// TODO: Implement this method
return true;
}



@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if(item.getItemId()==R.id.item1)
{
Toast.makeText(this, "Setting is clicked",
Toast.LENGTH_SHORT).show();
}else

if(item.getItemId()==R.id.item2)
{
Toast.makeText(this, "Help is clicked",
   Toast.LENGTH_SHORT).show();
}else

if(item.getItemId()==R.id.item3)
{
Toast.makeText(this, "About is clicked",
   Toast.LENGTH_SHORT).show();
}else

if(item.getItemId()==R.id.item4)
{
Toast.makeText(this, "Exit is clicked",
   Toast.LENGTH_SHORT).show();
}
// TODO: Implement this method
return true;
}
}





Share:

Sunday, September 4, 2016

AIDE Tutorial - 20.3 WebView with exit Alert Dailog

Java



package com.kc.webview3;
import android.app.*;
import android.os.*;
import android.widget.*;
import android.webkit.*;

public class MainActivity extends Activity
{
private FrameLayout fl;
private ProgressBar pb;
private WebView web;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
  
web=(WebView) findViewById(R.id.web);
pb=(ProgressBar)findViewById(R.id.pb);
fl=(FrameLayout)findViewById(R.id.fl);

WebSettings WebSettings=web.getSettings();
WebSettings.setJavaScriptEnabled(true);
web.loadUrl("http://shyamkumarkc.blogspot.com");
web.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView View, String url){
fl.removeView(pb);
}
});
}
@Override
    // Detect when the back button is pressed
    public void onBackPressed() {
        if(web.canGoBack()) {
            web.goBack();
        } else {
         

AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Are you sure you want to exit?");
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which)
{
MainActivity.this.finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
AlertDialog alert =builder.create();
alert.show();
}
}
}

Manifest
<uses-permission android:name="android.permission.INTERNET"/>

Main xml





<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
android:id="@+id/fl">


    <WebView
        android:id="@+id/web"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
<ProgressBar
android:id="@+id/pb"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>




Share:

Total Pageviews

Sponsor

Sponsor

ad300