I'm trying to make a program where user is able to input the number of test cases they want, input the number of alphabet, and then print it.
Since I want to do the printf of the Cases after the value of i is the same as input, which means I have to keep the value of word first but the next scanf always overwrite the value of the previous scanf.
Here's my current code:
#include<stdio.h>
int main()
{
int input=0;
int word=0;
int i=0;
int j=1;
scanf("%d", &input); //number of test cases
for(i=0;i<input;i++)
{
scanf("%d", &word); //how many alphabets
}
for(;i>0;i--)
{
printf("Case #%d: ", j);
j++;
if(word==1)
printf("a\n");
if(word==2)
printf("ab\n");
if(word==3)
printf("abc\n");
else
return 0;
return 0;
}
For example, currently the program works like this:
2
1
2
Case #1: ab
Case #2: ab
Which means the second word scanf (2) overwrote its previous value (1). When I want it to work like this:
2
1
2
Case #1: a
Case #2: ab
I've been searching google for the answer but haven't really found one. Please tell me how to do it in stdio.h if possible and also what does the function called (as in recursion, selection, etc). Thank you very much.
Firs of all are you need this code in C or C++? Case you tagged this post as C++ but code is written in C. So I will answer in C.
You have two solutions in this case:
Simple way is to print the Case
after user make second input like this:
#include<stdio.h>
int main()
{
int input=0;
int word=0;
int i=0;
scanf("%d", &input); //number of test cases
for(i = 0; i < input; i++)
{
scanf("%d", &word); //how many alphabets
printf("Case #%d: ", i);
if(word==1)
printf("a\n");
if(word==2)
printf("ab\n");
if(word==3)
printf("abc\n");
}
return 0;
}
Or you have to make some dynamic structure to hold all user input and then iterate over it and print your case. In C it will look like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int input=0;
int i=0;
int j=1;
int* word = NULL;
scanf("%d", &input); //number of test cases
if (input > 0) { // check if input cases are more than 0;
word = (int*)malloc(sizeof(int) * input);
}
for(i=0;i<input;i++) {
scanf("%d", &word[i]); //how many alphabets. Write new
}
for(;i > 0;i--) {
printf("Case #%d: ", j);
j++;
if(word[i-1] == 1)
printf("a\n");
if(word[i-1] == 2)
printf("ab\n");
if(word[i-1] == 3)
printf("abc\n");
}
free(word);
return 0;
}
Of corse in case of dynamic array's you need to check if word ptr is not null. But this case shows a bigger picture.
If you decide to use C++ it will be easier because you may use std::vector as dynamic container and there is no need to use pointers.