‘C’ Training

Welcome to C training program.Get a shot at the concepts in C & enjoy programming

Download Software Here

Index:

  1. Introduction of basic concepts in C
  2. Conditional Statements
  3. Creating Menus
  4. Arrays
  5. Strings
  6. Functions
  7. Pointers
  8. Dynamic Memory Allocation
  9. Structures
  10. Files

To start with lets go with basic “Hello World” Program

#include<stdio.h>//header files

#include<conio.h>//header files

main()

{//body of program begins

printf(“Hello World”);//output statement

getch();

}

The first two lines are called header files. These are in built library functions in C.

Std lib-Standard Library

conio-console input and output

The third line is main().Here is where the execution of program begins.C programs generally searches for this program to begin execution so keep in mind that u need write the program with this function.

printf-used for printing output on screen

getch()-it waits until a user presses a key on console.

The braces indicate that you need to write body of program within them.

Now lets see some basic “Arithmetical Operations” in Cthat takes input from user.

#include<stdio.h>

#include<conio.h>

main()

{

int a,b,c;//declaration of variables

printf(“Check Addition of Values Here\n”);

printf(“Enter first value: “);

scanf(“%d”,&a);//reading input from user

printf(“Enter second value: “);

scanf(“%d”,&b);

c=a+b;//performing required operation

printf(“Result: “,c);//displaying result

getch();

}

In the above program we have declared variable of type int which means they can hold integer values.

The word int is called “data type“.In the same way there are some more datatypes called “Float”,”Char”,”Double”,”short”,”Long”,”signed”,”unsigned”.

You can use these data types depending on your requirement.

The word scanf is used for reading input from user which is also a predefined i/o statement.

In scanf you can see variable is read using &operator this is used to allocate address for the variable which means allocating memory.

Similarly %d indicates the type of format specifier which indicates it is an integer value.

For float-%f,char-%c,string-%s,double-%d.

A simple program for displaying “Size of Data Types” using sizeof() -which used to display the size of the datatypes in C .

#include<stdio.h>
int main()
{
printf(“The size of int is: %d\n”,sizeof(int));                      
printf(“The size of float is: %d\n”,sizeof(float));
printf(“The size of char is: %d\n”,sizeof(char));
printf(“The size of double is: %d\n”,sizeof(double));
printf(“The size of short is: %d\n”,sizeof(short));
printf(“The size of long is: %d\n”,sizeof(long));
printf(“The size of longdouble is: %d\n”,sizeof(long double));
printf(“The size of longlong is: %d\n”,sizeof(long long));
getch();
}

Conditional Statements:

1.ifsyntax:

if(condition)

{

statements;

}

2.ifelse syntax:

if(condition)

{

statements;

}

else

{

statements;

}

3.ifelse ladder syntax:

if(condition)

{

statements;

}

else if(condition)

{

statements;

}

else if(condition)

{

statements;

}

.

..

else

{

statements;

}

4.while syntax:

while(condition)

{

statements;

}

5.dowhile syntax:

do

{

statements;

}while(condition);

The Difference between while and do while is while executes only if condition is satisfied but do while executes at least once before the condition is satisfied.

6.for syntax:

for(initialisation<condition<incre/decre)

{

}

Lets Check these functionality in the following programs.

1.Program for Smallest and Second Smallest in C using IF Statement

#include<stdio.h>
int main()
{
int a,b,c;
printf(“Enter First Number \n”);
scanf(“%d”,&a);
printf(“Enter Second Number \n”);
scanf(“%d”,&b);
printf(“Enter Third Number \n”);
scanf(“%d”,&c);
if(a<b && a<c)
{
printf(“smallest is %d”,a);
if(b<c)
{
printf(“second smallest is %d”,b);
}
else
{
printf(“second smallest is %d”,c);
}
}

else if(b<a && b<c)
{
printf(“smallest is %d”,b);
if(a<c)
{
printf(“second smallest is %d”,a);
}
else
{
printf(“second smallest is %d”,c);
}
}

if(c<a && c<b)
{
printf(“smallest is %d”,c);
if(a<b)
{
printf(“second smallest is %d”,a);
}
else
{
printf(“second smallest is %d”,b);
}
}

getch();
}

2.Program for Traffic Lights Signals in C using IF ELSE

