I need to do a program for school that reads few products and their price and then sort them in a list accodring by their price so im using array list to do it but when i print them i get random characters as output
#include <stdlib.h>
#include <stdio.h>
int main(){
int i = 0;
char list1[7];
char list2[7];
char list3[7];
while(i <= 3){
char name;
int price;
printf("Give me the product \n");
scanf("%s", &name);
printf("Give the price \n");
scanf("%d", &price);
if(price == 1){
list1[i] = list1[i] + name;
} else if(price == 2){
list2[i] = list2[i] +name;
} else if(price == 3){
list3[i] = list3[i] +name;
} else {
printf("Invalid number! \n Give us number 1,2 or 3");
printf("Give me the product \n");
scanf("%s", &name);
("Give the price \n");
scanf("%d", &price);
}
i = i + 1;
}
for (int z = 0; z <= 3; z++){
printf("%s",list1);
printf("\n");
printf("%s",list2);
printf("\n");
printf("%s",list3);
printf("\n");
}
}
#include <stdlib.h>
//Need string.h library to use strcopy
#include <string.h>
#include <stdio.h>
#define MAX_CHAR_SIZE 10
int main(){
//We define the maximum size of an array to be sure it will not overflow so the maximum character that list1,2,3 can contain is 10 including '/0' since you wanna print it as a string
char list1[MAX_CHAR_SIZE];
char list2[MAX_CHAR_SIZE];
char list3[MAX_CHAR_SIZE];
char name[MAX_CHAR_SIZE];
//I prefer unsigned if you know you don't to go in negative value
unsigned int price;
//Prefer for over while if you know how many time you need to loop
for (int i = 0; i < 3; i++){
printf("Give me the product \n");
scanf("%s", name);
printf("Give the price \n");
scanf("%u", &price);
if(price == 1){
//Copy name in list 1, you can't copy an array of x char in a single case of another array, 1 case of an array = 1 char
strcpy(list1, name);
}
else if(price == 2){
strcpy(list2, name);
}
else if(price == 3){
strcpy(list3, name);
}
else {
printf("Invalid number! \n Give us number 1,2 or 3");
printf("Give me the product \n");
scanf("%s", name);
printf("Give the price \n");
scanf("%u", &price);
}
}
//No need to loop over this 3 time only 1 is enough
printf("%s \n",list1);
printf("%s \n",list2);
printf("%s \n",list3);
}
I add comment over things I changed to make the initial objectives, IDK if it's the right goal but at least you got the same character in input and output, there was many things that wasn't right in your code you simply can't add the hexadecimal value of two character together to overwrite, you got to make something like list[I] = name[I].
And in C since we don't have the string type you got to create an array of char to make one AND BE SURE TO GET THE RIGHT SIZE TO FIT '\0'.
If it's your final exam a friendly advice, train a lot.
Looks like you forgot printf in one of your lines. Change ("Give the price\n"); to printf("give the price\n");.
It should work if I understand your question
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 10
int main(){
int n; //no of products
printf("Enter no. of products: ");
scanf("%d", &n);
char name[n][MAX_LENGTH]; //create multidimensional array to store namme
unsigned int price[n]; //array to store price. index will be similar to name
for (int i = 0; i < n; i++){ //Enter details
printf("Enter name: ");
scanf("%s", name[i]);
printf("Enter price: ");
scanf("%u", &price[i]);
}
int N = n;
while (N > 0){ //Run loop until index bigger than zero
char temp_string[MAX_LENGTH]; //create temporary variable
unsigned int temp_price; //to store values
int max_price_index = 0; //Index where max value is stored
for (int i = 1; i < N; i++){ //start loop from till end to search each value
if(price[i] > price[max_price_index]) //If searched value is bigger thar previous one(default at index 0)
max_price_index = i; //the replace it
}
strcpy(temp_string, name[N - 1]); //in next 7 lines name and price at max index is
strcpy(name[N - 1], name[max_price_index]); //swapped with values at index N (which is last of scope)
strcpy(name[max_price_index], temp_string);
temp_price = price[N - 1];
price[N - 1] = price[max_price_index];
price[max_price_index] = temp_price;
N--; //reduce the index by 1 making last value which was preiously maximum out of scope
}
for (int i = 0; i < n; i++){ //print details
printf("Name: %s\nPrice: %u\n", name[i], price[i]);
}
}
Related
New to programming/coding, and couldn't get why my code doesn't work.
It's supposed to show you the result of raising a number to another number. But it only ends up looping once.
Example of error:
Input an integer: 3
Raise integer to what number: 4
3 raised to 4 is 9
My code:
#include <stdio.h>
int raiseToPow(int nNum1, int *nResult) {
*nResult = nNum1 * nNum1;
}
int main() {
int nNum1, nNum2, nResult, i;
printf("Input an integer: ");
scanf("%d", &nNum1);
printf("\n");
printf("Raise integer to what number: ");
scanf("%d", &nNum2);
printf("\n");
for (i = 0; i < nNum2; i++) {
raiseToPow(nNum1, &nResult);
}
printf("%d raised to %d is %d", nNum1, nNum2, nResult);
}
you should initialize nResult by 1 because your variable doesn't have anything inside. Also, replace *nResult = nNum1 * nNum1 by *nResult = *nResult * nNum1
It's looping the right number of times, you just need to put the print inside the loop. Also you should add a newline to the end of your print.
for(i = 0; i < nNum2; i++)
{
raiseToPow(nNum1, &nResult);
printf("%d raised to %d is %d\n", nNum1, nNum2, nResult);
}
I'm getting implicit declaration error. Please help. I don't know how to explain it in terms of words, I'd appreciate it very much if you could help me with error. It's my assignment at school and I want to resolve the issue. Please help.
#include<stdio.h>
int printmenu(int *size_of_char);
int get_char(int **size_of_char);
int main() {
int choice = 0, size_of_char;
while (choice == 0) {
printf("Enter the size of the array: ");
scanf("%d", &size_of_char);
if (size_of_char <= 0) {
printf("Invalid input\n");
}
else {choice = printmenu(&size_of_char);
}
}
return 0;
}
int printmenu(int *size_of_char) {
int x;
printf("Menu\n\n");
printf("0. Input characters\n");
printf("1. Shift Elements to Right\n");
printf("2. Combinations of 2 digits\n");
printf("3. Exit\n");
printf("Enter choice: ");
scanf("%d", &x);
if (x == 0) {
get_char(&size_of_char);
}
}
int get_char(int **size_of_char) {
char string[**size_of_char];
for(int i = 0; i < **size_of_char; i++){
printf("Enter value: %c ", i+1);
scanf("%c", &string[i]);
for(int i = 0; i < **size_of_char; i++){
printf("Your grade in subject %d is %c.\n", i+1, size_of_char[i]);
//printf("Your grade in subject %d is %f.\n", i+1, *(grades + i));
}
}
}
Thanks
You've correctly included the header which declares printf in the example that you show.
There are other bugs however:
char string[**size_of_char];
This is ill-formed. The size of an array must be a compile time constant. That expression isn't.
int printmenu(int *size_of_char)
printmenu is declared to return int, but there is no return statement. The behaviour of the program is undefined.
// int **size_of_char
printf("Your grade in subject %d is %c.\n", i+1, size_of_char[i]);
You're trying to print a int* with a wrong format specifier. The behaviour of the program is undefined.
If I enter an amount of 5 players (5 elements in the score[] array) in the scanf("%d", &numPlayers) the for loop cycles the players all the way up to player 5 (element 4 of score[]), and then jumps to the winMsg function. The score of that element is a large value, even though I set all the score[] element's to 0 in the first for loop. If I enter 6 or more elements, the second for loop never executes. Program runs no problem with 4 or less elements in score[]. I am using gedit and terminal in Ubuntu. Any ideas? Fairly new to programming. I appreciate any help.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
int rollDie(){
return (rand()%6 + 1);
}
void winMsg(int winRoll, int player, int winScore){
printf("Congratulations Player %d! Your winning roll was a %d, putting your score at %d!\n\nGame Over\n\n", player + 1, winRoll, winScore);
return;
}
int main(){
srand(time(NULL));
int numPlayers = 0;
int roll = 0;
int i = 0;
int score[numPlayers];
char choice[2];
printf("Welcome to the \"Roll to Win\" game. Each roll adds to the current player's score, according to the die's number. A roll of 1 will cause the player to recieve no points that round, and then be skipped to the next player. First player to reach 100 or over wins! Please enter number of players: \n\n");
scanf("%d", &numPlayers);
printf("\n");
while (numPlayers >= 100 || numPlayers <= 0){
printf("Please enter a number of players less than 100, greater than 0.\n\n");
scanf("%d", &numPlayers);
printf("\n");
}
for (i = 0; i < numPlayers; ++i){
score[i] = 0;
printf("Set Player %d score to %d.\n", i + 1, score[i]);
}
printf("Starting with Player 1.\n\n");
for (i = 0; i < numPlayers; ++i){
roll = rollDie();
if (roll == 1){
printf("Player %d rolled a 1. Skipping turn. Current score: %d.\n\n", i + 1, score[i]);
}
else{
do{
score[i] += roll;
if (score[i] >= 100){
winMsg(roll, i, score[i]);
exit(0);
}
printf("Player %d rolled a %d, continue rolling (enter r to roll, or sr to stop rolling)? Current score: %d.\n\n", i + 1, roll, score[i]);
scanf("%s", choice);
printf("\n");
while ((strcmp ("r",choice) != 0) & (strcmp ("sr",choice) != 0)){
printf("Please enter a correct selection (enter r to roll, or sr to stop rolling).\n\n");
scanf("%s", choice);
printf("\n");
}
if (strcmp ("sr",choice) == 0){
printf("Player %d decided to stop rolling. Continuing to next player.\n\n", i + 1);
break;
}
roll = rollDie();
if (roll == 1){
printf("Player %d rolled a 1. Skipping turn. Current score: %d.\n\n", i + 1, score[i]);
break;
}
} while (strcmp (choice,"r") == 0);
}
if (i == numPlayers - 1){
i = -1;
}
}
}
Notice, that you set the size when initializing array before it is known, therefore you end up with garbage.
Doing int score[numPlayers]; and later scanf("%d", &numPlayers); will not do what you think it does.
it is not standard C++ to have a static array size which is not a constant,if you want that behavior you should use std::vector.
Even if this is working for you, then you should first ask for the number of players and then create the array. i.e
scanf("%d", &numPlayers);//first
....
int score[numPlayers];//then
When making a program that loops asking for the same variable multiple times and displaying some text that is different each time.Is there a more efficient way of doing that without having x amount of while loops?
#include <stdio.h>
#include <conio.h>
int main(void){
int loopcount;
int grade;
int avg;
int total;
total = 0;
loopcount = 0;
/* Displays "Enter your FIRST Grade" then stores the entered number in the variable grade
it then adds it to total and adds 1 to the loopcount */
while(loopcount<1){
printf("Enter your first grade: ");
scanf("%d", &grade);
total = total + grade;
loopcount = loopcount += 1;
}
/* Does the same thing but prints Enter your SECOND grade */
while(loopcount<2){
printf("Enter you second grade: ");
scanf("%d", &grade);
total = total + grade;
loopcount = loopcount += 1;
}
// etc etc
avg = total/2;
printf("Your average is %d", avg);
getch();
}
Use a static array with the info you want to by different:
static const char * const ordinal[] = { "first", "second" };
while(loopcount<2){
printf("Enter your %s grade: ", ordinal[loopcount]);
scanf("%d", &grade);
total = total + grade;
loopcount = loopcount + 1;
}
I have a program used to manage a database of records called "client_DB". The array "client_DB" is composed of customer cell phone call records. Each customer call record contains eight fields, which are as follows: 1) a ten digit cell phone number (string, no dashes), 2) the number of relay stations used in making the call (integer), 3) the length of the call in minutes (integer), 4) the net cost of the call (double), 5) the tax rate (double), 6) the call tax (double), 7) the total cost of the call (double) and 8) string field called "discount_aval with a value of "yes" or "no". The array client_DB has a capacity (SIZE) of 20 records.
It reads from an input file first called "client_data.txt" which is composed of these values:
9546321555 0 0 yes
5612971340 5 50 no
3051234567 8 25 no
7542346622 24 17 no
3054432762 15 30 yes
9544321011 50 100 yes
8776219988 87 82 yes
9042224556 4 5 yes
7877176590 11 1 no
5617278899 20 45 no
9546321555 4 3 yes
5612971340 79 86 no
3051234567 8 25 no
7542346622 24 118 no
3054432762 115 25 yes
9544321011 43 10 yes
8776219988 265 22 yes
9042224556 2 5 yes
7877176590 89 67 no
5617278899 40 56 no
My Remove function only removes the first value, if i type in to remove any other value, it simply wont! My Search function simply gives me back 2 numbers. Which is off and its not what i want. Help? I want to be able to ask the user for a cellnumber, then have it search the entire array and find it and delete it. I want my search grab an input also, find it and give me back its location. I tried but i dont know what i did wrong. In my main, i called both functions when the user selects it from the function Menu.
heres my code:
#include <iostream>
#include <string>
#include <fstream>
//************************************************************************
//Name: Kevin Due Date: 022113
//Instructor: Dr. Bullard Total Points: 100 pts
//Assignment2: client_call.cpp UsIDFAU:
//:
using namespace std;
const int CAPACITY = 20;
class client_db
{
public:
string cellnum;
int numofrelay;
int call_length;
double net_cost;
double tax_rate;
double call_tax;
double total_cost;
string discount_aval;
};
bool IsFull(int); //returns true if the array is full; otherwise false.
bool IsEmpty(int count);// returns ture if the array is empty; otherwise false.
void Add(client_db A[], int & count, client_db & db);
void Remove(client_db A[], int *count, string name);// removes an item from the array if it is there
void Print_DB(client_db A[], int count);//prints to output file
void Call_stats(client_db A[], int count);// prints all the items in the array
int Search_DB(client_db A[], int count, string name); //if the name is in the array, its location is returned
// //otherwise return -1;
//
bool IsFull(int count)
////Description: Determines if the array is full
{
return (count == CAPACITY);
}
bool IsEmpty(int count)
////Description: Determines if the array is empty
{
return (count == 0);
}
void Process (client_db A[], int count)
{
for(int i=0; i<count; i++)
{
if (A[i].numofrelay >=1 && A[i].numofrelay<=5)
{
A[i].tax_rate=0.01;
A[i].net_cost = ((A[i].numofrelay / 50.0)*0.40*A[i].call_length);
}
else if (A[i].numofrelay >=6 && A[i].numofrelay<=11)
{
A[i].tax_rate=0.03;
A[i].net_cost = ((A[i].numofrelay / 50.0)*0.40*A[i].call_length);
}
else if (A[i].numofrelay>=12 && A[i].numofrelay<=20)
{
A[i].tax_rate=0.05;
A[i].net_cost = ((A[i].numofrelay / 50.0)*0.40*A[i].numofrelay);
}
else if (A[i].numofrelay >=21 && A[i].numofrelay<=50)
{
A[i].tax_rate =0.08;
A[i].net_cost = ((A[i].numofrelay / 50.0)*0.40*A[i].call_length);
}
else if (A[i].numofrelay >50)
{
A[i].tax_rate =0.12;
A[i].net_cost = ((A[i].numofrelay / 50.0)*0.40*A[i].call_length);
}
A[i].call_tax = ((A[i].tax_rate)/(100))*(A[i].net_cost);
A[i].total_cost = A[i].net_cost + A[i].call_tax;
}
}
void Print_DB(client_db A[], int count)
//Description: Prints the items stored in A to the standard i/o device
{
string filename;
cout<<"Enter output filename: "; //geting filename
cin>>filename;
ofstream output; //declaring an output file stream
output.open(filename.c_str()); // c_str() converts a C++ string into a
// c-style string (char array) &
//open binds an ofstream to a file
for(int i=0; i<count; i++)
{
output<<A[i].cellnum<<"\t"
<<A[i].numofrelay<<"\t"
<<A[i].call_length<<"\t"
<<A[i].net_cost<<"\t"
<<A[i].tax_rate<<"\t"
<<A[i].call_tax<<"\t"
<<A[i].total_cost<<"\t"
<<A[i].discount_aval<<endl;
}
output.close();
}
int Search(client_db A[], int count, string cellnum)
////Description: Locates cellnumbers in A's fields
{
cout<<"Please enter a phone number: "<<endl;
cin>>cellnum;
for(int i=0; i<count; i++)
{
if (cellnum == A[i].cellnum)
{
cout<<i<<endl;
}
}
return -1;
}
void Add(client_db A[], int &count)
////Description: Adds key to the array
{
if (!IsFull(count))
{
cout<<"Enter a cellphone number, number of relay stations and the call lenght and if a discount is available: ";
cin>>A[count].cellnum>>A[count].numofrelay>>A[count].call_length>>A[count].discount_aval;
count++;
}
else
{
cout<<"The list is full\n";
}
}
void Add(client_db A[], int &count, client_db &db)
////Description: Adds key to the array
{
if (!IsFull(count))
{
A[count] = db;
count++;
}
else
{
cout<<"The list is FULL! \n";
}
}
void Remove(client_db A[], int *count, string cellnum )
////Description: Removes the number from the array is it is there
{
int loc = Search(A,*count,cellnum);
if (IsEmpty(*count))
{
cout<<"There is nothing to remove\n";
return;
}
else if (loc == -1)
{
cout<<"Number is not in data\n";
}
else
{
for(int j=loc; j<(*count)-1; j++)
{
A[j] = A[j+1];
}
(*count)--;
}
}
void Call_stats(client_db A[],int count) // prints to screen
{
for(int i=0; i<count; i++)
{
cout<<A[i].cellnum<<"\t"
<<A[i].numofrelay<<"\t"
<<A[i].call_length<<"\t"
<<A[i].discount_aval<<endl;
}
}
void Menu ()
{
cout<<"The values of the filename you entered have been recognized"<<endl;
cout<<"Please enter the letter of your application of choice"<<endl;
cout<<" "<<endl;
cout<<"************ WELCOME TO THE MAIN MENU ************"<<endl;
cout<<" Add an item...........................A"<<endl;
cout<<" Remove an item........................R"<<endl;
cout<<" Search for an item....................S"<<endl;
cout<<" Print current data....................P"<<endl;
cout<<" Print to output file..................O"<<endl;
cout<<"****************************************************"<<endl;
}
int main()
{
char answer;
char answer2;
client_db CLIENT[CAPACITY]; //declaring database
int count = 0; //initializing count
string cellnum;
string filename;
cout<<"Hello!, this program holds clients call data records."<<endl;
cout<<"Enter input filename: "; //geting filename
cin>>filename;
ifstream input; //declaring an input file stream
input.open(filename.c_str()); // c_str() converts a C++ string into
while(count<CAPACITY && !input.eof()) //reading until the end of the file (eof=end-of-file)
{
input>>CLIENT[count].cellnum
>>CLIENT[count].numofrelay
>>CLIENT[count].call_length
>>CLIENT[count].discount_aval;
count++;
}
do
{
Menu();
cout<<"Please enter a command letter: "<<endl;
cin>>answer;
client_db db;
switch (answer)
{
case 'A' :
cout<<"Enter a cellphone number, number of relay stations and the call lenght and if a discount is available: "<<endl;
cin>>db.cellnum>>db.numofrelay>>db.call_length>>db.discount_aval;
Add(CLIENT, count, db);
break;
case 'R' : Remove(CLIENT,&count,cellnum);
break;
case 'S' :
Search(CLIENT,count,cellnum);
break;
case 'P' : Call_stats(CLIENT,count);
break;
case 'O' :
Process(CLIENT,count); //how do i set the precision for this?
Print_DB(CLIENT,count);
break;
}
cout<<"Would you like to make another command?(y/n): "<<endl;
cin>>answer2;
} while (answer2 == 'Y' || answer2 == 'y');
cout<<"Goodbye"<<endl;
return 0;
}
That seems to be exactly what you want the function to return. Note that the phone number at index 2 and 12 are the same. If fact, it seems that are only 10 unique phone numbers in the list. Therefore, you will get 2 numbers as output when searching for each of those 10 numbers, since they all have one duplicate.
If you only want the first match to be printed, simply add a break; as follows:
for(int i=0; i<count; i++)
{
if (!(A[i].cellnum.compare(cellnum)))
{
cout<<i<<endl;
break;
}
}
in the Search function. If identical phone number are not desired, you could consider checking this before allowing the user to search for a phone number.
EDIT:
I see that your Remove function is not working properly either. You try to get the index of the phone number by using the Search function, but the search function always returns -1.
I would add the break as I mentioned above, and then return i instead of -1. Declare i outside of the for loop for this to work.
As you want all occurrences to be deleted upon choosing Remove, I would do the following:
In your main function:
case 'R' :
cout<<"Please enter a phone number: "<<endl;
cin>>cellnum;
Remove(CLIENT,&count,cellnum); break;
and
case 'S' :
cout<<"Please enter a phone number: "<<endl;
cin>>cellnum;
Search(CLIENT,count,cellnum); break;
Search:
int Search(client_db A[], int count, string cellnum){
int index = -1;
for(int i=0; i<count; i++)
{
if (!(A[i].cellnum.compare(cellnum)))
{
cout<<i<<endl;
index = i;
break;
}
}
return index;
}
And Remove:
void Remove(client_db A[], int *count, string cellnum ){
int loc;
while((loc=Search(A,*count,cellnum)) != -1){
if (IsEmpty(*count)){
cout<<"There is nothing to remove\n";
return;
}
else if (loc == -1){
cout<<"Number is not in data\n";
}
else{
for(int j=loc; j<(*count)-1; j++)
{
A[j] = A[j+1];
}
(*count)--;
}
}
}