Saturday 31 August 2013

Program to find largest of n numbers in c

0 comments

Program to find largest of n numbers in c

#include<stdio.h>
int main(){
  int n,num,i;
  int big;
  
  printf("Enter the values of n: ");
  scanf("%d",&n);

  printf("Number %d",1);
  scanf("%d",&big);

  for(i=2;i<=n;i++){
    printf("Number %d: ",i);
    scanf("%d",&num);

    if(big<num)
      big=num;
  }
  
  printf("Largest number is: %d",big);

  return 0;
}

Sample Output:
Enter the values of n:
Number 1: 12
Number 2: 32
Number 3: 35
Largest number is: 35

C program for swapping of two numbers

0 comments

C program for swapping of two numbers

#include<stdio.h>
int main(){
    int a,b,temp;
   
    printf("Enter any two integers: ");
    scanf("%d%d",&a,&b);
    printf("Before swapping: a = %d, b=%d",a,b);

    temp = a;
    a = b;
    b = temp;
    printf("\nAfter swapping: a = %d, b=%d",a,b);

    return 0;
}

=> C program for swapping of two numbers using pointers

#include<stdio.h>
int main(){
    int a,b;
    int *ptra,*ptrb;
    int *temp;

    printf("Enter any two integers: ");
    scanf("%d%d",&a,&b);

    printf("Before swapping: a = %d, b=%d",a,b);

    ptra = &a;
    ptrb = &b;

     temp = ptra;
    *ptra = *ptrb;
    *ptrb = *temp;

    printf("\nAfter swapping: a = %d, b=%d",a,b);
    return 0;
}

Sample output:
Enter any two integers: 5 10
Before swapping: a = 5, b=10
After swapping: a = 10, b=10


=> Swapping program in c using function

#include<stdio.h>
void swap(int *,int *);
int main(){

    int a,b;
   
    printf("Enter any two integers: ");
    scanf("%d%d",&a,&b);

    printf("Before swapping: a = %d, b=%d",a,b);

    swap(&a,&b);

    printf("\nAfter swapping: a = %d, b=%d",a,b);
    return 0;
}

void swap(int *a,int *b){
    int *temp;
    temp = a;
    *a=*b;
    *b=*temp;
}

Sample output:
Enter any two integers: 3 6
Before swapping: a = 3, b=6
After swapping: a = 6, b=6

Program in c to print 1 to 100 without using loop

0 comments

Program in c to print 1 to 100 without using loop

#include<stdio.h>
int main(){
    int num = 1;
    print(num);
    return 0;
}
int print(num){
    if(num<=100){
         printf("%d ",num);
         print(num+1);
    }
}

Output:
Sample output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

How to convert string to int without using library functions in c

0 comments

How to convert string to int without using library functions in c
How to convert string to int without using library functions in c
#include<stdio.h>
int stringToInt(char[] );
int main(){
    char str[10];
    int intValue;
    printf("Enter any integer as a string: ");
    scanf("%s",str);
   intValue = stringToInt(str);
    printf("Equivalent integer value: %d",intValue);
    return 0;
}
int stringToInt(char str[]){
    int i=0,sum=0;
    while(str[i]!='\0'){
         if(str[i]< 48 || str[i] > 57){
             printf("Unable to convert it into integer.\n");
             return 0;
         }
         else{
             sum = sum*10 + (str[i] - 48);
             i++;
         }
    }
    return sum;
}

Sample output:
Enter any integer as a string: 123
Equivalent integer value: 123

Write a c program to find out NCR factor of given number.

0 comments

Write a c program to find out NCR factor of given number.
Write a c program to find out NCR factor of given number
#include<stdio.h>
int main(){
  int n,r,ncr;
  printf("Enter any two numbers->");
  scanf("%d %d",&n,&r);
  ncr=fact(n)/(fact(r)*fact(n-r));
  printf("The NCR factor of %d and %d is %d",n,r,ncr);
  return 0;
}
 int fact(int n){
  int i=1;
  while(n!=0){
      i=i*n;
      n--;
  }
  return i;
 }

Alogrithm:
In the mathematics nCr has defined as
nCr = n! /((n-r)!r!)

Write a c program to find out prime factor of given number.

0 comments

Write a c program to find out prime factor of given number.
Prime factor of a number in c
#include<stdio.h>
int main(){
  int num,i=1,j,k;
  printf("\nEnter a number:");
  scanf("%d",&num);
  while(i<=num){
      k=0;
      if(num%i==0){
         j=1;
          while(j<=i){
            if(i%j==0)
                 k++;
             j++;
          }
          if(k==2)
             printf("\n%d is a prime factor",i);
      }
      i++;
   }
   return 0;
}

Write a c program to find out generic root of any number.

0 comments

Write a c program to find out generic root of any number.
FIND OUT GENERIC ROOT OF A NUMBER By C PROGRAM
C program for generic root
#include<stdio.h>
int main(){
long int num,sum,r;
printf("\nEnter a number:-");
scanf("%ld",&num);
while(num>10){
sum=0;
while(num){
r=num%10;
num=num/10;
sum+=r;
}
if(sum>10)
num=sum;
else
break;
}
printf("\nSum of the digits in single digit is: %ld",sum);
return 0;
}

C code for calculation of generic root in one line
#include <stdio.h>
int main(){         
int num,x;
printf("Enter any number: ");
scanf("%d",&num);
printf("Generic root: %d",(x=num%9)?x:9);
return 0;
}

Sample output:
Enter any number: 731
Generic root: 2

Meaning of generic root:
It sum of digits of a number unit we don't get a single digit. For example:
Generic root of 456: 4 + 5 + 6 = 15 since 15 is two digit numbers so 1 + 5 = 6
So, generic root of 456 = 6

Write a c program to subtract two numbers without using subtraction operator.

