March 2018


STRUCTURE IN C


A structure is a user-defined data type available in C that allows to combining data items of different kinds. Structures are used to represent a record.
Defining a structure: To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member. The format of the struct statement is as follows:
   struct [structure name]
   {
       member definition;
       member definition;
       ...
       member definition;
   };


UNION IN C

A union is a special data type available in C that allows storing different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple purposes.

Defining a Union: To define a union, you must use the union statement in the same way as you did while defining a structure. The union statement defines a new data type with more than one member for your program. The format of the union statement is as follows:

    union [union name]
    {
       member definition;
       member definition;
       ...
       member definition;
    };


Similarities between Structure and Union


  1. Both are user-defined data types used to store data of different types as a single unit.
  2. Their members can be objects of any type, including other structures and unions or arrays. A member can also consist of a bit field.
  3. Both structures and unions support only assignment = and sizeof operators. The two structures or unions in the assignment must have the same members and member types.
  4. A structure or a union can be passed by value to functions and returned by value by functions. The argument must have the same type as the function parameter. A structure or union is passed by value just like a scalar variable as a corresponding parameter.
  5. ‘.’ operator is used for accessing members.


Differences
Structure
Union
Keyword
The keyword struct is used to define structure.
The keyword union is used to define Union.
Size
When a variable is associated with a structure, the compiler allocates the memory for each size of its member. The size of the structure is greater than or equal to the sum of the sizes of its members.
When a variable is associated with a union, the compiler allocates the memory by considering the size of the largest memory. So, the size of the union is equal to the size of the largest member.
Memory
Each member within a structure is assigned a unique storage area of location.
Memory allocation is shared by individual members of the union.
Value Altering
Altering the value of a member will not affect other members of the structure.
Altering the value of any of the members will alter other members' values.
Accessing members
Individual members can be accessed at a time.
Only one member can be accessed at a time.
Initialization
Several members of a structure can be initialized at once
Only the first member of a union can be initialized.

At last, I think, the structure is better because as memory is shared in union ambiguity is more.

Structure 

  Arrays are used to store large set of data and manipulate them, but the disadvantage is that all the elements stored in an array are to be of the same data type. If we need to use a collection of different data type items, it is not possible using an array. When we require using a collection of different data items of different data types, we can use a structure.  Structure is a method of grouping data of different types.  A structure is a convenient method of handling a group of related data items of different data types.  
Structure declaration: 
General format:   
struct tag_name{          
data type member1;   
data type member2;   
…   
};

C Program to Store Information in Structure and Display it

#include <stdio.h>
struct student
{
    char name[50];
    int roll;
    float marks;
} s[10];

int main()
{
    int i, n;
    printf("Enter how many students marks you want to store.\n");
    scanf("%d", &n);

    printf("Enter information of students:\n");

    // storing information
    for (i = 0; i < n; ++i)
    {
        s[i].roll = i + 1;

        printf("\nFor roll number%d,\n", s[i].roll);

        printf("Enter name: ");
        scanf("%s", s[i].name);

        printf("Enter marks: ");
        scanf("%f", &s[i].marks);

        printf("\n");
    }

    printf("Displaying Information:\n\n");
    // displaying information
    for (i = 0; i < n; ++i)
    {
        printf("\nRoll number: %d\n", i + 1);
        printf("Name: ");
        puts(s[i].name);
        printf("Marks: %.1f", s[i].marks);
        printf("\n");
    }
    return 0;
}

C Programming | Fibonacci Series

The phrase, “the Fibonacci sequence” usually refers to a set of numbers that starts as {0, 1, 1, 2, 3, 5, 8, 13, 21…}. At least, “The Life and Numbers of Fibonacci” starts with “zero and one”. Many others would skip the zero and simply start with “one and one”, but that does not matter.
This sequence is created by following two rules:
  • The first two numbers are 0 and 1.
  • The next number is the sum of the two most recent numbers.