#include<stdio.h>
int main()
{
int r;
printf(“Enter Color \n”);
scanf(“%c”,&r);
if(r==’r’ || r==’R’)
{
printf(“STOP!”);
}
else if(r==’g’ || r==’G’)
{
printf(“Go”);
}
else if(r==’y’ || r==’Y’)
{
printf(“CAUTION”);
}
else
{
printf(“Invalid Selection”);
}
getch();
}

3.Program to print odd numbers is increasing order and even numbers in decreasing order in C using while condition

#include<stdio.h>
int main()
{
int odd=1,even=100;
printf(“The odd numbers from 1 to 100 in increasing order are:”);
while(odd<=100)
{
if(odd%2!=0)
printf(“%d,”,odd);
odd=odd+1;
}
printf(“\n The even numbers from 1 to 100 in decreasing order are:”);
while(even>=0)
{
if(even%2==0)
printf(“%d,”,even);
even=even-1;
}
getch();
}

4.Program to print prime numbers in the range entered by user in C 

#include<stdio.h>
int main()
{
int prime,i,c,j=1;
int flag=0;
int count=0;
printf(“Enter the range of prime numbers: \n”);
scanf(“%d”,&prime);
for(i=2;i<prime;i++)
{
flag=0;
for(j=2;j<i;j++)
{
if(i%j==0)
{
flag=1;
}
}
if(flag==0)
{
count=count+1;
printf(“%d”,i);
}
}
printf(“\nThe Count is %d”,count);

getch();
}

Now lets see how to create menus using C Language

Syntax:

Switch(int)

{

case 1: statements;

break;

case 2:statements;

break;

.

.

.

.

default:statements;

}

In this default is mandatory for switch case since when the user gives invalid input the default statement exceutes showing invalid input means you need to write a print statement there other wise program ends up with an error during run time.

C program that implements switch case

#include<stdio.h>
int main()
{
    int r;
    printf(“Enter Color \n”);
    scanf(“%c”,&r);
    char c=tolower(r);
    switch(c)
    {
             case ‘r’:
                  printf(“STOP!”);
                  break;
             case ‘g’:
                  printf(“GO”);
                  break;
             case ‘y’:
                  printf(“CAUTION”);
                  break;
             default:
                   printf(“invalid selection”);
                   
    }
    getch();
}    

Check out other programs by clicking the links below

Program for Upper Triangle in C
Program for Fibonacci Series in C
Program For Coin Denominations in Form of Change in C
Program For Cumulative Sum Of Numbers in C
Program For printing the possible ways of sum of numbers in a given series without repetition in C

Now you are all set with the basics of programming in C.So lets now check how to take more number of values from user.

This can be done by using the concept of ARRAYS:

Arrays are used for storing more number of values where each value is assigned an INDEX.The values are retrieved from the array basing on these index values.

The general syntax for an array is-<data-type> arrayname[size];

Here datatype means the type of array you are initilalising like Int,Float,char,String.

Size means how many values you want to store.By Default index value of array starts with ZERO when you start assigning values to array.

An array can be declared statically.This will be more clearer when we go to the examples below.

Lets see a small basic example of how to use an array in C.

#include<stdio.h>

#include<conio.h>

int main()

{

int a[10],i=0;

printf(“Enter 10 Values for Integer Array”);

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

{

scanf(“%d”,&a[i]);

}

printf(“Entered Values are”);

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

{

printf(“%d”,a[i]);

}

getch();

}

In the above program we are declaring an array of Integer type with size 10.

Here we are running a for loop since we need to take values from user and we will be running the loop upto 9 since array index starts with 0.

To print those values we will again run the loop and print value as a[i],since values will be retrieved basing on index value as mentioned earlier.

Check out other programs by clicking the links below

Program for Average of numbers in C using array

Program to find Smallest ans Second Smallest Number in C using an array

Program for Matrix Transpose and Matrix Multiplication with that Transpose in C

Thats all about arrays where you can perform different operations using arrays.

Now lets see how to read a complete line from user including spaces.

This can be done using concept of strings.

Strings:

Strings are used to store array of characters i.e., a complete word or sentence.

The basic declaration of string is string <variable name>

The String variables are read using %s symbol in c

Lets see a program that implements string operations in c

Program for String Operations in C