0 comments

Write a c program to subtract two numbers without using subtraction operator.
Write a c program or code to subtract two numbers without using subtraction operator
#include<stdio.h>
int main(){
    int a,b;
    int sum;
    printf("Enter any two integers: ");
    scanf("%d%d",&a,&b);
    sum = a + ~b + 1;
    printf("Difference of two integers: %d",sum);
    return 0;
}

Sample Output:

Enter any two integers: 5 4
Difference of two integers: 1

Write a c program to add two numbers without using addition operator.

0 comments

Write a c program to add two numbers without using addition operator.
Write a c program to add two numbers without using addition operator
Add two numbers in c without using operator
How to add two numbers without using the plus operator in c

#include<stdio.h>
int main(){
    int a,b;
    int sum;
    printf("Enter any two integers: ");
    scanf("%d%d",&a,&b);
    //sum = a - (-b);
    sum = a - ~b -1;
    printf("Sum of two integers: %d",sum);
    return 0;
}

Sample output:
Enter any two integers: 5 10
Sum of two integers: 15

C program to reverse a number using recursion

0 comments

C program to reverse a number using recursion

#include<stdio.h>
int main(){
    int num,reverse;

    printf("Enter any number: ");
    scanf("%d",&num);

    reverse=rev(num);
    printf("Reverse of number: %d",reverse);
    return 0;
}
int rev(int num){
    static sum,r;

    if(num){
         r=num%10;
         sum=sum*10+r;
         rev(num/10);
    }
    else
         return 0;
    return sum;
}

Sample output:
Enter any number: 456
Reverse of number: 654

Write a c program to reverse any number.

0 comments

Write a c program to reverse any number.

Reverse any number using c program
Code 1:
1. Write a c program to reverse a given number
2. C program to find reverse of a number
3. C program to reverse the digits of a number
4. Reverse of a number in c using while loop
#include<stdio.h>
int main(){
    int num,r,reverse=0;

    printf("Enter any number: ");
    scanf("%d",&num);

    while(num){
         r=num%10;
         reverse=reverse*10+r;
         num=num/10;
    }
    printf("Reversed of number: %d",reverse);
    return 0;
}

Sample output:
Enter any number: 12
Reversed of number: 21

Sample Programs for C Language

0 comments

1.   Write a c program to reverse any number.
2.     C program to reverse a number using recursion
3.     Write a c program to add two numbers without using addition operator.
4.     Write a c program to subtract two numbers without using subtraction operator.
5.     Write a c program to find out generic root of any number.
6.     Write a c program to find out prime factor of given number.
7.     Write a c program to find out NCR factor of given number.
8.     How to convert string to int without using library functions in c
9.     Program in c to print 1 to 100 without using loop
10.   C program for swapping of two numbers
11.   Program to find largest of n numbers in c
12.   Write a c program to check given number is Armstrong number or not.
13.   Write a c program to check given number is prime number or not.
14.   Write a c program to check given number is strong number or not.
15.   Write a C program to check a number is odd or even.
16.   Write a c program to check given number is palindrome number or not.
17.   Write a c program to print Fibonacci series of given range.
18.   Write a c program to get factorial of given number.
19.   Write a c program to print Pascal triangle.
20.   Write a c program to generate multiplication table.
21.   Write a c program to find out largest element of an array.
22.   Write a c program to find out second largest element of an unsorted array.
23.   Write a c program to find out second smallest element of an unsorted array.
24.   Write a c program which deletes the duplicate element of an array.
25.   Write a C program to find largest and smallest number in an array
26.   Write a c program to convert decimal number to binary number.
27.   Write a C code for decimal to octal converter
28.   Easy way to convert decimal number to octal number in c
29.   Write a c program for linear search.
30.   Write a c program for binary search.
31.   Write a c program for binary search using recursion.
32.   Write a c program to find out the sum of series 1 + 2 + ….  + n.
33.   Write a c program for bubble sort.
34.   Write a c program for insertion sort.
35.   Write a c program for selection sort.
36.   Write a c program for quick sort.
37.   Write a c program for merge sort.
38.   Write a c program to convert the string from upper case to lower case.
39.   Write a c program to swap two numbers.
40.   Write a c program to swap two numbers without using third variable.

Error handling | C Programming Language Tutorial

0 comments

Error handling

It is possible that an en-or may occur during I/O operations on a file. Typical en-or situations include:
1. Trying to read beyond the end of file mark.
2. Device overflow
3. Trying to use a file that has not been opened.
4. Opening a file with an invalid file name.
5. Attempting to write to a write protected file.
6. Trying to perform an operation on a file when the file is opened for another type of operation. he standard I/O functions maintain two indicators with each open stream to show the end-of file and en-or status of the stream.

These can be interrogated and set by the following functions: 
#include <stdio.h>
void clearerr(FILE *stream);
int feof(FILE *stream);
int ferror(FILE *stream);
void perror(const char *s);
clearer clears the error and EOF indicators for the stream.

feof: returns non-zero if the stream's EOF indicator is set, zero otherwise.
Ferror: returns non-zero if the stream's error indicator is set, zero otherwise.
Perror: prints a single-line error message on the program's standard output, prefixed by the string pointed to by s, with a colon and a space appended. The error message is determined by the value of ermo and is intended to give some explanation of the condition causing the error.

For example, this program produces the error message shown:
#include <stdio.h>
#include <stdlib.h>
main()
{
fclose(stdout);
if(fgetc(stdout) >= 0)
{
fprintf(stderr, "What - no error!\n");
exit(EXIT _FAILURE);
}
ferror("fgetc");
exit(EXIT _SUCCESS);
}

/* Result */
fgetc: Bad file number

Random access files | C Programming Language Tutorial

0 comments

Random access files:

