Printing first array data amount of times based on second array data - c

sorry for the poor title structure, couldn't think of how to word it.
Anyway, I'm facing a problem when it comes to arrays and loops in C. I need to have a user input 5 letters and store them in the first array. Then I need them to input 5 numbers between 1 and 10 and store those in a second array. Then I need to print the data of the first array the amount of times based on the corresponding number entered in the second array.
For example, if the first letter entered into the first array was A and the first number entered into the second array was 4, i need to print out AAAA.
I know that I need to use a for loop in there somewhere, I'm sure that would be better than a while loop because I will know all the data being used in the loop.
Here is my code so far, it's not much but I hate to ask a question with not even some code in it.
Cheers!
#include <stdio.h>
#include <stdlib.h>
int main() {
char input1[5];
int input2[5], i;
printf("Please enter a letter to be stored in the first array: \n");
scanf(" %c", &input1[0]);
printf("Please enter another letter to be stored in the first array: \n");
scanf(" %c", &input1[1]);
printf("Please enter another letter to be stored in the first array: \n");
scanf(" %c", &input1[2]);
printf("Please enter another letter to be stored in the first array: \n");
scanf(" %c", &input1[3]);
printf("Please enter a final letter to be stored in the first array: \n");
scanf(" %c", &input1[4]);
printf("The first array contains these values: %c, %c, %c, %c and %c. \n", input1[0], input1[1], input1[2], input1[3], input1[4]);
printf("Please enter five numbers between 1 and 10 to be stored in a second array: \n");
scanf("%d", &input2[0]);
printf("Please enter five numbers between 1 and 10 to be stored in a second array: \n");
scanf("%d", &input2[1]);
printf("Please enter five numbers between 1 and 10 to be stored in a second array: \n");
scanf("%d", &input2[2]);
printf("Please enter five numbers between 1 and 10 to be stored in a second array: \n");
scanf("%d", &input2[3]);
printf("Please enter five numbers between 1 and 10 to be stored in a second array: \n");
scanf("%d", &input2[4]);
printf("The second array contains these values: %d, %d, %d, %d and %d \n", input2[0], input2[1], input2[2], input2[3], input26[4]);

for(i=0;i<5;i++){
for(j=0;j<input2[i];j++){
printf("%c",input1[i]);
}
}

Code:
for(i=0; i < input1.length; i++) {
char charValue = input1[i];
int loopNumber = input2[i];
for(j=0 ;j < loopNumber; j++) {
printf("%c" + charValue);
}
}

Related

Replacing a char in a char array not working from a variable

I am trying to write a program that takes in 5 characters then takes in a number and a letter and switches the character at the index/number to the new character. I think I have it but it is not working and defaulting the number to 0.
Also, is there a way to get both inputs at the same time?
char str[5];
int index;
char temp;
printf("Enter five characters\n");
scanf("%s", str);
printf("Please enter a number.\n");
scanf("%d", &index);
printf("Please enter a letter.\n");
scanf("%s", &temp);
str[index - 1] = temp;
printf("The five characters are now %s\n", str);
accessing the char array with the index variable is giving me the first element always.
FYI: I haven't code in C for a long, long time; however, I did run this code below successfully. You might have to review it and fix other things I might have missed.
First, we will change the first scanf by indicating we want only 5 characters scanf("%5c", str); and I'm indicating we want the last position in the array to have.
Next, we will do a for loop because we want to only accept an index between 1 to 5.
Finally, and this is important, we change the scanf to get one character; however, this isn't intuitive as before, because you need a space before the character indicator: scanf(" %c", &temp);
Code:
#include <stdio.h>
int main()
{
char str[5];
printf("Enter five characters\n");
scanf("%5c", str);
int index = -1;
while (index < 1 || index > sizeof(str)){
printf("Please enter a number 1 to %d.\n", (int) sizeof(str));
scanf("%d", &index);
}
char temp;
printf("Please enter a letter.\n");
scanf(" %c", &temp);
str[index - 1] = temp;
printf("The five characters are now %s\n", str);
return 0;
}
Result:
Enter five characters
12345
Please enter a number 1 to 5.
1
Please enter a letter.
x
The five characters are now x2345
...Program finished with exit code 0
Press ENTER to exit console.
#include <stdio.h>
int main()
{
char str[5];
int index;
char temp;
printf("Enter five characters\n");
scanf("%s", str);
printf("Please enter a number.\n");
scanf("%d", &index);
printf("Please enter a letter.\n");
scanf(" %c", &temp);
str[index - 1] = temp;
printf("The five characters are now %s\n", str);
return 0;
}
Output:
Enter five characters
12345
Please enter a number.
2
Please enter a letter.
x
The five characters are now 1x345
Press any key to continue . . .

Prompt user to re-enter number

I'm doing a practice 'do while' program where I want the user to enter three numbers and the program will print the sum on screen. After receiving the answer, the program will ask the user if he wants to enter another three numbers to get another answer, and so on. I'm fine with this.
If user enters anything other than an integer ("A,!,%") etc, I want the program to prompt the user to re-enter a number. See comments in program.
#include <stdio.h>
/*
Do - While
This program shall ask the user to enter
three numbers and print out the sum. Entering letters
or special characters will ask the user to re-enter that
number.
example:
Enter Number 1: 2
Enter Number 2: 5
Enter Number 3: 9
Answer is 16
...
Enter Number 1: 2
Enter Number 2: yum here user incorrectly enters letters
Enter Number 2: 8 re-prompted to enter number to continue
Enter Number 3: 9
Answer is 19
*/
int main(void) {
int a,b,c,ans,n;
do{
do{
printf("Enter Number 1: ");
scanf("%d", &a);
printf("\n");
}
while((a>0) || (a<0)|| (a==0));
do{
printf("Enter Number 2: ");
scanf("%d", &b);
printf("\n");
}
while((b>0) || (b<0)|| (b==0));
do{
printf("Enter Number 3: ");
scanf("%d", &c);
printf("\n");
}
while ((c>0) || (c<0)|| (c==0));
ans = a+b+c;
printf("Answer is %d\n\n", ans);
printf("Press 1 to start over, or 0 to quit...");
scanf("%d",&n);
printf("\n");
}while (n!=0);
return 0;
}
Your program contains multiple repeated sections. Since you are gathering three numbers, you should use a for loop which runs three times.
for (int i = 0; i < 3; i++) {
/* ... */
}
Inside the for loop, you're gathering the i+1-th number each time. If the user doesn't enter a valid number, you keep trying to gather it. So the do-while loop containing the printf and scanf will go inside the for loop.
for (int i = 0; i < 3; i++) {
do {
printf("Enter Number %d: ", i+1);
scanf( /* ... */ );
} while ( /* ... */ );
}
scanf returns the number of input items successfully read as an int. So the do-while loop should repeat as long as the return value of scanf is zero. We could store the return value in a variable and check the variable in the while (...);, but we can just move the scanf itself into the while (...);. We also need an array to store the three input numbers.
int n[3];
for (int i = 0; i < 3; i++) {
do {
printf("Enter Number %d: ", i+1);
} while (scanf("%d", n+i) == 0);
}
The rest of the program would loop over the array and store the sum of the elements. You would then output the sum. This approach is robust and maintainable as changing the amount of input numbers is easy and repeated or similar code sections are eliminated.
You can use fgets to get the input and use strtol() to cast the string the user input into an int. If strtol returns 0 when the user input does not start with a number or have a number in it. From there you can check if the user input is 0 and then reprompt the user until a is not 0.
*instead of scanf()*
char num1[5];
char *end;
fgets(num1, 5, stdin);
a = strtol(num1, &end, 10);
while( a = 0){
fgets....
}

How do I get multiple lines to print after ending this logical loop

Me again. The C rookie. I am working on an assignment to write a program that prompts a user to enter info after which the program should list back out the data that was entered. My code only prints the last record info that is entered.
For example, I enter the following info for employee #1 "Rookie Coder" as the first employee name and enter 25 and 40 for hourly wage and hours worked, respectively. Then, I enter the following info for employee #2 "Slow Learner" as the 2nd employee name and enter 20 and 45 for hourly wage and hours worked, respectively. The program only prints the info related to "Slow Learner". But I want to print out the info for both records entered.
Can someone please offer guidance on what I'm missing to get both records to print? Thank you from the C Rookie
// C Libraries Used
#include <stdio.h>
#include <math.h>
#include <string.h>
// Constant declerations
const float OTPAYFACTOR = 1.5;
FILE *userinputfile; //disk file (for input)
// Variable declerations
char deptname [21];
char firstname [10];
char lastname [10];
char fullname [21];
float hrsworked;
float hrwage;
int count;
char again;
// Function Prototypes
// M A I N F U N C T I O N
int main (void){
printf("Mountain Pacific Corporation\nDepartment Salary Program\n\n");
printf("Please enter the name of the department: ");
scanf("%s", &deptname);
count = 0; // Initialize this "counting" variable to zero to start
printf("\n");
count = 0; // Initialize this "counting" variable to zero to start
printf("\n");
do {
count++; // Increment the counting variable
printf("Enter employee #%d: ", count);
scanf("%s %s", &firstname, &lastname);
strcpy(fullname, firstname);
strcat(fullname, " ");
strcat(fullname, lastname);
printf("Enter the hourly wage of %s: ", fullname);
scanf("%f", &hrwage);
printf("Enter total number of hours: ");
scanf("%f", &hrsworked);
printf("\nThank you. Process another employee? ");
scanf ("%s", &again);
printf("\n");
} while (again != 'N' && again != 'n');
printf("End of processing.");
printf("%s, $%0.2f, %0.2f: \n", fullname, hrwage, hrsworked);
return 0;
}
You only have one set of variables that you use on each iteration of the loop. Anything stored the first time through the loop is overwritten the second time through the loop. So you'll only ever store the most recently entered set of values.
You want to declare each of the variables that are taking data as an array, that way you can save multiple values.
char deptname [5][21];
char firstname [5][10];
char lastname [5][10];
char fullname [5][21];
float hrsworked[5];
float hrwage[5];
...
do {
printf("Enter employee #%d: ", count+1);
scanf("%s %s", &firstname[count], &lastname[count]);
strcpy(fullname[count], firstname[count]);
strcat(fullname[count], " ");
strcat(fullname[count], lastname[count]);
printf("Enter the hourly wage of %s: ", fullname[count]);
scanf("%f", &hrwage[count]);
printf("Enter total number of hours: ");
scanf("%f", &hrsworked[count]);
printf("\nThank you. Process another employee? ");
scanf ("%s", &again);
printf("\n");
count++; // Increment the counting variable
} while (again != 'N' && again != 'n');
Then you need to loop through the array to print each element:
int i;
for (i=0; i<count; i++) {
printf("%s, $%0.2f, %0.2f: \n", fullname[i], hrwage[i], hrsworked[i]);
}
:) naive from your side but don't worry. You are storing only the last data into the fullname, hrwage, hrsworked, so only the last output is saved there. You need a better data structure to store the data as they are inserted by user.
1) If you know how many inputs there will be you can use a predefined array of strings for strings for the name and floats for the hours and wage.
2) if you don't know then you will need an scaling data structure like for example a list in order to put/add/append elements to it ;)
for C Arrays check this and for Lists in C check this
Then last but not least after you fill them with the input you just need to loop with a for / while loop in order to print the array or list.
Hope this will help!
remove the & symbol from below statement because deptname itself is string
scanf("%s", &deptname);
do same from below statements also
scanf("%s %s", &firstname, &lastname);
you want to print all records but at last there is only one printf so obviously it prints only last employee records
printf("%s, $%0.2f, %0.2f: \n", fullname, hrwage, hrsworked);
if you wants to prints all employee data after giving 'N' option, you should store information before that, my suggestion is put all entries inside structure and then take array of structure and store every time.