#include<stdio.h>
int main()
{
int choice,length;
char string[10],string1[10],string2[10],upper,lower,combine;
printf(“1. Calculate length of given string \n2. Check if two strings are equal \n3. Concatenate two given strings \n4. Lower case to upper case \n5. Upper case to Lower case\n”);
printf(“enter the choice (1-4):”);
scanf(“%d”,&choice);
switch(choice)
{
case 1:printf(“Enter the String: “);
scanf(“%s”,&string);
length=strlen(string);
printf(“The Length of string is : %d”,length);
break;
case 2:printf(“Enter String1:”);
scanf(“%s”,&string1);
printf(“Enter String2:”);
scanf(“%s”,&string2);
if(strcmp(string1,string2)==0)
printf(“Strings are equal\n”);
else
printf(“Strings not equal”);
break;
case 3:printf(“Enter String1:”);
scanf(“%s”,&string1);
printf(“Enter String2:”);
scanf(“%s”,&string2);
printf(“%s”,strcat(string1,string2));
break;
case 4:printf(“Enter the String: “);
scanf(“%s”,&string);
printf(“%s”,strupr(string));
break;
case 5:printf(“Enter the String: “);
scanf(“%s”,&string);
printf(“%s”,strlwr(string));
break;
default:
printf(“Invalid Input”);

}
getch();
}

In the above program functions strlwr,strupr,strcat,strcmp,strlen are predefined functions in C.

Program for String Tokenizer in C

#include<stdio.h>
int main()
{
int number,i,length,count=0;
char string[30];
printf(“Enter The String\n”);
scanf(“%s”,&string);
length=strlen(string);
printf(“Enter the value :”);
scanf(“%d”,&number);
for(i=0;i<length;i++)
{
printf(“%c”,string[i]);
count=count+1;
if(count==number)
{
printf(“\n”);
count=0;
}

}
getch();
}

Program for String Tokenizer when a Delimiter is given in C

#include<stdio.h>
int main()
{
char string[30],delemit[30],b[30];
int length,i,j,len;
printf(“enter String \n”);
scanf(“%s”,&string);
printf(“Enter Delemiters\n”);
scanf(“%s”,&delemit);
length=strlen(string);
len=strlen(delemit);
for(i=0;i<length;i++)
{
for(j=0;j<len;j++)
{
if(string[i]==delemit[j])
{
printf(“\n”);
i++;
}
}
printf(“%c”,string[i]);
}
getch();
}

The difference between char and string is char reads only a character where as string reads a complete word.

This ends up the concept of strings and we shall move to the concept of functions which are more important for any programming language.

Functions:

Functions allow you to modular your code so that it will be easy for you to trace when you write long lines of code.

There are four types of functions.

  1. Functions with arguments no return type
  2. Functions without arguments but with return type
  3. Functions with arguments with return type.
  4. Functions without arguments and without return type.

Here arguments generally refers to the parameters we pass to the functions.

Now let us see some examples related to functions in C.

Functions without arguments and without return type.

#include<stdio.h>

#include<conio.h>

int main()

{

add();

getch();

}

void add()

{

int a,b,res;

printf(“Addition of Numbers\n”);

printf(“Enter Number 1: “);

scanf(“%d”,&a);

printf(“Enter Number2: “);

scanf(“%d”,&b);

res=a+b;

printf(“Result: %d”,res);

}

In the above program we just declared a function  in main program that consists of no return type and no parameters.So on execution main program simply calls that function.So here we are dividing our code into blocks so that each block carries a respective functionality.

Functions with arguments no return type

#include<stdio.h>

#include<conio.h>

void add(int,int);//prototyping functions

int main()

{

int a,b;

printf(“Addition of Numbers\n”);

printf(“Enter Number 1: “);

scanf(“%d”,&a);

printf(“Enter Number2: “);

scanf(“%d”,&b);

add(a,b);

getch();

}

void  add(int a,int b)

{

int res;

res=a+b;

printf(“Result: %d”,res);

}

In the above program we have used a function that has no return type but has arguments.In the main function we are reading values from user and passing them as arguments to the add function.In add function we need to specify the type of parameters (int a,int b) depending on the data type you are sending.

It is best practice to prototype your functions as i have done after header files declaration.This gives a gist of  functions you are using in your program.

Functions without arguments but with return type

#include<stdio.h>

#include<conio.h>

int add();//prototyping functions

int main()

{

res;

res=add();

printf(“Result: %d”,res);

getch();

}