The file I/O routines all work in the same way; unless the user takes explicit steps to change the file position indicator, files will be read and written sequentially. A read followed by a write followed by a read (if the file was opened in a mode to permit that) will cause the second read to start immediately following the end of the data just written. (Remember that stdio insists on the user inserting a buffer-flushing operation between each element of a read-write-read cycle.) To control this, the Random Access functions allow control over the implied read/write position in the file. The file position indicator is moved without the need for a read or a write, and indicates the byte to be the subject of the next operation on the file.

Three types of function exist which allow the file position indicator to be. examined or changed. Their declarations and description follow.
#include <stdio.h>
/* return file position indicator * / .
long ftell(FILE *stream);
int fgetpos(FILE *stream, fpos_t *pos);
/* set file position indicator to zero * / void rewind (FILE *stream);
/* set file position indicator */
int fseek(FILE *stream, long offset,
int ptmame); int fsetpos(FILE *stream, const fpos_t *pos);

ftell returns the current value (measured in characters) of the file position indicator if stream refers to a binary file. For a text file, a 'magic' number is returned, which may only be used on a subsequent call to fseek to reposition to the current file position indicator. On failure, -1 L is returned and ermo is set.
rewind sets the current file position indicator to the start of the file indicated by stream. The file's error indicator is reset by a call of rewind. No value is returned.
Fseek allows the file position indicator for stream to be set to an arbitrary value (for binary files), or for text files, only to a position obtained from ftell, as follows:
=> In the general case the file position indicator is set to offset bytes (characters) from a point in the file determined by the value of ptrname. Offset may be negative. The values of ptmame may be SEEK_SET, which sets the file position indicator relative to the beginning of the file, SEEK_CUR, which sets the file position indicator relative to its current value, and SEEK_END, which sets the file position indicator relative to the end of the file. The latter is not necessarily guaranteed to work properly on binary streams.
=> For text files, offset must either be zero or a value returned from a previous call to ftell for the same stream, and the value ofptrname must be. SEEK_SET.
=> Fseek clears the end of file indicator for the given stream and erases the memory of any ungetc. It works for both input and output.
=> Zero is returned for success, non-zero for a forbidden request.

Note that.for ftell and fseek it must be possible to encode the value of the file position indicator into a long. This may not work for very long files, so the Standard introduces fgetpos and fsetpos which have been specified in a way that removes the problem.
fgetpos stores the current file position indicator for stream in the object pointed to by pos. The value stored is 'magic' and only used to return to the specified position for the same stream using fsetpos. fsetpos works as described above, also clearing the stream's end-of-file indicator and forgetting the effects of any ungetc operations. For both functions, on suc,cess, zero is returned; on failure, non-zero is returned and errno is set.
#include <stdio.h>
;
int main()
{
FILE * f;
f= fopen("myfile.txt", "w"); fputs("Hello World", f); fseek(f, 6,
SEEK_SET); fputs(" India", f);
fclose(f);
return 0;
}
Now the file consist of following data:
Hello India

Sample program to print the current position of the file pointer in the file using ftell()
function:
#include<stdio.h> .
void main()
{
FILE *fp;
char ch; fp=fopenG'lines.txt" ,"r"); fseek( fp,21 ,SEEK_SET); ch=fgetc(fp );
clrscr();
while(!feof(fp ))
{
printf("%c" ,ch); printf("%d",ftell(fp )); ch=fgetc(fp );
}
rewind(fp ); while(! feof( fp))
{
printf("%c" ,ch); printf("%d" ,ftell(fp)); ch=fgetc(fp );
}
fclose(fp );
}

Closing the File | C Programming Language Pdf

0 comments

Closing the File:

The input output library supports the function to close a file; it is in the following format.
f close(file -'pointer);
A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer.

Observe the following program ..
FILE *p 1 *p2;
Pl = fopen ("Input","w");
p2 = fopen ("Output" ,"r");
……
……
fclose(p1); fclose(p2)

The above program opens two files and closes them after all operations on them are completed, once a file is closed its file pointer can be reversed on other file.
Reading a character from a file and writing a character into a file ( getc () and putc ()' functions)
The getc and putc functions are analogous to getchar and putchar functions and handle one character at a time. The putc function writes the character contained in character variable c to the file associated with the pointer fp1. ex putc(c,fpl); similarly getc function is used to read a character from a file that has been open in read mode.
c=getc(fp2).
The program shown below displays use of a file operations. The data enter through the keyboard and the program- writes it. Character by character, to the file input. The end of the data is indicated by entering an EOF character, which is control-z. the file input is closed at this signal.

Sample program for using getc and putc functions*/.:
#include< stdio.h >
void mainO
{
FILE *fl;
printf("Data input output");
fl =fopen("Input","w"); /*Open the file Input*/
while«c=getcharO)!=EOF) /*get a character from key board*/
putc( c,fl); /*write a character to input* /
fclose(fl); /*close the file input* / printf("Data output");
fl =fopen("INPUT" ,"r"); /*Reopen the file input* /
while« c=getc(fl ))!=EOF)
printf("%c",c );
fclose(fl );
}

4. Reading a integer from a file and writing a integer into a file ( getw() and putw() functions)
These are integer-oriented functions. They are similar to get c and putc functions and are used to read and write integer values. These functions would be useful when we deal with only integer data.
The general forms of getw and putw are:
putw(integer,fp );
getw(fp);

/*Example program for using getw and putw functions * 
/ #include< stdio.h >
void main( )
{
FILE *fl, *f2, *f3;
int number,i;
printf("Contents of the data filenn");
fl =fopen("DA T A","W");
for(i=l;i< 30;i++)
{
printf("enter the number");
scanf("%d" ,&number);
if(number= =-l)
break;
putw (number,fl );
}
fclose(fl);
fl =fopen("DA T A","r");
f2=fopen("ODD", "w");
f3 =fopen ("EVEN", "w");
while((number=getw(fl))!=EOF)/* Read from data file*/
{
if(number%2=0)
putw(number,f3);/*Write to even file*/
else
putw(number,f2);/*write to odd file*/
}
fclose(fl );
fclose(f2);
fclose(f3);
f2=fopen("O DD" ,"r");
f3 =fopen("EVEN", "r");
printf("nnContents of the odd filenn");
while(number=getw(f2))! = EO F)
printf("%d" ,number);
printf("nnContents of the even file");
while(number=getw(f3))! = EPF)
printf("%d" ,number);
fclose(f2);
fclose(f3);
}