Actually, one must perform rule #2 over and over again, until one runs out of time, patience, paper or ink in the pen.
So, constructing the Fibonacci sequence starts from 1=1+0, then 2=1+1, then 3=2+1, then 5=3+2, 8=5+3, and so on.

C Program for Fibonacci Series

#include <stdio.h>
#include <conio.h>

int fibonacci(int term);
int main()
{
    int terms, counter;
    printf("Enter number of terms in Fibonacci series: ");
    scanf("%d", &terms);
    /*
     *  Nth term = (N-1)th therm + (N-2)th term;
     */
    printf("Fibonacci series till %d terms\n", terms);
    for (counter = 0; counter < terms; counter++)
    {
        printf("%d ", fibonacci(counter));
    }
    getch();
    return 0;
}
/*
 * Function to calculate Nth Fibonacci number
 * fibonacci(N) = fibonacci(N - 1) + fibonacci(N - 2);
 */
int fibonacci(int term)
{
    /* Exit condition of recursion*/
    if (term < 2)
        return term;
    return fibonacci(term - 1) + fibonacci(term - 2);
}


C Code to Find Fibonacci Series 


#include <stdio.h>
int main()
{
    int i, first = 0, second = 1, third, n;
    printf("Enter number of terms \n");
    scanf("%d", &n);
    printf("The First terms of fibonisse series are:");
    for (i = 0; i < n; i++)
    {
        if (i <= 1)
        {
            third = i;
        }
        else
        {
            third = first + second; // This changes the values.
            first = second;
            second = third;
        }
        printf("%d\n", third);
    }
    return 0;
}

Introduction To Pointer

A Pointer in C language is a variable which holds the address of another variable of same data type.
Pointers are used to access memory and manipulate the address.
Pointers are one of the most distinct and exciting features of C language. It provides power and flexibility to the language. Although pointers may appear a little confusing and complicated in the beginning, but trust me, once you understand the concept, you will be able to do so much more with C language.

C Program to change the address of entered number using pointer and function


#include <stdio.h>
#include <string.h>
void exchange(int *, int *);
int main()
{
    int num1, num2;
    printf("Enter the number to be exchanged\n");
    scanf("%d%d", &num1, &num2);
    printf("Before exchanging: \nnum1=%d num2=%d\n", num1, num2);
    exchange(&num1, &num2);
}
void exchange(int *num1, int *num2)
{
    int temp;
    temp = *num1;
    *num1 = *num2;
    *num2 = temp;
    printf("After Exchanging:\nnum1=%d num2=%d", *num1, *num2);
}

C program to transpose the matrix

#include <stdio.h<

int main()

{

    int a[10][10], i, j, row, col, trans[10][10];

    printf("Enter no. of rows:");

    scanf("%d", &row);

    printf("Enter no. of columns:");

    scanf("%d", &col);

    printf("Enter elements of matrix:");

    for (i = 0; i < row; i++)

    {

        for (j = 0; j < col; j++)

        {

            scanf("%d", &a[i][j]);
        }
    }

    printf("\nThe given matrix is :\n");

    for (i = 0; i < row; i++)

    {

        for (j = 0; j < col; j++)

        {

            printf("%d\t", a[i][j]);
        }

        printf("\n");
    }

    printf("\nThe matrix after transpose is :\n");

    for (i = 0; i < row; i++)

    {

        for (j = 0; j < col; j++)

        {

            trans[i][j] = a[j][i];

            printf("%d\t", trans[i][j]);
        }

        printf("\n");
    }
}
#include<stdio.h>
#include<string.h>

int main()
 {
   char str[100], rev;
   int i=0,c,j;
   printf("Enter the string :\n");
   gets(str);
   j = strlen(str)-1;
   while (i < j)
   {
  rev = str[i];
      str[i] = str[j];
      str[j] = rev;
      i++;
      j--;
   }

   printf("\nReverse string is\n%s",str);
   return 0;
}

OUTPUT

C program to reverse the given word using string

for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax

The syntax of a for loop in C programming language is −

for(init; condition; increment){
 statement(s);
}