int  add()

{

int res,a,b;

printf(“Addition of Numbers\n”);

printf(“Enter Number 1: “);

scanf(“%d”,&a);

printf(“Enter Number2: “);

scanf(“%d”,&b);

res=a+b;

return res;

}

In this program we are not passing any arguments but we are using a return type Integer for returning a value i.e., int add() in this int specifies the type of value the function returns.That returned value is printed in main function.

Functions with arguments with return type.

#include<stdio.h>

#include<conio.h>

int add(int,int);//prototyping functions

int main()

{

int a,b,res;

printf(“Addition of Numbers\n”);

printf(“Enter Number 1: “);

scanf(“%d”,&a);

printf(“Enter Number2: “);

scanf(“%d”,&b);

res=add(a,b);

printf(“Result: %d”,res);

getch();

}

int  add(int a,int b)

{

int res;

res=a+b;

return res;

}

Here we are specifying a return type as well as returning a value.

Check out other programs by clicking the links below

Program for String operations in C using functions

Program for printing the lines entered by user in C using functions

Program for proper positive factors in c

Program for factorial in C using functions

Program for fibonacci in C using functions

So now you are used to functions in c programming.Now lets move to crucial concept of C programming which is the concept of pointers.

Pointers:

Pointers play a crucial role since they help us to refer to the address location of another variable.By using the concept of pointers we can traverse the address locations in the memory and we can also manipulate the value at the address location.Learning the concept of pointers is crucial for any programmer.Pointers are declared using * operator.

Now lets look at a example of pointers.

Program for String operations using pointers in C.

#include<stdio.h>
#include<string.h>
int length(char *a);
char stringcopy(char *a,char *b);
char strcats(char *c,char *d);
int main()
{
char string[20],string1[20],string2[20],string3[20],string4[20];
int i=0;
//lenght of string
printf(“Enter The String: “);
scanf(“%s”,&string);
int len=length(string);//calling function by passing address
printf(“The Length Of String is: %d”,len);

//copying string
printf(“\nEnter String: “);
scanf(“%s”,&string2);
stringcopy(string1,string2);  //calling function by passing address
printf(“The Copied String is: %s”,string1);

//concatenating string
printf(“\nEnter First String: “);
scanf(“%s”,&string3);
printf(“Enter Second String: “);
scanf(“%s”,&string4);
strcats(string3,string4);//calling function by passing address
printf(“The Concatenated Strings are: %s”,string3);
getch();
}

//function for calculating length
int length(char *a)//pointers pointing to the variable address passed to the function previously
{
int len=0;
while(*a!=”)
{
len++;
a++;
}
return(len);
}

//function for copying
char stringcopy(char *a,char *b)//pointers pointing to the variable address passed to the function previously
{
char *t;
while(*a!=” || *b!=”)
{
*a=*b;
a++;
b++;
}
return *a;
}

//function for concatenation
char strcats(char *c,char *d) //pointers pointing to the variable address passed to the function previously
{
int len=strlen(c);
int len1=strlen(d);
int i=len;
for(i=0;i<len1;i++)
{
*(c+len+i)=*(d+i);
}
*(c+len+i)=”;
return *c;
}

In the above program we are passing the address values of variables to the functions as parameters where a pointer is pointing to that address.So there by using that pointer we are performing the operations so that value at that address location is changed.

Program to display pointer sizes in C

#include<stdio.h>
int main()
{
int *i;
char *c;
float *f;
double *d;
printf(“Size of Int is:%u\n”,sizeof(*i));
printf(“Size of Char is:%u\n”,sizeof(*c));
printf(“Size of Float is:%u\n”,sizeof(*f));
printf(“Size of Double is:%u\n”,sizeof(*d));
getch();
}

Program to find Sum,Average and Median in C