5. fscanf() and fprintf() functions:
The fprintf and fscanf functions are identical to printf and scanf functions except that they work on files. The first argument of theses functions is a file pointer which specifies the file to be used. The general form of fprintf is fprintf(fp,"control string", list);
Where fp id a file pointer associated with a file that has been opened for writing. The control string is fiJe output specifications list may include variable, constant and string.
fprintf(fl ,%s%d%f",name,age,7 .5);
Here name is an array variable of type char and age is an int variable
The general format of fscanf is fscanf(fp,"controlstring" ,list);
This statement would cause the reading of items in the control string.

Example:
fscanf( fL,"5 s%d" ,item, & quantity");
Like scanf, fscanf also returns the number of items that are successfully read.
*Program to handle mixed data types*
#include< stdio.h >
main()
{
FILE *fp;
int num,qty,i;
float price,value;
char item[10],
flemupe[10];
printf("enter the filename");
scanf("%s" ,filename);
fp=fopen( filename, "w");
printf("Input inventory data");
printf("Item namem number price quantity");
for (i=l;i< =3;i++)
{
fscanf( stdin, "%s%d %f%d" ,item,&number ,&price,&quality);
fprintf( fp, "%s%d%fl,lod" ,itemnumber, price, quality );
}
fclose (fp);
fprintf( stdout, "nn");
fp=fopen( filename, "r");
printf ("Item name number price quantity value");
for(i=l;i< =3;i++)
{
fscanf( fp, "%s%d %f1l,lod" ,item, &number ,&prince, &quality);
value=price*quantity;
fprintf("stdout, "%s%d%f1l,lod %dn" ,item, number ,price, quantity , val ue);
} fclose(fp );
}

6. fgetc () and fputc() functions:
fgetc() function is similar to getc() function. It also reads a character and increases the file pointer position. If any error or end of the file is reached it returned EOF.
fputc() function writes the character to the file shown by the file pointer. It also increases the file pointer position.
Sample program to write text to a file using fputc() and read the text from the same file using fgetc()
#include<stdio.h>
void main()
{
FILE *fp; char c;
fp=fopen("lines. txt", "w");
while( ( c=getcharO 1 =' *.') fputc( c,fp);
fclose(fp);
fp=fopen("lines. txt" ,"r");
while(( c=fgetc(fp ))!=EOF) printf("%c",c );
fclose(fp);
}

7. fgets() and fputs() functions:
fgets() function reads string from a file pointed by file pointer. It also copies the string to a memory location referred by an array.
fputs() function is useful when we want to write a string into the opened file .
Sample program to write string to a file using fputs() and read the string from the same file using fgets()
#include<stdio .h> void main()
{
FILE *fp;
Char file [ 12],text[ 50];
fp = fopen("line. txt" ,"w");
printf("enter text here ");
scanf("%s" , te~t); fputs(text,fp );
fclose( fp );
fp = fopen("line. txt", "r");
if(fgets(text,50,fp )!=NULL)
while(text[i] !='\O')
{
putchar(text[i]);
i++;
}
fclose(fp );
getch();
}

8. fread() and fwrite () functions
You can regard an array, or an array of structured variables, as simply a block of memory of a particular size. The input/output routines provide you with routines that you can call to drop a chunk of memory onto a disk file with a single function call.
However, there is one thing you must remember. If you want to store blocks of memory in this way the file must be opened as a binary file. What you are doing is putting a piece of the program memory out on the disk. You do not ~ow how this memory is organised, and will never want to look at this, so you must open the file as a binary file. If you want to print or read text you use the fprintf or scanf functions.
The function fwrite sends a block of memory out to the specified file. To do this it needs to know three things; where the memory starts, how much memory to send, and the file. to send the memory to. The location ofthe memory is just a simple pointer, the destination is a pointer to a FILE which has been opened previously, the amount of memory to send is given in two parts, the size of each chunk, and the number of chunks. This might seem rather long wjnded, but is actually rather sensible. Consider:
typedef struct {
char name [30] ;
char address [60] ;
int account ;
int balance ;
int overdraft ;
} customer;
customer Hull_Branch [100] ;
FILE * Hull_File;
fwrite ( Hull_Branch, sizeof ( customer), 1 00, Hull_File) ;

The first parameter to fwrite is the pointer to the base of the array of our customers.
The second parameter is the size of each block to save. We can use sizeof to find out the size of the structure. The third parameter is the number of customer records to store, in this case 100 and the -final parameter is the file which we have opened. Note that if we change the number of items in the customer structure this code will still work, because the amount of data saved changes as well.
The opposite of fwrite is fread. This works in exactly the same way, but fetches data from the file and puts it into memory:
fread ( Hull_Branch, sizeof ( customer), 1 00, Hull_Data) ;
If you want to check that things worked, these functions return the number of items that they transferred successfully:
if( fread (Hull_Branch, sizeof( customer), 100, Hull_Data) < 100) {
printf ( "Not all data has been read!\n\n" ) ; }
}

Sample program using fread() and fwrite() functions
#include<stdio.h>
struct student
{
char name[20];
int age;
}stud[5];
void main()
{
FILE *fp;
int i,j=0,n;
char str[15];
fp=fopen("line. txt" ,"rb");
printf("enter the number of records");
scanf("%d",n);
for(i=O;i<n;i++ )
{
scanf("%s",stud[i] .name);
scanf("%d",stud[i] .age);
}
}
whileG<n)
{
fwrite( &stud,size( stud), 1 ,fp);
j++;
}
}
fclose(fp );
fp=fopen ("line. txt", "r");
j=0;
while(j<n)
{
fread( &stud,sizeof( stud), 1 ,fp);
printf("%s %d" ,stud[j] .name,stud[j] .age);

fclose(fp ); 
}

Opening a File | C Programming Language Tutorial

0 comments

Opening a File:

C communicates with files using a new data type called a file pointer. This type is defined within stdio. h, and written as FILE *. A file pointer called output_file is declared in a statement like  FILE *output_file;
If we want to store data in a file into the secondary memory, we must specify certain things about the file to the operating system. They include the filename, data structure, purpose.
The general format of the function used for opening a file is FILE *fp;
fp = fopen("filename", "mode");
The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier, File is a structure that is defined in the I/O Library. The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp. This pointer, which contains all the information about the file, is subsequently used as a communication link between the system and the program.
The second statement also specifies the purpose of opening the file. The mode does this job.
r     open the file for read only.
w    open the file for writing only.
a     open the file for appending data to it.
r+   open an existing file for update (reading and writing)
w+  create a new file for update. If it already exists, it will be overwritten.
a+   open for append; open for update at the end of the file

Consider the following statements:
FILE *pl, *p2;
pI =fopen("data" ,"r");
p2=fopen("results", "w");

In these statements the pI and p2 are created and assigned to open the files data and results respectively the file data is opened for reading and result is opened for writing. In case the results file already exists, its contents are deleted and the files are opened as a new file. If the data file does not exist error will occur.


FILES | C Programming Language Tutorial

0 comments

FILES

A file is a place on disk where group of related data are stored. C supports a number of functions that have the ability to perform basic file operations, which
include:
=> Naming a file
=> Opening the file
=> Reading data from the file
=> Writing data to the file
=> Closing the file
There are two distinct ways to perform file operations in C. The first one is known as the low level I/O and uses UNIX system calls. The second method is referred to as the high level I/O operation and uses functions in C's standard I/O library.

FILE TYPES:
DOS treats files in two different ways viz., as binary or text files. Almost all UNIX Systems do not make any distinction between the two. If a file is specified as the binary type, the file I/O functions do not interpret the contents of the file when they read from or write to the· file. But, if the file is specified as the text type the I/O functions interpret the contents of the file.
The basic differences in these two types of files are:
I. ASCII 0xla is considered an end-of-file character by the file I/O function when reading from a text file and they assume that the end of the file has
been reached.
II. In case of DOS a new file is stored as the sequence 0*0d 0*0a on the disk in case of text files. UNIX stores \n as 0* 0a both on disk and in memory.

Union | C Programming Language Tutorial pdf

0 comments

Union:-

Union is a data type in „C? which allows an ruelay of more than none Var in the same memory arc i.e. using the memory space for different van at same place.
Syntax:-
union uni-name
{
type Var 1;
type Var 2;
}< union Var> ;
All var inside an union share storage space. The compiler will allocate sufficient storage for the union var to accommodate the largest element in the union .Other element of the union use the same space (as it is using same space) it is different from structures.

Declining var & pointer to unions:-
union name
{
char name [40];
char id [20];
} id *ptr 2;

Difference b/w structures & unions:
structure
{
char name [25]
Int idno;
float sal;
} emp;
union
{
char name [25]
Int idno;
float sal;
} desc;
void main()
{
printf (“ size of struct is %d” size of ( emp));
printf (“size of union is %d”, size of (desc));
}

Operations on union members:
Only one member of a union can be accessed at a time i.e. because at every instance only one of the union var. will have a meaningful value, only that var is read.

Operations an unions:-
Unions have all the features provided y a Structure which are a conveyance of memory sharing properties of a union. This is evident by the following operations union which are legal.
1. Union var. can be assigned to another union var
2. Union Var can be passed to a function as parameters.
3. The address of the union var. can be extracted by using address of operator.
4. A function can accept & retune a union of a ptr to a union

Scope of a Union:
void main ( )
{
union
{
int i;
char c;
float f;
};
printf { “ i = % d”, i);
}

Output:-
/* compiler dependent* /

Fields in structure:
To allocate memory in bits. Bit fields are treated as unsigned integers
Syntax:-
structure <tag>
{
unsigned <var> : value ;/*rep of bit fields */
};