Here is the flow of control in a 'for' loop −

  • The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
  • Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop.
  • After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.

 

The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates

#include <stdio.h>
int main()
{
    int rows, i, j, number= 1;
    printf("Enter number of rows: ");
    scanf("%d",&rows);
    for(i=1; i <= rows; i++)
    {
        for(j=1; j <= i; ++j)
        {
            printf("%d ", number);
            ++number;
        }
    printf("\n");
    }
return 0;
}

OUTPUT

C program to print pattern of Floyd's triangle

#include <stdio.h>
int main()
{
    int i, j;
    char input, alphabet = 'A';

    printf("Enter the uppercase character you want to print in last row: ");
    scanf("%c",&input);

    for(i=1; i <= (input-'A'+1); ++i)
    {
        for(j=1;j>=i;++j)
        {
            printf("%c", alphabet);
        }
        ++alphabet;

        printf("\n");
    }
    return 0;
}

OUTPUT

C program to print right angled triangle using alphabets

#include<stdio.h>
int main()
{
int i,n;
char a[100][25];
printf("Enter the number:-  ");
scanf("%d",&n);
printf("Enter the names in array\n");
for(i=0;i<n;i++)
{
scanf("%s",a[i]);
}
printf("\nThe names you have entered is:-\n");
for (i=0;i<n;i++)
{
printf("%s\n",a[i]);
}
}

OUTPUT

C program to display entered names using array

for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax

Syntax
The syntax of a for loop in C programming language is −

for ( init; condition; increment ) {
   statement(s);

}
Here is the flow of control in a 'for' loop −
·      The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
·      Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop.
·      After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.

·      The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates.

C program  to print number triangle pattern

#include<stdio.h>
int main()
{
    int n,z=1,i,j,k;
    printf("Enter the digits: ");
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
    for(j=n-1;j>=i;j--)
    {
    printf(" ");
}
for(k=1;k<=z;k++)
{
printf("%d",k);
}
z+=2;
printf("\n");
}
    return 0;
}

OUTPUT

C program to print number triangle pattern

#include <stdio.h>
#include <string.h>

int main()
{
    int i, j = 0, k = 0, count = 0;
    char str[100], key[20];
    char str1[10][20];

    printf("enter string:");
    scanf("%[^\n]s",str);

/* Converts the string into 2D array */   
    for (i = 0; str[i]!= '\0'; i++)
    {
        if (str[i]==' ')
        {
            str1[k][j] = '\0';
            k++;
            j = 0;
        }
        else
        {
            str1[k][j] = str[i];
            j++;
        }
    }
    str1[k][j] = '\0';
    printf("Which word to delete ?:");
    scanf("%s",&key);

/* Compares the string with given word */   
    for (i = 0;i < k + 1; i++)
    {
        if (strcmp(str1[i], key) == 0) //When both are same then override the current row with next row and so on upto the last row.
        {
            for (j = i; j < k + 1; j++)
            strcpy(str1[j], str1[j + 1]);
            k--;
        }

    }
    for (i = 0;i < k + 1; i++)
    {
        printf("%s ", str1[i]);
    }
}

OUTPUT

C program to delete the written word using string function

C Program To Find Prime Number From Inputted Numbers

#include<stdio.h>
int main()
{
 int n,i,j,c=0,a[100];
 printf("How many numbers to be inputed ?");
 scanf("%d",&n);
 printf("\nEnter the numbers:\n");
 for(i=1;i<=n;i++)
 {
  scanf("%d",&a[i]);
 }
 printf("\n\nThe prime numbers are:  ");
 for(i=1;i<=n;i++)
 {
     c = 0;
     for(j=1; j<=a[i]; j++)
        {
            if(a[i]%j==0)
            {
                c=c+1;
            }
        }
        if(c==2)
        {
            printf("%d\t",a[i]);
        }
 }
 return 0;
}

OUTPUT

C Program To Find Prime Number From Inputted Numbers

C Program To Show Square Of Numbers And Find Their Sum

