7/31/2019 C Practicles
1/22
C PracticleExample codes for C programming practicle questions
(Refere on your own risk. No author responsibility on its accuracy.)
7/31/2019 C Practicles
2/22
#include//we have to include math.h library to use sqrt() which is implemented within it
#include
void main(){
printf("Number\tSquare\tSquare Root");
printf("\n------\t-------\t-----------\n");
int num=0;for(num=1;num
7/31/2019 C Practicles
3/22
#include
void main(){
int fatherAge=0;
int sonAge=0;
printf("Enter the father's age.......");
scanf("%d",&fatherAge);
printf("Enter the son's age.......");scanf("%d",&sonAge);
//Logic to calculate when father's age become double as son's agewhile(fatherAge!=2*sonAge){
fatherAge++;sonAge++;
}
printf("Father age.... %d\n",fatherAge);
printf("Son age.... %d\n",sonAge);
}
7/31/2019 C Practicles
4/22
#include
//I was unable to get the sharp end of the triangle. You can try for it.
void main(){
int col=0;
int row=0;int count=1;
for(row=0;rowrow;col--){ //creates a triangle with stars on right side. Upside downtriangle.printf("*");
}count++;
}
printf("\n");}
7/31/2019 C Practicles
5/22
#include
void main(){
//Answer for 1
int numbers[10]={3,4,5,6,7,8,2,1,9,23};
int count=0;
while(count
7/31/2019 C Practicles
6/22
int noOfChars=0;#include
main(){
printf("Enter the number of the characters of your name....");scanf("%d",&noOfChars); //C array length should be predefined
noOfChars=noOfChars+1;
char name[noOfChars];
count=0;
printf("Enter your name.....");
while(count=0){
printf("%c",name[count]);count--;
}printf("\n");
}
7/31/2019 C Practicles
7/22
#include
main(){count=0;
int count2=0;
int noOfSameItems=0;int checkOccu=1;
int numElements[20]={2,6,8,1,3,4,7,2,2,5,6,8,9,3,1,1,2,5,8,4};
int controller=0;
while(count
7/31/2019 C Practicles
8/22
#include
void main(){
FILE *fp;
char c;
float total=0;int count=-1;
int minimum=0;
int maximum=0;
fp=fopen("value.txt","r");
if(fp!=NULL){
c=getc(fp);
//c1=c;
minimum=atoi(&c);
maximum=atoi(&c);//printf("%c",c);
while(c!=EOF){
if(c != ' '){count++;
}
total=total+atoi(&c); // atoi() converts char to int
if(maximumatoi(&c)){
minimum=atoi(&c);
}
7/31/2019 C Practicles
9/22
c=getc(fp);
}fclose(fp);
printf("Summation of values.......%.2f\n",total);printf("Average of values.......%.2f\n",total/count);
printf("Minimum of values.......%d\n",minimum);
printf("Maximum of values.......%d\n",maximum);
}
}
7/31/2019 C Practicles
10/22
#include
void oddNum();// function signature of 'oddNum()' to indicate it initially
main(){
oddNum(); //call to oddNum()
}
void oddNum(){//function to find odd numbersint fNum=20;
FILE *fp;
fp=fopen("odd.txt","w"); //connect with the text file names odd.txt with the 'writing
perspective'
while(fNum
7/31/2019 C Practicles
11/22
#include
#include
void main(){
int looper=0;
while(looper==0){ //This loop is for continuity of the program. this will loop until no 3 is entered
int itemNo=0;
FILE *fp; //FILE pointer for write to file
FILE *fpRead; //FILE pointer for read from file
fp=fopen("directory.txt","a"); //create a connection to append to File directory.txt
fpRead=fopen("directory.txt","r"); //create a connection to read File directory.txt
char name[256]; //Used to store a string which is lenght of 256 chars
char stuID[10];
char phoneNo[12];char eMail[100];
char *result;char word[50];
printf(".......................Menu.......................\n");
printf("1-Add new contact\n");
7/31/2019 C Practicles
12/22
printf("2-Show contacts\n");
printf("3-Exit\n");printf("..................................................\n");
printf("Enter menu no....");scanf("%d",&itemNo);
switch(itemNo){
case 1: //this part will do appendings to the text filefgets(name,25,stdin);
printf("Enter your name....");fgets(name,256,stdin); //get the user input through terminal.'name' is the array name where
will be the string stored.'stdin' stands for keyboard input
fputs(name,fp); //output is saved on the text file. 'name' is the array where name of theperson is stored. 'fp' is the name of the pointer
printf("Enter your Student ID....");fgets(stuID,10,stdin);
fputs(stuID,fp);printf("Enter your phoneNo....");
fgets(phoneNo,12,stdin);fputs(phoneNo,fp);
printf("Enter your E-Mail....");
fgets(eMail,100,stdin);fputs(eMail,fp);
fputs("\n",fp);
fclose(fp); //close the file coonnection
break;
case 2: //read from text file and print on terminalprintf("---------------contact Info----------------------\n");
printf("Name \t ID \t Phone No \t E-Mail \n\n");
do{fscanf(fpRead, "%s%s%s%s", name, stuID,phoneNo,eMail); //get the data from text file to
above arrys named 'name','stuID' etc.fprintf(stdout, "%s \t %s \t %s \t %s \t\n", name, stuID,phoneNo,eMail);//print the data on
terminal with data from above arrysresult=fgets(word,50,fpRead); //this is for loop condition}while(result!=NULL); //loop will be executed until there is nothing in text file
printf("-------------------------------------------------\n");fclose(fpRead); //break the connection with text file
break;
case 3:exit(1); //exit from the program
break;}
}
}
7/31/2019 C Practicles
13/22
#include#include
main(){
FILE *voltageFp; //pointer to point text file where voltages are storedFILE *resistanceFp; //pointer to point text file where resistances are stored
FILE *fp; ////pointer to point text file where voltages are stored only for while loop condition
int voltage=0; //variable to store received voltage value from the file
int resistance=0; //variable to store received resistance value from the filechar *result;
char word[60];float totalPower=0;
float max;
float maxPower;
voltageFp=fopen("voltage.txt","r"); //point the file to read.(text File contains voltage values)
resistanceFp=fopen("resistance.txt","r"); //(text file contains resistance values for given voltages)fp=fopen("resistance.txt","r");
do{
fscanf(voltageFp,"%d",&voltage); //read data as integers from the text filefscanf(resistanceFp,"%d",&resistance);
totalPower=totalPower+((voltage*voltage)/resistance);if(max
7/31/2019 C Practicles
14/22
}while(result!=NULL); //executes the loop until 'result' get null at the end
//There is a logical error. Loop doesn't stop at the end. Repeat the last line twise.
fclose(voltageFp);
fclose(resistanceFp);printf("Total power consumption of the circuit = %.2f\n",totalPower);
printf("Maximum power consuming resistor of the circuit = %.2f\n",max);printf("Voltage of the maximum power consuming resistor = %.2f\n",maxPower);
}
7/31/2019 C Practicles
15/22
#include
#include
//in C we have to indicate about the function below main() at the begining of the source usingfunction signature
void inputFile();
void outputFile(char *blank);
main(){
inputFile(); //executes the inputFile()}
void inputFile(){
FILE *input;
input=fopen("unedited.txt","r");//there are more than one space between two words in the text file.
char text[1000];char blank[1000];
int location = 0;
int blankLocation=0;
fgets(text,999,input); //initially takes a string to char array 'text'
while (text[location] != '\0') //loop executes until 'text' is not null
{//condition becomes true if there is no another space or tab soon after a space or tab
if (!((text[location] == ' ' && text[location+1] == ' ') || (text[location] == '\t' && text[location+1]== '\t'))) {
blank[blankLocation] = text[location];
blankLocation++;
}location++;
fgets(text,999,input);
}
blank[blankLocation] = '\0';outputFile(blank);// parse the char array blank to output()
}
7/31/2019 C Practicles
16/22
void outputFile(char *blank){//In C we cannot define arrays for parameter list so we can use apointer instead of that
FILE *output;
output=fopen("edited.txt","w");int counter=0;
for(counter=0;counter
7/31/2019 C Practicles
17/22
#include
#include
main(){
char area[50];printf("Enter area..... ");
gets(area);//gets the area as a system input
FILE *inputFile;
char fName[200];char lName[200];
char location[100];char tpn[50];
char *result;char buffer[200];
inputFile=fopen("info.txt","r");
do{
fscanf(inputFile,"%s%s%s%s",fName,lName,location,tpn);
if(strcmp(location,area)==0){ //compare the system input area with file input area '0' indicates trueand '1' indicate false
printf("%s\n%s\n%s\n%s\n",fName,lName,location,tpn);
}else{
}
result=fgets(buffer,199,inputFile);}while(result!=NULL);
}
7/31/2019 C Practicles
18/22
#include
#include
void calSubAvg();void appendMarks(); //indicate about the function at the begining by using the function signature
void calStuAvg();
main(){
int choice=0;while(1>0){ //continuity of program until user decide to stop
printf("1- Input student data\n2- Calculate average of each subject\n3- Calculate average of eachstudent\n0- Exit\n");
printf("Input your choice no.....");
scanf("%d",&choice);
switch(choice){
case 1:appendMarks(); //call the function
break;case 2:calSubAvg();
break;case 3:calStuAvg();
break;
default:exit(0);
}
}
}
void appendMarks(){ //function to append marks
char indexNo[10];char mark1[5];
char mark2[5];char mark3[5];
char mark4[5];
printf("Enter the index no......");
gets(indexNo);
7/31/2019 C Practicles
19/22
gets(indexNo); //gets the input as strings to a char array
printf("Enter the mark 1......");
gets(mark1);
printf("Enter the mark 2......");
gets(mark2);
printf("Enter the mark 3......");
gets(mark3);
printf("Enter the mark 4......");gets(mark4);
FILE *outputFile;
outputFile=fopen("markList.txt","a");
fprintf(outputFile,"%s\t%s\t%s\t%s\t%s\n",indexNo,mark1,mark2,mark3,mark4);//print the data totext file keeping a tab between two data items
fclose(outputFile);
}
void calStuAvg(){ //function to calculate average mark of each student
char indexNoIn[10];int mark1In;
int mark2In;int mark3In;
int mark4In;
char *result;char text[10];
FILE *inputFile;
inputFile=fopen("markList.txt","r");do{fscanf(inputFile,"%s\t%d\t%d\t%d\t
%d",indexNoIn,&mark1In,&mark2In,&mark3In,&mark4In);//read data from text file. when weread data as integer values to a int variabl, we should call variable's memory location with '&'
printf("%s\t%.2f\n",indexNoIn,(mark1In+mark2In+mark3In+mark4In)/4.0); //4.0 to convert int
result to floatresult=fgets(text,9,inputFile);
}while(result!=NULL);
fclose(inputFile);
}
7/31/2019 C Practicles
20/22
void calSubAvg(){ //function to calculate average mark to each subject
float counter=0;
int mark1=0;
int mark2=0;
int mark3=0;int mark4=0;
char indexNo[10];
int mark1Total=0;
int mark2Total=0;int mark3Total=0;
int mark4Total=0;
char *result;char text[10];
FILE *inputFile;
inputFile=fopen("markList.txt","r");
do{fscanf(inputFile,"%s\t%d\t%d\t%d\t%d",indexNo,&mark1,&mark2,&mark3,&mark4);
mark1Total=mark1Total+mark1;//calculate total of mark1
mark2Total=mark2Total+mark2;
mark3Total=mark3Total+mark3;mark4Total=mark4Total+mark4;
counter++; //count the number of studentsresult=fgets(text,9,inputFile);
}while(result!=NULL);
printf("Average of mark1...%.2f\n",mark1Total/counter);printf("Average of mark2...%.2f\n",mark2Total/counter);
printf("Average of mark3...%.2f\n",mark3Total/counter);printf("Average of mark4...%.2f\n",mark4Total/counter);
fclose(inputFile);
}
7/31/2019 C Practicles
21/22
#include
struct weather //structure to store weather information
{int rainfall[24];
float wind_speed;
float temperature;};
main(){
int hours=0;
int cummulativeRaunFall=0;
struct weather day; //creates a structure with the reference name 'day'
printf("Enter the weather......");
while(hours
7/31/2019 C Practicles
22/22
hours++;
}
printf("\n\n\n-----------------------The weather Information----------------------------------");
printf("Cummulative rainfall.......%d\n",cummulativeRaunFall);printf("Wind Speed.......%f\n",day.wind_speed);
printf("Temperature.......%f\n",day.temperature);printf("--------------------------------------------------------------------------------");
}