Ex:
structure with_bits
{
unsigned first :5;
unsigned second :9;
};
Total 14, but it goes to 16 as we can?t have 14 bit memory
void main ( )
{
Union
{
int i ;
};
i = 0;/*second =0 */
b. first =9; /* second =0*/
}

Structures & pointers | C Programming Language

0 comments

Structures & pointers:-

So far we have seen that pointer is a variable that hold the memory address of other var. of basic data type such as integer, float, char etc. A pointer can also be used in a program to hold the address of heterogeneous type of var .i.e. structure var. pointer along with structure are used to make linked lists, binary trees etc.
Ex:-
strtuct data
{
char n[10]
---
---
};
struct data * ptr;
*ptr is a ptr var.
Which holds the address of the structure named data?
The ptr is declared same as any object of a struct. Now, this ptr struct var can be accessed & processed by one of the following given two methods.

1) Any field of the structure can be accessed as:
(*ptr name ). Field name =var;
Ex:-
void main ()
{
struct data
{ int a ; float b; char c; };
struct data * ptr;
(*ptr) . a =100;
(*ptr) . b =20.9;
(*ptr). C =?m?;
}
The pointer to struct is expressed using a dashed line followed by (>) sign.
ptr name – >field name = var;

=> wap to use ptr s in structures using 2 methods
void main ()
{
struct data
{ int a; float b; char c ; };
struct data * ptr;
ptr a = 100;
ptr b = 20.9;
ptr c = „m? ;
-----
-----
};