#include<stdio.h>
int sum(int *a1,int *a2,int *a3,int *a4,int *a5);
int averages(int *a6,int *a7,int *a8,int *a9,int *a10);
int median(int *a11,int *a12,int *a13,int *a14,int *a15);
int main()
{
int a,b,c,d,e,result,result1,result2;
printf(“Enter 1st integer: “);
scanf(“%d”,&a);
printf(“Enter 2nd integer: “);
scanf(“%d”,&b);
printf(“Enter 3rd integer: “);
scanf(“%d”,&c);
printf(“Enter 4th integer: “);
scanf(“%d”,&d);
printf(“Enter 5th integer: “);
scanf(“%d”,&e);
result=sum(&a,&b,&c,&d,&e);
result1=averages(&a,&b,&c,&d,&e);
result2=median(&a,&b,&c,&d,&e);
printf(“The Sum is: %d\n”,result);
printf(“The Average is: %d\n”,result1);
printf(“The Median is value %d \n”,result2);
getch();
}
int sum(int *a1,int *a2,int *a3,int *a4,int *a5)
{
int res;
res=(*a1+*a2+*a3+*a4+*a5);
return res;
}
int averages(int *a6,int *a7,int *a8,int *a9,int *a10)
{
int res;
res=(*a6+*a7+*a8+*a9+*a10)/5;
return res;
}
int median(int *a11,int *a12,int *a13,int *a14,int *a15)
{
int res;
res=5/2;
return res;
}

This is all about pointers where you can access the address location of a particular variable by using * operator.You need to practice a lot to get used to pointers.

Next topic will be dynamic memory allocation in C.

Dynamic Memory Allocation:

Till now we are declaring memory statically at the start of program,but using this concept of dynamic memory allocation we can assign or delete memory at any part of our program.

This is done using malloc() ,realloc()and calloc() functions.

Program for Dynamic Memory allocation in C.

#include<stdio.h>
int main()
{
int i=0,*p,b,n,*q;
printf(“Enter Number OF Elements you want to enter:”);
scanf(“%d”,&b);
int a[b];
p=(int *)malloc(b*sizeof(int));//allocating memory
if(p==NULL)
{
printf(“Memory Allocation failed”);
}
printf(“Enter %d elements\n”,b);
for(i=0;i<b;i++)
{
scanf(“%d”,(p+i));
}
printf(“Elements Entered are: “);
for(i=0;i<b;i++)
{
printf(“%d”,*(p+i));
}

printf(“\nInput the number of elements you want to increase: “);
scanf(“%d”,&n);
q=realloc(p,n);//reallocating memory
printf(“enter %d elements: \n”,n);
for(i=0;i<n;i++)
{
scanf(“%d”,(q+i));
}
printf(“Elements Entered are: “);
for(i=0;i<n;i++)
{
printf(“%d”,*(q+i));
}
getch();
}

In the above program we are using malloc to allocate a memory which is of type int dynamically i.e., at required position in our program and at the same time we are reallocating it using realloc.

Structures:

Now lets move on to structures which plays a crucial role when you want to create a number of records that contains same information like student information,employee information etc…

Syntax:

struct structure name

{

member variables;

}

create a object for structure using struct structure name object; in your main program.

Program to demonstrate structures in C

#include<stdio.h>
struct employee//creating structure
{
char ename[10];
char dob[10];
char phn[10];
int age;
int salary;
char joindate[10];
char role[10];
char addres[10];
char dept[10];
char groupname[10];
};
int main()
{
struct employee emp;//creating variable for structure

//reading values
printf(“Enter Employee Name: “);
scanf(“%s”,&emp.ename);
fflush(stdin);
printf(“\nEnter Date Of Birth(DD/MM/YY): “);
fflush(stdin);
scanf(“%s”,&emp.dob);
printf(“\nEnter Phone Number: “);
fflush(stdin);
scanf(“%s”,&emp.phn);
printf(“\nEnter Age: “);
fflush(stdin);
scanf(“%d”,&emp.age);
printf(“\nEnter Salary: “);
fflush(stdin);
scanf(“%d”,&emp.salary);
printf(“\nEnter Join Date(DD/MM/YY): “);
fflush(stdin);
scanf(“%s”,&emp.joindate);
printf(“\nEnter Role: “);
fflush(stdin);
scanf(“%s”,&emp.role);
printf(“\nEnter Address: “);
fflush(stdin);
scanf(“%s”,&emp.addres);
printf(“\nEnter Department: “);
fflush(stdin);
scanf(“%s”,&emp.dept);
printf(“\nEnter Group Name: “);
fflush(stdin);
scanf(“%s”,&emp.groupname);

//printing values
printf(“——————————–“);
printf(“\nThe Employee Details are\n”);
printf(“Name: %s\n”,emp.ename);
printf(“Date Of Birth: %s\n”,emp.dob);
printf(“Phone Number: %s\n”,emp.phn);
printf(“Age: %d\n”,emp.age);
printf(“Salary: %d\n”,emp.salary);
printf(“Join date: %s\n”,emp.joindate);
printf(“Role: %s\n”,emp.role);
printf(“Address: %s\n”,emp.addres);
printf(“Department: %s\n”,emp.dept);
printf(“Group Name: %s”,emp.groupname);

getch();

}

