You are on page 1of 22

C Practicle

Example codes for C programming practicle questions


(Refere on your own risk. No author responsibility on its accuracy.)

#include<stdio.h> //we have to include math.h library to use sqrt() which is implemented within it #include<math.h> void main(){ printf("Number\tSquare\tSquare Root"); printf("\n------\t-------\t-----------\n"); int num=0; for(num=1;num<11;num++){ printf("%d\t",num); printf("%d\t",num*num); printf("%.4f\t\n",sqrt(num));//here we find the square root and '.4f' indicates there should be only 4 decimal points of the output } } //As we have included math.h and used sqrt function, we have to complie this file as below if not compiler returns an error // gcc -o Ex1 Ex1.c -lm

#include<stdio.h> 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 age while(fatherAge!=2*sonAge){ fatherAge++; sonAge++; } printf("Father age.... %d\n",fatherAge); printf("Son age.... %d\n",sonAge); }

#include<stdio.h> //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;row<8;row++){ printf("\n"); //whole triangle is consisted of three sub triangles. for(col=0;col<row;col++){ //creates a triangle with spaces on the left side. printf(" "); } for(col=8;col>row;col--){ //creates a triangle with stars on the center. Upside down triangle. printf("*"); } for(col=8;col>row;col--){ //creates a triangle with stars on right side. Upside down triangle. printf("*"); } count++; } printf("\n"); }

#include<stdio.h> void main(){ //Answer for 1 int numbers[10]={3,4,5,6,7,8,2,1,9,23}; int count=0; while(count<10){ printf("%d , ",numbers[count]); count++; } printf("\n");

int noOfChars=0; #include<stdio.h> 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<noOfChars){ scanf("%c",&name[count]); //get the characters one by one to the char array count++; } printf("Your name backward...."); count=noOfChars; while(count>=0){ printf("%c",name[count]); count--; } printf("\n"); }

#include<stdio.h> 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<20){ checkOccu=1; //used for avoiding printing the same element count2=0; while(count2<count){ if(numElements[count]==numElements[count2]){ checkOccu=0; break; } count2++; } count2=0; while(count2<20 && checkOccu==1){ if(numElements[count]==numElements[count2]){ noOfSameItems++; } count2++; } if(checkOccu==1){ printf("Item %d - No Of Occurence= %d\n",numElements[count],noOfSameItems); } noOfSameItems=0; count++; } }

#include<stdio.h> 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(maximum<atoi(&c)){ maximum=atoi(&c); } if(minimum>atoi(&c)){ minimum=atoi(&c); }

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);

} }

#include<stdio.h> void oddNum();// function signature of 'oddNum()' to indicate it initially main(){ oddNum(); //call to oddNum() } void oddNum(){//function to find odd numbers int fNum=20; FILE *fp; fp=fopen("odd.txt","w"); //connect with the text file names odd.txt with the 'writing perspective' while(fNum<=100){ if(fNum%2 !=0 ){ fprintf(fp,"%d,",fNum); //print on the text file data as integer values } fNum++; } fclose(fp); }

#include<stdio.h> #include <string.h> 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 *fpRead; //FILE pointer for write to file //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]; char stuID[10]; char phoneNo[12]; char eMail[100]; char *result; char word[50]; //Used to store a string which is lenght of 256 chars

printf(".......................Menu.......................\n"); printf("1-Add new contact\n");

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 file fgets(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 the person 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); break; //close the file coonnection

case 2: //read from text file and print on terminal printf("---------------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 arrys result=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; } } }

#include<stdio.h> #include<string.h> main(){ FILE *voltageFp; //pointer to point text file where voltages are stored FILE *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 file char *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 file fscanf(resistanceFp,"%d",&resistance); totalPower=totalPower+((voltage*voltage)/resistance); if(max<((voltage*voltage)/resistance)){ max=((voltage*voltage)/resistance); maxPower=voltage; } result=fgets(word,50,fp);

}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); }

#include<stdio.h> #include<string.h> //in C we have to indicate about the function below main() at the begining of the source using function 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()

void outputFile(char *blank){//In C we cannot define arrays for parameter list so we can use a pointer instead of that FILE *output; output=fopen("edited.txt","w"); int counter=0; for(counter=0;counter<strlen(blank);counter++){ //executes the loop until the end of the char array 'blank' putc(*(blank+counter),output); } }

#include<stdio.h> #include<string.h> 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 true and '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); }

#include<stdio.h> #include<string.h> 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 each student\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);

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 to text 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 we read 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 float result=fgets(text,9,inputFile); }while(result!=NULL); fclose(inputFile); }

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 students result=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); }

#include<stdio.h> 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<24){ scanf("%d",&day.rainfall[hours]);//we have to call structutre variable with '.' operator hours++; } printf("Enter the wind speed......"); scanf("%f",&day.wind_speed); printf("Enter the temperature......"); scanf("%f",&day.temperature); hours=0; while(hours<24){ cummulativeRaunFall=cummulativeRaunFall+day.rainfall[hours];

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("--------------------------------------------------------------------------------"); }

You might also like