Uses of structures:-
Structures are useful in database management i.e. to main to data about employees, but use of structures much beyond data base management. They can be used for.
1. Changing the size of cursor.
2. Clearing the eonents of the screen.
3. Drawing any graphical shape on the screen.
4. Placing the cursor at appropriate position on the screen.
5. Receiving a key from the keyboard.
6. Checking the memory size of the computer finding out the list of equipment attached to the computer.
7. Formatting a floppy.
8. Hiding a file from directly.
9. Display the directory of a disk.
10. Sending the o/p to printer.
11. Interacting with the mouse.

Terms within structures:-
ptr : can be used as a member of the structure.
Ex :
void main ()
{
struct student
{
int rno, *ptr;
};
struct student s;
s.ptr = * s.rno;
*s.ptr = 10;
printf (”rno = % d/n”, s.rno);
}

Structures & functionctions:-
Structures may be passed as an argument to a functionction in diff ways. We can pass individual members, who structures or struct ptr. To the function, similarly, a function. Can return either a struct. Member or a whole structure van or a ptr. To structure.
1). Passing struct members as arguments.
2). Passing struct var. as argument.
3). Passing ptr. To struct as argument.
4). Returning a struct var. from function.
5). Returning a ptr. To struct from function.
6). Passing away of struct as argument.

Note :-
1). All the change made in the away of struct. Inside the called function. Will be visible in the calling function .
2). If the size of a struct is very large then it is not efficient to pass the whole struct. To function.
3) It is better to sent the address of the structure which will improve the execution speed.
4) Passing individual members to a function. Become cumbersome when there are many members & the relationship b/w the members is also last so we can pass the whole structure as an argument
5) As any other van. Structure .van is return the retuned value can be assigned to a structure of the appropriate time.
6) As we pass away to a function away of Structure. Can also be passed to a function where each ele. of away is of Structure type.

Array of structures | C Study Material for freshers

0 comments

Array of structures:-

A structure is simple to define if there are only one or two element, but incase there are too many objects needed for a structure, for ex. A structure designed to show the data of each student of the class, then in that case, the away will be introduced. A structure declaration using array to define object is given below.
Stuct student
{
Char name [15];
Int rollno;
Char sex;
};
Student data[50];

Initializing array of structures:-
It is to be noted that only static or external variable can be initialized.
Ex: -
struct employee
{
int enum;
Char sex;
Int sal;
};
Employee data [3] = { { 146, „m?, 1000 },
{ 200, 'f', 5000},
{ 250, 'm',10000} };
If incase, the structure of object or any element of struct are not initialized, the compiler will automatically assigned zero to the fields of that particular record.
Ex: employee data [3] = { { 146,'m'} ,{ 200, 'f' },{250 ,'m'}};
Compiler will assign:-
Data [0] sal=0; data [1].sal=0; data [2]. Sal=0;

=>WAP to initialize the array of structure members & display
void main ()
{
int i;
Struct student
{
long int rollno;
char sex;
float height;
float weight;
};
struct student data [3] = { {121,'m',5.7,59.8},
{122,'f',6.0,65.2},
{123,'m', 6.0, 7.5} };
clrscr ();
printf (“the initialized contents are:”);
For ( i=0; i< =2; i++)
{
printf (“%d/n ** Record is \n “, data [i].rollno);
printf (“% c\n “, data [i] .sex);
printf (“%f\n”, data [i].height);
printf (“%f\n”, data [i]. weight);
}
}

Arrays with in the structures:-
Arrays can be used within the structure along with the member declaration. In other words, a member of a structure can be an array type also.
struct emp
{ char name [30] ;// 30 characters array .
char dept [30];
int sal;
char add[50];
};

Structures and Unions Introduction

0 comments

STRUCTURES & UNIONS

Data in the array is of the same composition in native a fan as type is concerned. In real life we need to have different data types for ex. To maintain the employee information. We should have information such as name, age, qualification, salary etc. here to maintain the information of employee dissimilar data types required. Name & qualification are char data type age is integer, & salary is float. All these data types cannot be expressed in a single away. One may think to declare different always for each data type. Hence, always cannot be useful her for tackling such mixed data types, a special feature is provided by C, known as Structure.
Structure is a collection of heterogeneous type of data i.e. different types of data. The various individual components, in a structure can be accessed is processed separately. A structure is a collection of variables referenced under a name, providing a convenient means of keeping related information. A structure declaration forms a template that may be used to create structure objects.

Difference between structure is arrays :-
                 Structure                                                     Arrays
1. Collection of heterogeneous types     1. Collection of homogeneous types of of data i.e. different                                                               types of data. data i.e. same types of data
2. A structure element component         2. An away it is referred by its position of structure has a                                                                 unique name. i.e. index.
The point on which array & structures can be similar is that both array & structure must be definite number of components.

Features of Structures:-
To copy elements of one array to another array of same data type elements are copied one by one. It is not possible to copy elements at a time. Where as in structure it is possible to copy the contents of all structure elements of different data types to another structure var of its type using assignment (=) operator. It is possible because structure elements are stored in successive memory locations. Nesting of structures is possible.
It is also possible to create structure pointers. We can also create a pointer. Pointing to structure elements.
For this we require ' -> ' operator.

Declaration of structure :-
Struct Struct_type
{
type val 1; // members of structures
type val 2;
};