#include<stdio.h>
int main()
{
int i=1,n,sq,sum=0;
printf("Enter number:\n");
scanf("%d",&n);
printf("number\tsquare\n");
while(i<=n)
{
sq=i*i;
printf("%d\t%d\n",i,sq);
i++;
sum+=sq;
}
printf("sum is %d",sum);
return 0;
}

OUTPUT

C program to show square of numbers and find their sum

File Handling in C Programming | C Programming Language

    C supports a number of functions that have the ability to perform basic file operations, which include:   
1. Naming a file   
2. Opening a file   
3. Reading from a file   
4. Writing data into a file   
5. Closing a file   

File Operations functions in C  

             
File Handling in C

Defining and opening a 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.           

w      open for writing (file need not exist)         
a       open for appending (file need not exist)         
r+     open for reading and writing, start at beginning         
w+    open for reading and writing (overwrite file)         
a+     open for reading and writing (append if file exists) 


Consider the following statements:       

FILE *p1, *p2;     
p1=fopen(“data”,”r”);     
p2=fopen(“results”,”w”); 

In these statements the p1 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 data file does not exist error will occur.     

Closing a file    

The input output library supports the function to close a file; it is in the following format.       fclose(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 *p1 *p2;   
p1=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.   

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,fp1); 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.     


The 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 usefull when we deal with only integer data. The  general forms of getw and putw are:       
putw(integer,fp);   
getw(fp);     


The fprintf & fscanf functions    

The fprintf and scanf functions are identical to printf and scanf functions except that they work on files. The first argument of these 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  file output specifications list may include variable, constant and string.               

fprintf(f1,%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(f2,”5s%d”,item,&quantity”);   
Like scanf, fscanf also returns the number of items that are successfully read.   

Basic Concept Of Function


A function is a block of code that performs a specific task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. Function can also be defined as the idea to put some repeatedly done task together by making block of statement which helps while instead of writing the same block of code again and again for different inputs, we can call the same block of statement in the program.

Note: If you want to know more about C function Click Here:

C program to calculate Simple Interest using function:-

#include<stdio.h>
int calculate();
int main()
{
float si;
si=calculate();
printf("The Simple Intrest of given data is %.2f",si);
return 0;
}
int calculate()
{
float principal, rate, time, si;
printf("Enter the Principal, Rate and Amount Respectively:-\n");
scanf("%f%f%f",&principal,&rate,&time);
si=(principal*rate*time)/100;
return si;
}

OUTPUT

C program to calculate Simple Interest using function


Calculate Simple Interest using function with argument but no return type:- 


#include<stdio.h>
void calculate(float , float , float );
int main()
{
float principal,time,rate,si;
printf("Enter Principal, Rate and Time respectively1:-\n");
scanf("%f%f%f",&principal,&rate,&time);
calculate(principal,rate,time);
}
void calculate(float principal, float rate, float time)
{
float si;
si=(principal*time*rate)/100;
printf("The Simple Interst of given value is %.2f",si);
}

OUTPUT

C program to calculate Simple Interest using function



Calculate Simple Interest using function with no argument and no return type:- 

#include<stdio.h>
int calculate();
int main()
{
calculate();
return 0;
}
int calculate()
{

float p,t,r,si;
printf("Enter Principal, Rate and Time respectively1:-\n");
scanf("%f%f%f",&p,&r,&t);
si=(p*t*r)/100;
printf("The Simple Interst of given value is %.2f",si);
return 0;
}

OUTPUT

C program to calculate Simple Interest using function


Calculate Simple Interest using function with  argument and  return type:- 

#include<stdio.h>
int calculate(float p, float t, float r);
int main()
{
float principal,time,rate,c;
printf("Enter Principal, Rate and Time respectively1:-\n");
scanf("%f%f%f",&principal,&rate,&time);
c = calculate(principal,time,rate);
printf("The Simple Interst of given value is %.2f",c);
return 0;
}
int calculate(float p, float t, float r)
{
int si;
si=(p*t*r)/100;
return si;
}

OUTPUT

C program to calculate Simple Interest using function