Program to read a certain number of records and display oldest employee in that record

#include<stdio.h>

struct employee//creating structure
{
struct date1//structure in structure
{
int dd;
int mm;
int yy;
}dob;//object to structure

char ename[10];
char phn[10];
int age;
int salary;
char joindate[10];
char role[10];
char addres[10];
char dept[10];
char groupname[10];

};
main()
{
struct employee *b;//variable for structure
int d,m,y,x,v,z,i;
b=(struct employee *)malloc(10*sizeof(struct employee));//dynamic memory allocation

//reading values
for(i=1;i<=10;i++)
{
printf(“\nEnter The Details of Employee%d\n”,i);
printf(“\nEnter Employee Name: “);
scanf(“%s”,(b+i)->ename);
fflush(stdin);
printf(“\nEnter Date Of Birth(Date,Month,Year): \n”);
printf(“Day: “);
fflush(stdin);
scanf(“%d”,&(b+i)->dob.dd);
printf(“Month: “);
fflush(stdin);
scanf(“%d”,&(b+i)->dob.mm);
printf(“Year: “);
fflush(stdin);
scanf(“%d”,&(b+i)->dob.yy);
printf(“\nEnter Phone Number: “);
fflush(stdin);
scanf(“%s”,(b+i)->phn);
printf(“\nEnter Age: “);
fflush(stdin);
scanf(“%d”,&(b+i)->age);
printf(“\nEnter Salary: “);
fflush(stdin);
scanf(“%d”,&(b+i)->salary);
printf(“\nEnter Join Date(DD/MM/YY): “);
fflush(stdin);
scanf(“%s”,&(b+i)->joindate);
printf(“\nEnter Role: “);
fflush(stdin);
scanf(“%s”,&(b+i)->role);
printf(“\nEnter Address: “);
fflush(stdin);
scanf(“%s”,&(b+i)->addres);
printf(“\nEnter Department: “);
fflush(stdin);
scanf(“%s”,&(b+i)->dept);
printf(“\nEnter Group Name: “);
fflush(stdin);
scanf(“%s”,&(b+i)->groupname);
}

//checking for oldest age
d=b[0].dob.dd;
m=b[0].dob.mm;
y=b[0].dob.yy;
for(i=1;i<=10;i++)
{
if(d>=b[i].dob.dd)
{
d=b[i].dob.dd;
x=i;
}
if(m>=b[i].dob.mm)
{
m=b[i].dob.mm;
v=i;
}
if(y>b[i].dob.yy)
{
y=b[i].dob.yy;
z=i;
}
}

//displaying output
printf(“***************************”);
printf(“\nThe Oldest Person is\n”);
printf(“Name: %s\n”,b[z].ename);
printf(“Date Of Birth: %d-%d-%d \n”,b[z].dob.dd,b[z].dob.mm,b[z].dob.yy);
printf(“Phone Number: %s\n”,b[z].phn);
printf(“Age: %d\n”,b[z].age);
printf(“Salary: %d\n”,b[z].salary);
printf(“Join date: %s\n”,b[z].joindate);
printf(“Role: %s\n”,b[z].role);
printf(“Address: %s\n”,b[z].addres);
printf(“Department: %s\n”,b[z].dept);
printf(“Group Name: %s”,b[z].groupname);
getch();

}

Program to display highest salary in employee records using structures in C

#include<stdio.h>
struct employee//creating structure
{
char ename[10];
char dob[10];
char phn[10];
int age;
int salary;
char joindate[10];
char role[10];
char addres[10];
char dept[10];
char groupname[10];
};