After defining structure we can create variables as given Struct struct_type v1, v2, v3.
The declaration defines the structure but this process does not allocate memory. The memory allocation takes only when var.r declared
Example:-
Struct book
{
Char book [30];
int pages;
float price;
};
Strict book bk1, bk2;
Initialization:-
Struct book bk1= {“siri”, 500, 38500};
All the members of structure are related to variable bk1 structure – var. member i.e. bk1.book
The period (.) sign is used to access the struct members.
WAP to define & initialize a structure & its variables
main ( )
{
Strict book
{
char book [30];
int pages;
float price;
};
struct book bk1 = { “c++”, 300, 285};
clrscr ( );
printf (“ \n Book name : %s “ , bk1.book);
printf (“\n No of pages :%d “,bk1.pages);
printf (“\n book price :%f “,bk1.price);
}
Out put:
Book name : C ++
No of pages : 300
Book Price : 285

Structure within structure (nested):-
We can take any data type for declaring structure members like int, float, char etc. In the same way wee can also take object of one structure as member in another structure.
The syntax as follows:-
struct s1
{
Type var1;
Type var2;
};
struct s2
{
Type v3;
Strict s1 v4;
Strict s2 v5;
};
struct s2 p;

=> WAP to enter the records of no of students & then display them using nested structure
# include <stdio.n> # define max 300
Struct data
{
int day;
int month;
int year;
};
Struct student
{
char name [30];
long int rollno;
struct data dob;
};
struct student bio [max];
void main ()
{
int i, n;
printf (“ How many student data required:”);
scanf (“%d”,&n);
for(i=0;i<=n-1; i++)
{
printf (“Record. No : % d\n”, i+1);
printf (“Student name :”); sf(“ %s”,bio[i].name);
printf (“Roll no :”) ; sf (“ %d “, bio [i].rollno);
pf (“date of birth”); pf (“\n Day”);
printf (“%d”, &bio [i].dob.day);
printf (“ month:”); sf (“%d”, &bio[i].dob.month)
printf (“year:”) ; sf (“% d”, & bio[i].dob.year).
}
printf (“ The entered contents are :”);
for (i=0;i <=n-1;i++)
{ printf (“\n Record No : % d”, i+1).
printf (“\n Student name : % s”, bio [i].name);
printf (“\n Roll no : % d “, bio [i] . rollno);
printf (“\n Date of birth “);
printf (“\n day : % d”,bio[i].dob.day);
printf (“\n month : % d”, bio [i].dob. month);
printf (“\n year : % d”, bio [i].dob.year);
}
}

Pointer Arithmetic | C Language Study Material pdf

0 comments

Pointer Arithmetic:

An integer operand can be used with a pointer to move it to a point / refer to some other address in the memory.
consider an int type ptr as follows
Assume that it is allotted the memory address 65494 increment value by 1 as follows .
mptr ++;             or   ++ mptr;
mptr = mptr +1;  or   mptr + =1 ;
++ and - - operators are used to increment, decrement a ptr and commonly used to move the ptr to next location. Now the pointer will refer to the next location in the memory with address 64596.
C language automatically adds the size of int type (2 bytes) to move the ptr to next memory location.
mptr  = mtpr + 1
         = 645.94 + 1 * sizeof (int)
         = 65494 + 1 * 2