How to compare strings with user input?

I have a question in my paper. I have 10 employee ids M001,A004,D007,etc...User is inputting one of the the mentioned Ids and if the id is not there it prints id not found. I tired with strcmp and got stuck. Its good if you tell me a way to do it? Thanks, note: i am a beginner in C.I am trying an easy way now it gives the error with the for loop.
subscripted value is neither array nor pointer nor vector
#include<stdio.h>
#include<string.h>
float tSalary(float salary,float bonus);
char searchid(char search);
int main(void)
{
char status,input,search,C,P;
char searchId[8][4]={"M001","A004","D007","D010","D012","Q008","Q015","DE09"};
float salary,bonus,tSalary;
int i,j;
do{
printf("Enter the employee id: ");
scanf("%s", &search);
printf("Enter the job status: ");
scanf("%s", &status);
printf("Enter the salary: ");
scanf("%f", &salary);
for(i=0;i<8;i++){ //This is where all things go wrong
for(j=0;j<4;j++){
if(searchid[i][j]=search){ //the [i] where the subscripted error occurs
printf("Id is valid\n");
}
else printf("Invalid id\n");
}
}
printf("Do you want to enter another record?(Y-Yes/N-No): ");
scanf(" %c", &input);
}while(input=='Y'||input=='y');
return 0;
}
There are quite a few problems in the posted code. For starters, searchId should be declared as searchId[8][5], to make room for the \0 terminator at the end of each string.
It appears from the input code that status and search should hold strings, but these are declared as chars. After fixing this, note that there is no need for the address operator & in the calls to scanf() that read into these arrays. Also, maximum widths should always be specified when using the %s conversion specifier with scanf() to avoid buffer overflows.
Strings can not be compared using the == comparison operator, so strcmp() should be used here. This can be done in a loop that steps through the array of strings; the loop exits when the index reaches 8, or a comparison is successful. Then, after the loop, if the index has reached 8 (all valid id strings failed the test) the search string was not valid.
Here is a modified version of the posted code that implements all of this:
#include <stdio.h>
#include <string.h>
float tSalary(float salary,float bonus);
char searchid(char search);
int main(void)
{
char status[1000];
char search[1000];
char input, C, P;
char searchId[8][5] = { "M001", "A004", "D007", "D010",
"D012", "Q008", "Q015", "DE09" };
float salary, bonus, tSalary;
int i, j;
do {
printf("Enter the employee id: ");
scanf("%999s", search);
printf("Enter the job status: ");
scanf("%999s", status);
printf("Enter the salary: ");
scanf("%f", &salary);
i = 0;
while (i < 8 && strcmp(search, searchId[i]) != 0) {
++i;
}
if (i < 8) {
printf("Id is valid\n");
} else {
printf("Invalid id\n");
}
printf("Do you want to enter another record?(Y-Yes/N-No): ");
scanf(" %c", &input);
} while (input == 'Y' || input == 'y');
return 0;
}
Sample program interaction:
Enter the employee id: A004
Enter the job status: pending
Enter the salary: 2000
Id is valid
Do you want to enter another record?(Y-Yes/N-No): y
Enter the employee id: Q015
Enter the job status: completed
Enter the salary: 3000
Id is valid
Do you want to enter another record?(Y-Yes/N-No): y
Enter the employee id: B001
Enter the job status: completed
Enter the salary: 1200
Invalid id
Do you want to enter another record?(Y-Yes/N-No): n