int main()
{
struct employee *b;//structure variable
int i,highest,c;
b=(int *)malloc(10*sizeof(sizeof(int)));//dynamic memory allocation

//reading values
for(i=1;i<=10;i++)
{
printf(“\nEnter The Details of Employee%d\n”,i);
printf(“\nEnter Employee Name: “);
scanf(“%s”,&(b+i)->ename);
fflush(stdin);
printf(“\nEnter Date Of Birth(DD/MM/YY): “);
fflush(stdin);
scanf(“%s”,&(b+i)->dob);
printf(“\nEnter Phone Number: “);
fflush(stdin);
scanf(“%s”,&(b+i)->phn);
printf(“\nEnter Age: “);
fflush(stdin);
scanf(“%d”,&(b+i)->age);
printf(“\nEnter Salary: “);
fflush(stdin);
scanf(“%d”,&(b+i)->salary);
printf(“\nEnter Join Date(DD/MM/YY): “);
fflush(stdin);
scanf(“%s”,&(b+i)->joindate);
printf(“\nEnter Role: “);
fflush(stdin);
scanf(“%s”,&(b+i)->role);
printf(“\nEnter Address: “);
fflush(stdin);
scanf(“%s”,&(b+i)->addres);
printf(“\nEnter Department: “);
fflush(stdin);
scanf(“%s”,&(b+i)->dept);
printf(“\nEnter Group Name: “);
fflush(stdin);
scanf(“%s”,&(b+i)->groupname);
}

//checking for highest salary
highest=b[0].salary;
for(i=1;i<=10;i++)
{
if(highest<b[i].salary)
{
highest=b[i].salary;
c=i;
}
}

//displaying output
printf(“***************************”);
printf(“\nThe Highest salary is for\n”);
printf(“Name: %s\n”,b[c].ename);
printf(“Date Of Birth: %s\n”,b[c].dob);
printf(“Phone Number: %s\n”,b[c].phn);
printf(“Age: %d\n”,b[c].age);
printf(“Salary: %d\n”,b[c].salary);
printf(“Join date: %s\n”,b[c].joindate);
printf(“Role: %s\n”,b[c].role);
printf(“Address: %s\n”,b[c].addres);
printf(“Department: %s\n”,b[c].dept);
printf(“Group Name: %s”,b[c].groupname);
getch();
}

This ends the concept of structures

Files:

Now we are into final concept of c programming that is files where you can store data permanently in your system if required. There are certain operations in files which you need for writing and reading and the rest you need to apply the concepts dealt before if necessary.

The operations in files are

1.Reading

2.Writing

3.Updating 

4.Removing

The modes of opening are

read(r),write(w),append(a),read write(r+),write read(w+),append read(a+). These are for text files.

read binary(rb),write binary(wb),append(ab),read write(rb+),write read(wb+),appendread(ab+). These are for binary files.

Program on File Operations in C

#include<stdio.h>
#include<stdlib.h>
main(int argc,char *argv[])
{
FILE *fp;//file pointer
int i;
int n=0;
printf(“Enter The Data to your file and press ctrl^z to stop entering\n”);
if(argc!=2)
{
printf(“usage: %s filename”,argv[0]);
}
else
{
fp=fopen(“data2.txt”,”w”);//opening file
if(fp==0)
{
printf(“Error:Cannot Open File”);
}
else
{
while((i=getchar())!=EOF)//checking end of file
{
putc(i,fp);
if(“\n”)
{
n=n+1;
}
}
fclose(fp);
}
}
printf(“The Entered Data is\n”);//displaying data
fp=fopen(“data2.txt”,”r”);
while((i=getc(fp))!=EOF)
{
printf(“%c”,i);
}
fclose(fp);
getch();
}

In this you need to pass command line arguments since the main function contains the parameters.Declaring main in that way indicates that we need to pass command line arguments.

For that open DEVC++-> Tools->compiler options and give the file name in the text area and click ok.

Program for reading a file in C

#include<stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
FILE *fp;//file pointer
int i,n=1;
if(argc!=2)
{
printf(“usage: %s filename”,argv[0]);
}
else
{
fp=fopen(argv[1],”r”); //opening file

if(fp==0)
{
printf(“Error:Cannot Open File”);
}
else
{
while((i=fgetc(fp))!=EOF)//reading file
{
printf(“%c”,i);
}
fclose(fp);
}
}
getch();
}

Check out other programs by clicking the links below

Program for reading and writing Binary file in C 

Program for copying data from binary file to text file in C

Source code for reading contents in directory using C


One thought on “‘C’ Training

    Programming and World said:
    August 23, 2012 at 9:57 pm

    […] HomeTech TrainingTech WorldCareer BuildingMy Resume […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s