Similarly an integer can be added or subtract to move the pointer to any location in RAM. But the resultant address is dependent on the size of data type of ptr.
The step in which the ptr is increased or reduced is called scale factor.Scale factor is nothing but the size of data type used in a computer.
We know that in a pc,
The size of float = 4
char = 1
double = 8 and so on
Ex: float *xp; (assume its address = 63498)
xp = xp + 5;
Will more the ptr to the address 63518
? 63498 + 5 * size of (float0
? 63498 + 5*4
? 63498+20
? 63518

Rules for pointer operation:
The following rules apply when performing operations on pointer variables
1. A pointer variable can be assigned to address of another variable.
2. A pointer variable can be assigned the values of another pointer variables.
3. A pointer variable can be initialized with NULL or 0 value.
4. A pointer variable can be prefixed or postfixed with increment and decrement operator.
5. An integer value may be added or subtracted from a pointer variable.
6. When 2 pointers points to the same array, one pointer variable can be subtracted from another.
7. when two pointers points to the objects of save data types, they can be compared using relational .
8. A pointer variable cannot be multiple by a constant.
9. Two pointer variables cannot be added.
10. A value cannot be assigned to an arbitrary address.

Pointer and Character array | C Programming Language Material pdf

0 comments

Pointer and Character array

Pointers are very useful in accessing character arrays. The character strings can be assigned with a character pointer.
Ex:
char array[ ] = “Love India”; array version
char *p= “Love India”; pointer version
Here p points to the first character in a string.
Ex1:
#include<stdio.h>
#include<conio.h>
main()
{
int i;
char *p= “ Love India”;
clrscr();
while (*p! = '\0')
{
printf (“ %c “, *p);
“Programming with C” course material
Department of CSE, GIT, GU Page 141
p++;
}
}

Output: Love India

Ex2:
# include <stdio.h>
# include <conio.h>
int slen(char *);
main ( )
{
char name[50];
int k;
printf (“ enter string: “);
gets (name);
k = slen (name);
printf (“ the string length is %d ” , k);
}
int slen (char *s)
{
int n;
for (n=0; (*s) != '\0'; n++)
s++;
return (n) ;
}

Output:
enter string: College
the string length is 7

Pointer and arrays | C Programming Language Tutorial pdf

0 comments

Pointer and arrays :

Pointer can be used with array for efficient programming. The name of an array itself indicates the stating address of an array or address of first element of an array.
That means array name is the pointer to starting address or first elements of the array.
If A is an array then address of first element can be expressed as &A[0] or A.The compiler defines array name as a constant pointer to the first element.

Ex: 
#include<stdio.h>
#include< conio.h>
void disp (int *, int);
main( )
{
int i, a[10],n;
printf (“ enter the size of an array:”);
scanf (“%d”, &n);
printf (“ enter the array elements:”);
for (i=0; i<n; i++)
scanf (“%d”, &a[i]);
disp (a,n);
printf(“ array elements after sorting ” );
for(i=0;i<n;i++)
printf (“%d”, a[i]);
}
void disp(int a[ ], int n)
{
int i,j, temp;
for (i=0; i<n; i++)
for (j=0; j<n; j++)
{
if (a[j] > a[i])
{
temp = a[ j ];
a[ j ] = a[ i ];
a[ i ] = temp;
}
}
}

Output :
enter the size of an array: 5
enter the array elements: 20 30 10 50 40
array elements after sorting: 10 20 30 40 50

Pointer and functions | C Programming Language Material pdf

0 comments

Pointer and functions

1. Pointers can be passed as argument to a function definition.
2. Passing pointers to a function is called call by value.
3. In call by reference what ever changes are made to formal arguments of the function definition will affect the actual arguments in calling function.
4. In call by reference the actual arguments must be pointers or references or addresses.
5. Pointer arguments are use full in functions, because they allow accessing the original data in the calling program.

Ex1: 
void swap (int *, int *);
main ( )
{
int a=10, b=20;
swap(&a, &b); /* a,b are actual parameters */
printf (“ %d %d ”, a ,b);
}
void swap (int *x , int *y) /* x,y are formal parameters */
{
int t;
t = *x;
*x=*y;
*y=t;
}

Output: 20 10

Ex 2:
# include < stdio.h>
# include < conio.h>
void copy (char *, char *);
main ( )
{
char a[20], b[20];
printf (“ enter string a:”);
gets(a);
printf (“ enter string b:”);
gets(b);
printf (“ before copy “ );
printf (“ a=%s and b=%s ”, a , b);
copy(a ,b);
printf (“after copy “);
printf (“ a=%s and b=%s”, a , b);
}
void copy (char *x, char *y)
{
int i=0;
while ((X[i]=Y[i]) != „\0?)
i++;
}

Output: 
enter string a: computer
enter string b: science
before copy
a=computer and b= science
after copy
a=science and b=science

Introduction to Pointers | C Programming Language Material pdf

0 comments

INTRODUCTION:

When variables are declared memory is allocated to each variable.
C provides data manipulation with addresses of variables therefore execution time is reduced. Such concept is possible with special data type called pointer. A pointer is a variable which holds the address of another variable or identifier this allows indirect access of data.

DECLARATION:
1. To differentiate ordinary variables from pointer variable, the pointer variable should proceeded by called „value at address? operator. It returns the value stored at particular address. It is also called an indirection operator( symbol * ).
2. Pointer variables must be declared with its type in the program as ordinary variables.
3. Without declaration of a pointer variable we cannot use in the program.
4. A variable can be declared as a pointer variable and it points to starting byte  address of
any data type.

SYNTAX:
Data type *pointer variable;

The declaration tells the compiler 3 things about variable p
a) The asterisk (*) tells that variable p is a pointer variable
b) P needs a memory location
c) P points to a variable of type data type.

Ex:
int * p, v;
float *x;
In the first declaration v is a variable of type integer and p is a pointer variable.
             V stores value p stores address
In the 2nd declaration x is a pointer variable of floating point data type.

2) Pointer variables are initialized by p= &v, it indicates p holds the starting address
of
integervariable v.
int v=20,*p;
p=&v; /*address of v stored in p*/
  V      p
  20    1000
Let us assume that address of v is 1000.
This address is stored in p. Now p holds address of v now *p gives the value stored at the address pointer by p i.e *p=20.

IMPORTANT POINTS:
1. A pointer variable can be assigned to another pointer variable, if both are pointing to the same data type.
2. A pointer variable can be assigned a NULL value.
3. A pointer variable cannot be multiplied or divided by a constant.
Ex: p*3 or p/3 where p is a pointer variable
4. One pointer variable can be subtracted torn another provided both winters points to Elements on same away.
5. C allows us to add integers to or subtract integers from pointers.
Ex: p1+4, p2-2, p1-p2
If both p1, p2 are pointers to same way then p2-p1 gives the number of elements between p1,p2
6. Pointer variable can be intermingled or decremented p++ & p- -
The values of a variable can be released in to way
1.by using variable name
2.by using adders.

Disadvantages:
1. Unless pointer is defined and initialized properly use of pointers may lead to disastrous situations.
2. Using pointers sometimes be confusions.
Program:
#incude < stdio.h>
main ( )
{
int x = 10, * p1, *p2, *p3;
P1=p2=p3=&x;
printf (“%d”,*p1);
printf (“% d”,*p2);
printf (“%d”,*p3);
printf (“%d”, x);
printf (“%d”,*(& x));
}

Output : 10 10 10 10 10

Void Pointers :
We can declare a pointer to be of any data type void and can assign a void pointer to any other type.
Ex : 
int x:
void p;
p= &x;
*p = 27
printf(“%d”,*p);
It given error because the pointer p is of type void and cannot hold any value.
So we have to type cast the pointer variable from one type to other type.
int x = 27;
void *p;
p=&x;
printf (“ %d”, * ((int*)p));
Output is 27

The statement (int *)p makes p to become an integer type
Ex:
#include < stdio.h>
#include < conio.h>
main()
{
int x = 27;
void *p;
p= &x;
printf (“value is = %d”, * ((int *)p));
}

Output : Value is 27


 

C Programming Language Interview Questions and Answers Tutorial for beginners. Copyright 2013 All Rights Reserved