In: Computer Science
Write three functions that will print your names 25 times to csis.txt and the console. One function will use a for() loop, one function a while() loop and the final function will use a do while() loop.
Here are the three prototypes for the functions:
void nameUsingForLoop(int);
void nameUsingWhileLoop(int);
void nameUsingDoWhileLoop(int);
Call each function in main() using an input parameter 25.
Each function has one int parameter, example:
void nameForLoop(int times){
}
submit nameLoop.c and csis.txt files
use the statements in the loop to give yourself 5 columns and 5 rows:
if(count % 5 == 0){
printf(“\n”);
}
use braces { } around both statements:
if(count % 5 == 0){
printf("\n");
fprintf(fp,"\n");
}
write functions:
//prototype void use_while_loop(void);
int main(){
//call use_while_loop();
Below is the code in C++ containing three functions for different loop methods as mentioned in the question. The program is able to print on the console and on the file simultaneously as mentioned. Sample output is attached at the end for the same.
Note:- Change "xyz" to your name.
#include <iostream>
#include <stdlib.h>
using namespace std;
// function to implement the task using for loop.
void nameForLoop(int times){
// creating file pointer.
FILE *fp;
// opening the file csis.txt to write names on to it.
fp = fopen ("csis.txt", "w+");
for(int i = 1; i<=25; i++){
if(i % 5 == 0){
printf("xyz ");
printf("\n");
}
if(i % 5 == 0){
fprintf(fp,"xyz ");
fprintf(fp,"\n");
}
if(i%5 != 0){
printf("xyz ");
fprintf(fp,"xyz ");
}
}
fclose(fp);
}
// function to implement the task using while loop.
void nameWhileLoop(int times){
// creating file pointer.
FILE *fp;
// opening the file csis.txt to write names on to it.
fp = fopen ("csis.txt", "w+");
int i = 1;
while(i <= 25){
if(i % 5 == 0){
printf("xyz ");
printf("\n");
}
if(i % 5 == 0){
fprintf(fp,"xyz ");
fprintf(fp,"\n");
}
if(i%5 != 0){
printf("xyz ");
fprintf(fp,"xyz ");
}
i++;
}
fclose(fp);
}
// function to implement the task using doWhile loop.
void nameDoWhileLoop(int times){
// creating file pointer.
FILE *fp;
// opening the file csis.txt to write names on to it.
fp = fopen ("csis.txt", "w+");
int i = 1;
do {
if(i % 5 == 0){
printf("xyz ");
printf("\n");
}
if(i % 5 == 0){
fprintf(fp,"xyz ");
fprintf(fp,"\n");
}
if(i%5 != 0){
printf("xyz ");
fprintf(fp,"xyz ");
}
i++;
} while(i <= 25);
fclose(fp);
}
int main()
{
// uncomment the function you want to execute. By default doWhile will run.
//nameForLoop(25);
//nameWhileLoop(25);
nameDoWhileLoop(25);
return 0;
}
Sample Output on file:-
Sample Output on console:-