C Code; nested do while loops with inputs

So I got some awesome assistance the other day with a C code problem, hoping this one can generate similar responses. First task is to write a code to accept an unknown number of names. Second is to allow input of an unknown number of values (grades) for each name, and each set of values is averaged and printed with the name. There is a similar thread i read and found some inspiration, but it still isn't compiling right.
I am not married to any particular part of this code, but I was trying to keep it simple with nested Do...while loops. I have tried several different approaches, all fall short of elegantly expressing the unknown number of values assigned to an unknown number of people.
My hope is that the user will be prompted to enter a name, then as long as that value isnt nulled out, the user is immediately prompted to enter grade values that are tabulated in a running total. When the value of grade goes null, the loop quits and the sum total is averaged. The name and average are printed together until the name value is null and then the sub quits. Greatly appreciate any input from the community.
#include <stdio.h>
#include <math.h>
int main(){
char b, stu_name;
float grade, sum, avg;
int i,counter;
do{
printf("Enter a student's name? \n");
scanf("%s", &stu_name);
do{
printf("How many grades are to be entered for this student? \n");
scanf("%d", &i);
for (counter = 0; counter < i; counter++) {
printf("Enter %s's grade, hit enter and enter another \n");
scanf("%f", &grade);
sum = sum + grade;
} while (grade != '\0');
avg = sum/i;
printf("GPA for %s is %f\n", stu_name,avg);
printf("Press any key to enter another student");
scanf("%c",b);
}while (b != '\0');
return(0);}
You're missing the ending brace on the for loop, as Helio Santos pointed out.
You're also having various syntax-type problems:
For the "Enter grade" prompt, you need a %c not a %s as you only
defined stu_name as a char not a char[]
The end of the interior Do/While loop should be checking against i, not grade
That check should also be against a value that scanf could return in your setup; the %d will force trying to get a numeric value
Bam! Compilation success. Thanks much, I appreciate the help. Doesn't look like i can test it fully (notice the whacked out GPA down below) because i don't know how use this online compiler to add a grade more than once (in the loop). If anyone knows whats going on with the GPA stdout i am all ears, going to the next step of the assignment with this code.
*edit after some more comments. Currently rockin the below code. It works...but only 3-4 times for some reason.
#include <stdio.h>
#include <math.h>
int main(){
char b;
char stu_name[75];
float grade, sum, avg;
int i,counter;
do{
printf("Enter a student's name? \n");
scanf("%s", stu_name);
b = '\0'
i = 0;
sum = 0;
printf("How many grades are to be entered for this student? \n");
scanf("%d", &i);
for (counter = 0; counter < i; counter++) {
printf("Enter %s's grade, hit enter and input another \n",stu_name);
scanf("%f", &grade);
sum = sum + grade;}
avg = sum/i;
printf("GPA for %s is %f\n", stu_name,avg);
stu_name[0]= '\0';
printf("Type q or Q to quit or enter to input another student \n");
scanf(" %c", &b);
} while (b != 'q' && b!='Q');
return(0);}

Resources