r/C_Homework • • Sep 14 '20

Can anyone help me on this assignment?

0 Upvotes

Create a templated PlatonicSolid interface, see Platonic solid, and several classes that implement various polyhedrons. The classes, along with the their implementations should be written in the file platonicsolids.h.

Details and Requirements Write a C++ program that has following

a PlatonicSolid interface that has abstract functions, area(), and volume(). Implement classes for Tetrahedron, Cube, Octahedron, Dodecahedron, and Icosahedron, which implement above interface, with the obvious meanings for the area() and volume() functions. Implement classes, RightSquarePyramid and Parallelepiped, which have the appropriate inheritance relationships to Tetrahedron and Cube. Finally, write a simple user interface that allows users to create shapes of the various types, input their geometric properties, and then output their area and perimeter.


r/C_Homework • • May 12 '20

Please help with this assignment question, it is due tomorrow!!!! It will be greatly appreciated.

0 Upvotes

Question:

You are to read in two sets of numbers both of known size. The first set of numbers will be numbers the search will be searching into. The second set of numbers will be the numbers to be searched. Numbers are real numbers. You will declare as float for the first set of numbers, as double for the second set.

In both sets of numbers, the format is defined as follows.

  • The beginning line is a number indicating how many numbers there are in this set, followed by

  • numbers in this set one per line.

In your program, those two sets of numbers will be stored in two dynamically created arrays. In this assignment, you are to do the following.

  1. Search each number in the second set to see if it is in the first set, print the index, and obtain the comparison count by using the linear search algorithm.

  2. Sort the first set by using a selection sort algorithm.

  3. Search each number in the second set to see if it is in the first set, print the index, and obtain the comparison count by using the binary search algorithm. For the binary search, calculate Mid as (Low + High) / 2.

In the first three lines of the output, print your name, Date, and assignment name.


r/C_Homework • • Apr 27 '18

New C++ user. Need help with Final Program for class.

0 Upvotes

I really hate to ask for help but Im having a real hard time with this program. If I post up the final, could I get some help?


r/C_Homework • • Jun 11 '18

can anyone help me understand how my program worked? (intro to c++)

0 Upvotes

this is my assignment.

Consider an input file A1.txt. Each line of A1.txt consists of two numbers separated by space. Write a C++ program that reads the two numbers from each line and adds all the integers between those two numbers (starting from the first number and ending at the second. Show your output in B1.txt

include <iostream>

include <fstream>

using namespace std;

int main(){ int a, b; //variables int sum = 0;

ifstream input("A1.txt"); 
ofstream output("B1.txt");
//reading the file
while (input)
{input >> a >> b; //reads the first and 2nd numbers
	
	
	
	if (a <= b)
	{
		for (int i = a; i <= b; i++)
			sum = sum + i;
		output << sum << endl;}
}
input.close();
output.close();
return 0;

}

can anyone help me understand what happens after it reads the a and b? i had to mess around with this for more than one hour to get it to work.


r/C_Homework • • Jul 11 '21

can you please explain the output of a two-dimensional array

0 Upvotes
using System;
public class Program
 {
 
 public static void Main(string[] args)
 {
 int i, j;
 int [,] A = new int[5,5];
 for (i = 0; i < 5; ++i)
 {
 for (j = 0; j < 5; ++j)
 {
 A[i,j] = i*i;
 } 
 }
 for (i = 0; i < 4; ++i)
 {
 for (j = 0; j < 5; ++j)
 {
    if (i < 5)
     {
         A[j, i] = A[i, j];
 }
    else
    break;
    Console.Write(A[i, j] + " ");
 }
 Console.WriteLine();
 }
 Console.ReadLine();
 }
 }

and the output is

0 0 0 0 0
0 1 1 1 1
0 1 4 4 4
0 1 4 9 9

r/C_Homework • • Jan 06 '18

HELP IN A TETRIS GAME C LANGUAGE

0 Upvotes

Hi guys, i've been doing a tetris program trough a tutorial i found and loved the tutorial and made it trought but now i have an assignment for school similar to tetris but instead of the blocks the program asks a string with at least 4 characters and use that word to make the line, can i someone help me how can i do it? I leave the link with the program. http://javilop.com/files/tetris_tutorial_sdl.zip


r/C_Homework • • Feb 23 '17

I'm having a bit of trouble trying to program a dynamic currency converter, the math doesn't seem to want to work, please, help me, I'll message my code to someone if they are interested.

0 Upvotes

r/C_Homework • • Feb 05 '17

How to convert inches to feet and inches using a while loop with / and % operators

0 Upvotes

Hey! So I'm quite new to using while loops and am stuck here. Would anyone be able to help me on this one or point me in the right direction? It's a part of a larger program I am trying to create. Thanks for any help!


r/C_Homework • • Jun 30 '18

How do i call a function that just collects user input??

0 Upvotes

include <iostream>

include <math.h>

include <cmath>

using namespace std; double UserInput(double cr, double last, double two); double InflationCalc(double cr, double last, double two);

int main(){

cout << UserInput();



return 0;

}

double UserInput(double cr, double last, double two){ cout << "Enter the current price of the item:" << endl; cin >> cr; cout << "Enter the price of of the item one year ago:" << endl; cin >> last; cout << "Enter the price of the item two years ago:" << endl; cin >> two;

enum numbers{cr,last,two};

return numbers();
}

//calc the inflation rate double InflationCalc(double cr, double last, double two){

UserInput(cr, last, two);   //gets values from the input function

double ci = (cr - last) / last;
double TwoYears = (last - two) / two;

enum values{ci,twoyears};
return values();

}

how do i call the function that asks the user for input into my main?? all it does is get info from the user then that info gets used in the other function


r/C_Homework • • Apr 30 '21

another help in my code

0 Upvotes

I have to make a program where it reads from a file and then enter a string with letter, symbols and numbers and then it have to print only the letters in reverse way, now i have to use recursive function for the letters and I must use prints in the main function not in the recursive function for example if the file the program reads from has :

input :#$f^t&^$q&%Y &^q~!$n!@n&@g%$#J*/&^(%

output : Hello Word

NOTE : ALL that wouldn't happen to me if I haven't been asked to use print only in the main function, and also when there is a symbol or number it avoids the if statements and the function

The main question is : how I can use printf in the main function and be used properly where it should print reverse way and the symbols shouldn't be shown, in the function itself those thing works btw

here is my code :

int decode(char x[])
{ 
    if (!x[0])
    {
        return 1;
    }
decode(x+1);
    if ( x[0]== ' ' || x[0]== ',' ||((x[0]>='A' && x[0]<='Z') || (x[0]>='a' && x[0]<='z' ) ) )
    { // here each string i enter at makes it backward by -2 for example c-->a
        switch(x[0])
        {
        case 'A':
            x[0]='Y';
            break;
        case 'B':
            x[0]='Z';
            break;
        case 'a':
            x[0]='y';
            break;
        case 'b':
            x[0]='z';
            break;
        case ',':
            x[0]=',';
              break;
              case ' ':
              x[0]=' ';
              break;
              default:
              x[0]-=2;
              break;
        }
else 
return ;
   }
here is the main function 
int main()
{
    FILE *fp;
    char str[1000];
    char filename[100];
    scanf("%s",filename);// here i have to enter the file name to get all the strings from another file //
    fp = fopen(filename, "r");
    if (fp == NULL)
    {
        printf("Could not open file %s",filename);
        return 1;
    }
    while (fgets(str,1000, fp) != NULL)// the problem start here it get the strings input
    {
            decode(str);
            printf("%s",str);// and in the printf it prints everything where it should only print the letters in revrse way
        fclose(fp);
    }

r/C_Homework • • Sep 29 '17

Beginner C Programming Assignment

0 Upvotes

So, I'm trying to write a word search program that is directed towards a file with the : cat data1 | ./WordSearch type of input. So I basically have to use scanf. What I'm having trouble with is reading in the characters that are part of the crossword and not part of the words that I'm searching for. I've tried a number of things, mainly looking for a '\n' character so as to stop taking in input when I reach the end of the first line so that I know how big the word search will be. (It will always be NN length with a maximum length of 5050). Also, I have to use a two-dimensional array for the input. But the biggest hurdle that I need help with is getting the input stored into my two-dimensional array. Any help or pointers would be greatly appreciated as I've been stuck for several hours and haven't been able to make any headway whatsoever. =/ Thanks in advance to anyone who takes the time to help me!

The code I have so far is:

include <stdio.h>

include <stdlib.h>

int main() { char str[1000]; char * text; int counter = 0; do{

        scanf("%s", str);
        printf("%s ", str);

} while(scanf("%c",str) != EOF);

And the input file I'm given looks like this: S T E L B M T F E Y D E E P S R T C I A E E N N E L I T R L B D E T A R E M U N E T Y L N O I T A N I M I R C N I F L E S S E N T A A U I D E W A R R A N T N U P R U S S E R P P G S G E A L P A P B A N P S A S S N M E A C O N S I T U T I O N D E E C W S O O H P D S V W D E L A N E E J A M E S M A D I S O N A E D E S N E G R J C U L T N O H L T I R A A R C E R R T R E E S B O N E E I D N N P R S N J U D I C I A L A S S E C O R P E U D I S M R A R A E B W B E S S M E O A U V P E M O E O I A I L N O U C D O D S S E N N I G R L N I D G Y T R C O M P E N S A T I O N N D D T O Z E H P Y N D R L E E A O H S C O I B I T P S U E T G O L U Z M M R B E H P I R T E O I E A R R S U U I B H A Y L L M S T F A R I N R E E E F U T L V Q U A R T E R I N G S I D B S R R D I Y E N I G M I A N A T I R S Q I S E B S C N S P E E C H R O T A E Y N D L C M I L I T I A F L R N C A T S S P S E R U T E D Y L E B I L C O H M L E T E S Y Y L S T R T E W Z L I O S A E N S A E I Y A L AMENDMENT ASSEMBLY BAIL BEARARMS CITIZEN CIVIL COMPENSATION CONGRESS CONSITUTION CONVENTIONS DELEGATED DOUBLEJEOPARDY DUEPROCESS ENUMERATED FREEDOM GOVERNMENT ILLEGAL INDICT INFRINGED JAMESMADISON JUDICIAL LAWSUIT LIBEL LIBERTY LIFE MILITIA MIRANDA NECESSARY PEACEABLY PEERS PETITION POWER PRESS PROBABLECAUSE PROPERTY PUNISHMENTS QUARTERING RELIGION RIGHTS SEARCH SECURITY SEIZURE SELFINCRIMINATION SLANDER SOLDIERS SPEECH SPEEDY TRIAL UNREASONABLE WARRANT WITNESS


r/C_Homework • • May 01 '22

Desperate mech eng undergraduate needs help in c++ numerical analysis project

0 Upvotes

I cant adjust the following code of 2 dimensions Bezier to 3 dimensions Bezier. Any help will be much appreciated

#include <iostream> #include <fstream> #include <cmath> #include <vector> using namespace std; vector < vector <double> > bezm(25, vector <double> (25)); void paragon(int n, int i, int &k) { int ks = max(i,n-i)+1; int kp = min(i,n-i); k=1; for(int iii=ks;iii<=n;iii++) k = kiii; for(int iii=1;iii<=kp;iii++) k = k/iii; } void inibezier(int nco) { int kres1,kres2,kres3; for(int mi=0;mi<nco;mi++) { double b=0.e0; double c=0.e0; for(int i=0;i<nco;i++) { paragon(nco-1,i,kres1); paragon(i,mi,kres2); kres3=pow(-1,(i-mi)); double coeffi = double(kres1kres2kres3); if(mi>i) coeffi=0.e0; bezm[mi][i]=coeffi; } } } void usebezier( vector <double> xco, vector <double> yco, int nco, vector <double> &x , vector <double> &y , int ideg) { double aa1 = 0.5e0; double dd = 0.1e0; for(int k=0;k<=ideg+1;k++) y[k] = double(k-1)/double(ideg); for(int kpoi=0;kpoi<=ideg+1;kpoi++) { int kpoi1=kpoi;//+1; double tlocal = y[kpoi1]; x[kpoi1]=0.e0; y[kpoi1]=0.e0; for(int mi=0;mi<nco;mi++) { double b=0.e0; for(int i=0;i<nco;i++) b = b + bezm[mi][i]pow(tlocal,i); x[kpoi1] += bxco[mi]; y[kpoi1] += byco[mi]; } } } int main(int argc, char** argv) { string line; vector <double> val(1000,0); vector <double> x(1000,0); vector <double> y(1000,0); vector <double> xb( 25,0); vector <double> yb( 25,0); ifstream in("bezier.dat"); int nb=0; for(int i=0;i<26;i++) { in>>xb[i]>>yb[i]; getline(in,line); if(in.eof()) { nb = i; break; } } in.close(); inibezier(nb); int ideg; cout<<"Type the number of points along the final curve"<<endl; cin>>ideg; usebezier(xb,yb,nb,x,y,ideg-1); ofstream out("curve"); for(int i=1;i<ideg+1;i++) out<<"\t"<<x[i]<<"\t"<<y[i]<<endl; out.close(); }


r/C_Homework • • Jul 30 '21

problems and confusion with class and methods....

0 Upvotes

here is what i need to do...

Write a C# application that implements a class ‘Employee’ with the following members. i. Six private data members ‘BasicSalary’, ‘HRA’, ’Deductions’, ‘Allowance’, ‘Insurance’ and ‘NetSalary’ of integer data type.

ii. A default constructor to display the message “Employee Pay Bill”.

iii. Four public methods, setMembers(), calcDed(), calcNet(), and disResult().

  1. setMembers() – set the values of BasicSalary as 2000, HRA as 200, Insurance as 100 and Allowance as 50.

  2. calcDed() – calculate and return the Deductions using the formulae “Deductions = Insurance + Allowance”.

  3. calcNet() – calculate and return the NetSalary using the formulae “NetSalary = BasicSalary + HRA – Deductions”.

  4. disResult() – display BasicSalary, HRA, Deductions and NetSalary

the output should look like

Employee Pay Bill
Basic Salary = 2000
HRA = 200
Deductions = 150
Net Salary = 2050

it says i have 6 errors

and this is the class Employee

using System;
using System.Collections.Generic;
using System.Text;

namespace Final_THE_M109
{
    class Employee
    {
        private int BasicSalary;
        private int HRA;
        private int Deductions;
        private int Allowance;
        private int Insurance;
        private int NetSalary;
        public void setMembers(int B, int H, int A, int I)
        {
            BasicSalary = B;
            HRA = H;
            Allowance = A;
            Insurance = I;
        }
        public int calDed()
        {
            int Deductions = Insurance + Allowance;
            return Deductions;
        }
        public int calcNet()
        {
          int  NetSalary = BasicSalary + HRA – Deductions; // i get a red line under the (-) and (deductions)
            return NetSalary
        }
        public void disResult()
        {
            Console.WriteLine("Basic Salary = ", setMembers(B)); // i also get a red line under (B)
            Console.WriteLine("HRA = ", setMembers(H));// a line under (H) too
            Console.WriteLine("Deductions = ", calDed());
            Console.WriteLine("Net Salary = ", calcNet());
        }
    }
}

now the code for the main method

using System;

namespace QuestionTwo
{
    class Program
    {
        public static void Main(string[] args)
        {
            Employee e = new Employee();
            Console.WriteLine("Employee Pay Bill");
// it gives me a red line under every setMembers
            int B = 2000;
            e.setMembers(B);
            int H = 200;
            e.setMembers(H);
            int A = 50;
            e.setMembers(A);
            int I = 100;
            e.setMembers(I);
            e.disResult();
        }
    }
}

r/C_Homework • • Apr 21 '17

Help! Segmentation Fault

0 Upvotes

I have written some code in order satisfy my c++ homework. The question reads as follows:

You are asked to write an app to keep track of a relatively small music library. The app should load song information from a data file once the app is started. It should allow user to view, add, remove, and search for songs. The app should save the data back to the same data file when the program exits. What Your Program Should Do: Write an interactive text based menu interface (using a loop) that will allow the user to  Enter information for a new song  Display information for all the songs in the database with index for each song  Remove a song by index  Search for songs by a certain artist  Search for songs by a certain album  Quit For each song, you need to keep track of:  title  artist  duration  album Allow the program to keep looping until user wants to quit. When the program starts, it should load the tasks from external file ("songs.txt") into memory. When user enters information about the new song, the program needs to read them in, save them in memory and eventually write them to the external data file ("songs.txt").

Unfortunately, though the code compiles, when I try to use the commands inside, I keep getting a Segmentation error. Any ideas? Here is my code right now: /**/

include <iostream>

include <cstring>

include <iomanip>

include <fstream>

using namespace std;

int NO_OF_SONGS;

struct songInfo { char title[30]; char artist[30]; int durationMin; int durationSec; char album[30]; };

void addSong (songInfo list[], int& listSize); void removeSong (songInfo list[], int& listSize); void displayList (songInfo list[], int listSize); void searchList (songInfo list[], int listSize); void readList (ifstream& infile, songInfo list[], int& listSize); void printList (ofstream& outfile, songInfo list[], int listSize);

int main() { songInfo trackListing[NO_OF_SONGS];

char selection;

cout << "*Music Track Database*" << endl;

do
{
ifstream infile ("songs.txt");
ofstream outfile;

	if (!infile)
            	{
                    cout << "Cannot open file: songs.txt";
            	}

	cout << "Main Menu:" << endl;
	cout << endl;
	cout << "(a)dd a song" << endl;
	cout << "(r)emove a song" << endl;
	cout << "(d)isplay track listings" << endl;
	cout << "(s)earch for a track" << endl;
	cout << "(q)uit" << endl;
	cout << endl;
	cout << "Select (a, r, d, s, q): ";
	cin >> selection;
	cout << endl;

	if (selection != 'a' && selection != 'r' && selection != 'd' && selection != 's' && selection != 'q')
	{
		cout <<  "Select (a, r, d, s, q): ";
            	cin >> selection;
		cout << endl;
	}

	switch (selection)
	{
		case 'a':
			readList(infile, trackListing, NO_OF_SONGS);
			addSong(trackListing, NO_OF_SONGS);
			printList(outfile, trackListing, NO_OF_SONGS);
			break;
		case 'd':
			readList(infile, trackListing, NO_OF_SONGS);
			displayList(trackListing, NO_OF_SONGS);
			break;
		case 'r':
                            cout << "Remove a Song" << endl;
		case 's':
			do
			{
			readList(infile, trackListing, NO_OF_SONGS);
			searchList(trackListing, NO_OF_SONGS);
		
			cout << "(r)emove song" << endl;
			cout << "(s)earch again" << endl;
			cout << "(m)ain menu" << endl;
			cout << "(r, s, m): ";
			cin >> selection;
			cout << endl;
			cout << endl;
			
				if (selection != 'r' && selection != 's' && selection != 'm')
					{
					cout << "(r, s, m): ";
					cin >> selection;
					}
				if (selection == 'r')
					{
					removeSong(trackListing, NO_OF_SONGS);
					printList(outfile, trackListing, NO_OF_SONGS);
					}
			}while(selection != 'm');
			break;
	}
}while (selection != 'q');

cout << "Happy Trails To You; Until We Meet Again!" << endl;

return 0;

}

void addSong (songInfo list[], int& listSize) { int i = ++listSize; cout << "Add a Song" << endl; cout << endl; cout << "Enter Song Title: "; cin.ignore(); cin.get(list[i].title, 30); cout << endl;

	cout << "Enter Artist Name: ";
	cin.ignore();
	cin.get(list[i].artist, 30);
	cout << endl;

	cout << "Enter Track Duration: ";
	cout << endl;
	cout << "(Seperate mins & secs with a space.";
	cout << endl;
	cout << "ex: if 3:40, enter 3 40): ";
	cin >> list[i].durationMin >> list[i].durationSec;
	cout << endl;

	cout << "Enter Album Title: ";
	cin.ignore();
	cin.get(list[i].album, 30);
	cout << endl;
	cout << endl;
	cout << "Song Added to Database!";
	cout << endl;
}

void readList (ifstream& infile, songInfo list[], int& listSize) { int i = 1; while (!infile.eof()) { infile.ignore(); infile.ignore(); infile.get(list[i].title, 30); infile.ignore(); infile.ignore(); infile.get(list[i].artist, 30); infile.ignore(); infile >> list[i].durationMin >> list[i].durationSec; infile.ignore(); infile.ignore(); infile.ignore(); infile.get(list[i].album, 30); i++; } listSize = i; } void printList (ofstream& outfile, songInfo list[], int listSize) { outfile.open ("songs.txt"); int i; outfile << left << setw(14) << '#' << left << setw(21) << "Song Name" << left << setw(21) << "Artist Name" << left << setw(20) << "Duration" << left << setw(22) << "Album Title" << endl; outfile << left << setw(76) << setfill ('-') << '-' << endl; outfile << setfill (' '); for (i=1; i<listSize; i++) { outfile << left << setw(2) << i << left << setw(32) << list[i].title << left << setw(32) << list[i].artist << right << setw(4) << list[i].durationMin << ':' << left << setw(5) << list[i].durationSec << left << setw(32) << list[i].album << endl; } outfile << left << setw(78) << setfill ('-') << '-' << endl; } void removeSong (songInfo list[], int& listSize) { int i; int e; cout << "Enter Track Number to Confirm Deletion: "; cin >> e; cout << endl;

for (i=0; i<listSize; i++)
	{
	if (e==i)
		{
		for(i=e; i<listSize; i++)
			{
			list[i] = list[i+1];
			}
		listSize--;
		}
	}
}

void displayList (songInfo list[], int listSize) { int i; cout << left << setw(14) << '#' << left << setw(21) << "Song Name" << left << setw(21) << "Artist Name" << left << setw(20) << "Duration" << left << setw(22) << "Album Title" << endl; cout << left << setw(110) << setfill ('-') << '-' << endl; cout << setfill (' '); for (i=1; i<listSize; i++) { cout << left << setw(2) << i << left << setw(32) << list[i].title << left << setw(32) << list[i].artist << right << setw(4) << list[i].durationMin << ':' << left << setw(5) << list[i].durationSec << left << setw(32) << list[i].album << endl; } cout << left << setw(110) << setfill ('-') << '-' << endl; } void searchList (songInfo list[], int listSize) { char aOrB; int i; char artist[30]; char album[30];

cout << "Search by (a)rtist or al(b)um? (a or b): ";
cin >> aOrB;
cout << endl;

if (aOrB != 'a' && aOrB != 'b')
	{
	cout << "(a or b): ";
	cin >> aOrB;
	cout << endl;
	}
if (aOrB == 'a')
	{
	cout << "Artist Name: ";
	cin.ignore();
	cin.get(artist, 30);
		
	for(i=0; i<listSize; i++)
		{
		if (artist == list[i].artist)
			{
			cout << left << setw(2) << i << left << setw(32) << list[i].title << left << setw(32) << list[i].artist << right << setw(4) << list[i].durationMin << ':' << left << setw(5) << list[i].durationSec << left << setw(32) << list[i].album << endl;
			}	
		else
			cout << "Artist not found" << endl;
		}	
	}
else
	{
	cout << "Album Name: ";
            cin.ignore();
	cin.get(album, 30);
           
            for(i=0; i<listSize; i++)
                    {
                    if (album == list[i].album)
                            {
                            cout << left << setw(2) << i << left << setw(32) << list[i].title << left << setw(32) << list[i].artist << right << setw(4) << list[i].durationMin << ':' << left << setw(5) << list[i].durationSec << left << setw(32) << list[i].album << endl;
                            }
		else
			cout << "Album not found" << endl;
                    }
            }
}

r/C_Homework • • Apr 16 '17

How to create a struct item in a struct item(sku) function?

0 Upvotes

I am trying to make an inventory system and want to create a new struct item with the sku in the function parameter. But also have output.

struct item ItemEntry (int sku)

This function receives an integer argument for sku and creates an Item and sets its sku to the sku argument value. Then it will prompt the user for all the values of the Item (except the sku that is already set) in the following order: Name, Price, Quantity, Minimum Quantity and Is Taxed. To get the name from the user, use the this format specifier in scanf: "%20[\n]" and then clear the keyboard using flushKeyboard() function. This format specifier tells to scanf to read up to 20 characters from the keyboard and stop if “\n” (ENTER KEY) is entered. After this flushKeyboard() gets rid of the “\n” left in the keyboard.

Here is the format of the data Entry: (Underlined Italic Bold Red values are user entries)

SKU: 999 Name: Red Apples Price: 4.54 Quantity: 50 Minimum Qty: 5 Is Taxed: n

This is what I have:

struct Item itemEntry(int sku)
{

    int sku1 = sku;
    printf("SKU: %d\n", sku1);

    char name;
    printf("Name: ");
    scanf("%20[^\n]", &name);
    flushKeyboard();

   double price;
   printf("\nPrice: ");
   price = getDouble();

   int quantity;
   printf("\nQuantity: ");
   quantity = getInt();

   int minQuantity;
   printf("\nMinimum Qty: ");
   minQuantity = getInt();

   int isTaxed;
   printf("\n Is Taxed: ");
   isTaxed = yes();

    struct Item item(price, sku1, isTaxed, quantity, 
minQuantity, name);
};

r/C_Homework • • Feb 09 '19

Need help with this if statement

0 Upvotes

o Read x1, y1, x2, y2

o Read x3, y3, x4, y4

o Compute vectors r, s, and q

o Compute cross-products qxs, qxr, and rxs

o Compute auxiliary values: q*r, r*r, q*s, and s*s

o If rxs is zero and qxr is zero, then

§ The two lines are collinear

· If 0 <= q*r <= r*r or 0 <= q*s <= s*s

o The two lines are overlapping

· else

o The two lines are disjoint

o If rxs is zero and qxr is not zero

§ The two lines are parallel and not intersecting

o If rxs is not zero , compute t and u

§ If 0 <= t <= 1 and 0 <= u <= 1

· The two lines intersect at P1+t*r

§ else

The two line segments do not intersect


r/C_Homework • • Oct 22 '16

would anyone be able to proof read my code?

0 Upvotes

Okay so ive coded this program to convert regular numerals to roman numerals. Now I have done this in both C and C++ but I want it strictly in C. Can you guys help me to get this to compile in C?

Here is the code:

#include <stdio.h>
#include <stdlib.h>

int main(void) {

int roman;
int integer;
int piece;

printf("enter a number: ");
fflush(stdout);
scanf("%d", &integer);

if (integer >= 4000 || integer <= 0 ){
	printf("error invalid int\n");
	}

else {

		//thousands
	if (integer >= 1000){
		for (int i = 0; i<piece; i++){
			roman += 'M';
		}
		integer %= 1000;
	}
	// Hundreds
		if (integer >= 100){
			piece = (integer == 9){
				roman += "CM";
			}
			else if (piece >= 5){
				roman += 'D';

				for (int i = 0; i< piece - 5; i++){
					roman += 'C';
				}
			}

			else if (piece == 4){
				roman +='CD';
			}
			else if (piece >=1){
				for(int i = 0; i< piece; i++){
					roman += 'C';
				}
			}
			integer %= 100;
		}
	//tens
		if (integer >= 10){
			piece = (integer /10);
			 if (piece == 9){
				 roman += "XC";
			 }
			 else if (piece >=5){
				 roman += "L";

				 for(int i = 0; i<piece -5; i++){
					 roman += "x";
				 }
			 }
			 else if (piece == 4){
				 roman += 'X';
			 }
		}
		integer %= 10;

}
//ones
		if(integer >= 1){
			piece = integer;

		if (piece == 9){
			roman += "IX";
		}
		else if (piece >= 5){
			roman += 'V';

			for(int i = 0; i<piece -5; i++){
				roman += "I";
			}
		}
		else if (piece >= 1){
			for(int i = 0; i<piece; i++){
				roman += "I";
			}
		}
}



		printf("Roman Numeral: %d", roman);

return EXIT_SUCCESS;

}


r/C_Homework • • Dec 07 '17

Help with c++ hw involving a class of arrays

0 Upvotes

Hey there; I got pretty far but now I'm getting stuck, and I know it's something really stupid so I'm hoping it'll be an easy "DOH" moment:
Code:
https://pastebin.com/J36dDXSH
Assignment:
https://pastebin.com/VyqXfAq3

It's throwing an "Id returned 1 exit status" error, with it also saying something about how the two Seller constructors have undefined refrences?


r/C_Homework • • Jan 21 '21

C Math

0 Upvotes

For this program, the user will enter the total length of the track and the maximum length of the trains for the track. It is assumed that the trains formed will be as long as possible. For example, if the user enters 30 for the maximum length of the train, then the actual trains will have three cars and be of length 26, since a four car train would exceed 30 feet. Your program should calculate the number of people that can be supported on the track at one time. (Note: It may be the case that more people can be supported by making a shorter train than possible, but for this particular assignment, maximize the size of each train.)

#include<stdio.h>

#define FIRST_CAR_LENGTH 10

#define NORMAL_CAR_LENGTH 8

#define CAR_CAPACITY 4

int main()

{

int trackL,trainL,trainL2;

float CarLength_Total;

printf("What is the total length of the track, in feet?");

scanf("%d",&trackL);

printf("What is the maximum length of the train, in feet?");

scanf("%d",&trainL);

trainL2= trainL-FIRST_CAR_LENGTH;

float Car_Length=(trainL2/NORMAL_CAR_LENGTH);

printf("Your ride, can have at the most %4.2f",Car_Length);

}


r/C_Homework • • Dec 14 '21

Convert java to C ( chudnovsky algorithm )

0 Upvotes

Hi i need to convert my java code to C but its been really difficult.

This is my code that i need to convert:

import java.lang.Math.sqrt;
import java.math.RoundingMode;
import java.lang.Math;
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;

// Calculating the digits of PI using the Chudnovsky algorithm
public class PIDigits {
    // Utility function to calculate factorials
    public static double factorial(int n)
    {
        if(n==0)
        {
            return 1;
        }
        else
        {
            return n*factorial(n-1);
        }
    }

    /** 
    * Returns a term of from the infinite series in the Chudnovsky algorithm.
    * @param n represents the term (nth term)
    * @return  a double representing the nth term, approximately equal to 1/Pi
    */
    public static double chudnovsky(int n)
    {
        // From the numerator 
        double numerator = Math.pow(-1,n)*factorial(6*n) * (545140134*n + 13591409);
        // From the denominator
        double denominator = factorial(3*n) * Math.pow(factorial(n), 3) * Math.pow(640320,3.0*n+3.0/2.0);
        
        if (n==0)
        {
            return 12.0*numerator/denominator;
        }
        
        return 12.0*numerator/denominator + chudnovsky(n-1);
    }
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of digits you want to see from PI.\nUp to 14 digits");
        
        int n = 0;
        while(sc.hasNext())
        {
            // If invalid input, exit the loop/program
            try
            {
                n = sc.nextInt();
            }
            catch(InputMismatchException e)
            {
                System.out.println("Invalid value (letters, float, etc). EXITING");
                break;
            }
            finally{
                if(n>14)
                {
                    n=14;
                }
                else if(n<0)
                {
                    System.out.println("Invalid value (negative value)");
                    n = sc.nextInt();
                }    

                // Formatting the output to have specified digits
                NumberFormat fmt = NumberFormat.getInstance(Locale.US);
                
                fmt.setMaximumFractionDigits(n);
                fmt.setRoundingMode(RoundingMode.FLOOR);

                System.out.println(fmt.format(1.0/chudnovsky(2)));
            }
        }
        sc.close();
    }
    
}}

This is what ive done:

#include<math.h>
#include<stdio.h>

   double factorial(int n)
    {
        if(n==0)
        {
            return 1;
        }
        else
        {
            return n*factorial(n-1);
        }
    }

    /** 
    * Returns a term of from the infinite series in the Chudnovsky algorithm.
    * @param n represents the term (nth term)
    * @return  a double representing the nth term, approximately equal to 1/Pi
    */
    double chudnovsky(int n)
    {
        // From the numerator 
        double numerator = pow(-1,n)*factorial(6*n) * (545140134*n + 13591409);
        // From the denominator
        double denominator = factorial(3*n) * pow(factorial(n), 3) * pow(640320,3.0*n+3.0/2.0);
        
        if (n==0)
        {
            return 12.0*numerator/denominator;
        }
        
        return 12.0*numerator/denominator + chudnovsky(n-1);
    }
    int main()
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of digits you want to see from PI.\nUp to 14 digits");
        
        int n = 0;
        while(sc.hasNext())
        {
            // If invalid input, exit the loop/program
            try
            {
                n = sc.nextInt();
            }
            catch(InputMismatchException e)
            {
                System.out.println("Invalid value (letters, float, etc). EXITING");
                break;
            }
            finally{
                if(n>14)
                {
                    n=14;
                }
                else if(n<0)
                {
                    printf("Invalid value (negative value)");
                    n = scanf("%d");
                }    

                // Formatting the output to have specified digits
                NumberFormat fmt = NumberFormat.getInstance(Locale.US);
                
                fmt.setMaximumFractionDigits(n);
                fmt.setRoundingMode(RoundingMode.FLOOR);

                System.out.println(fmt.format(1.0/chudnovsky(2)));
            }
        }
        sc.close();
    }
    
}}

Any help will be appreciate thanks.


r/C_Homework • • Aug 01 '22

Need final project ideas to program in C

Thumbnail self.c_programming
1 Upvotes

r/C_Homework • • Dec 14 '21

Convert java to C ( chudnovsky algorithm )

1 Upvotes

Hi i need to convert my java code to C but its been really difficult.

This is my code that i need to convert:

import java.lang.Math.sqrt;
import java.math.RoundingMode;
import java.lang.Math;
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;

// Calculating the digits of PI using the Chudnovsky algorithm
public class PIDigits {
    // Utility function to calculate factorials
    public static double factorial(int n)
    {
        if(n==0)
        {
            return 1;
        }
        else
        {
            return n*factorial(n-1);
        }
    }

    /** 
    * Returns a term of from the infinite series in the Chudnovsky algorithm.
    * @param n represents the term (nth term)
    * @return  a double representing the nth term, approximately equal to 1/Pi
    */
    public static double chudnovsky(int n)
    {
        // From the numerator 
        double numerator = Math.pow(-1,n)*factorial(6*n) * (545140134*n + 13591409);
        // From the denominator
        double denominator = factorial(3*n) * Math.pow(factorial(n), 3) * Math.pow(640320,3.0*n+3.0/2.0);
        
        if (n==0)
        {
            return 12.0*numerator/denominator;
        }
        
        return 12.0*numerator/denominator + chudnovsky(n-1);
    }
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of digits you want to see from PI.\nUp to 14 digits");
        
        int n = 0;
        while(sc.hasNext())
        {
            // If invalid input, exit the loop/program
            try
            {
                n = sc.nextInt();
            }
            catch(InputMismatchException e)
            {
                System.out.println("Invalid value (letters, float, etc). EXITING");
                break;
            }
            finally{
                if(n>14)
                {
                    n=14;
                }
                else if(n<0)
                {
                    System.out.println("Invalid value (negative value)");
                    n = sc.nextInt();
                }    

                // Formatting the output to have specified digits
                NumberFormat fmt = NumberFormat.getInstance(Locale.US);
                
                fmt.setMaximumFractionDigits(n);
                fmt.setRoundingMode(RoundingMode.FLOOR);

                System.out.println(fmt.format(1.0/chudnovsky(2)));
            }
        }
        sc.close();
    }
    
}}

This is what ive done:

#include<math.h>
#include<stdio.h>

   double factorial(int n)
    {
        if(n==0)
        {
            return 1;
        }
        else
        {
            return n*factorial(n-1);
        }
    }

    /** 
    * Returns a term of from the infinite series in the Chudnovsky algorithm.
    * @param n represents the term (nth term)
    * @return  a double representing the nth term, approximately equal to 1/Pi
    */
    double chudnovsky(int n)
    {
        // From the numerator 
        double numerator = pow(-1,n)*factorial(6*n) * (545140134*n + 13591409);
        // From the denominator
        double denominator = factorial(3*n) * pow(factorial(n), 3) * pow(640320,3.0*n+3.0/2.0);
        
        if (n==0)
        {
            return 12.0*numerator/denominator;
        }
        
        return 12.0*numerator/denominator + chudnovsky(n-1);
    }
    int main()
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of digits you want to see from PI.\nUp to 14 digits");
        
        int n = 0;
        while(sc.hasNext())
        {
            // If invalid input, exit the loop/program
            try
            {
                n = sc.nextInt();
            }
            catch(InputMismatchException e)
            {
                System.out.println("Invalid value (letters, float, etc). EXITING");
                break;
            }
            finally{
                if(n>14)
                {
                    n=14;
                }
                else if(n<0)
                {
                    printf("Invalid value (negative value)");
                    n = scanf("%d");
                }    

                // Formatting the output to have specified digits
                NumberFormat fmt = NumberFormat.getInstance(Locale.US);
                
                fmt.setMaximumFractionDigits(n);
                fmt.setRoundingMode(RoundingMode.FLOOR);

                System.out.println(fmt.format(1.0/chudnovsky(2)));
            }
        }
        sc.close();
    }
    
}}

Any help will be appreciate thanks.


r/C_Homework • • Apr 28 '21

need help understanding something in my homework

0 Upvotes

hi guys,

i'm kinda new to the c

i have this homework where one of the tasks is like this :

i have a maximum of 20 steps :

the guys have to start from n[0] to n[19]

how it works fisrt step he should move 2 steps forward and then one backward

then 3 steps forward and one backward ( and everytime add one step to the forward steps and keeps the backward steps 1)

and then it should sum the backward steps including step n[0];

and if there was a steps left to do and it can't continue because the max is 20 it shouldn't add it to the sum.

well here is my code:

please help me understand what i explained to what i have to do in my code to make it work :

it only sums the odd arrays here in my code

#define T 20
int steps(int a[])
 {
 	int i,j=1,sum=0;
    for(i=0; i<T;i++)
    {
i++;
           sum+=a[i];
// what I'm trying to do here is make the program start by two steps forward then
 backwards and then save the array that it have stopped on, after that it 
countinues from where it stopped and then moving 3 steps forward and then 1 
backward and (save the array that it stopped at) and continuing like this until
 it reaches the T Then sums all the arrays that it has stopped on
 
        }
     	return sum;
 }
int main ()
{
int,i,n[T],sum=0;  
    {
        scanf("%d",&n[i]);
    }
    sum=steps(n);
    printf("sum of array is :%d",sum);
    return 0;
}

r/C_Homework • • Sep 17 '16

Strings and Linked Lists

1 Upvotes

Hey everyone, new to this sub and I'm not sure about formatting so forgive me if I do something wrong.

I'm trying to write a program that reads a series of 6 strings into a linked list, and then prints the whole list off in the order I've provided the strings. My problem is that my program instead seems to overwrite every bit of data in the list with the final input, and then just prints that 6 times. If anyone could tell me where I'm going wrong and/or fix my code up that would be really helpful :) Below I've provided screenshots of my code and a couple examples of the inputs and then output. Thanks in advanced everyone!

https://gyazo.com/c8830b6074cbb498d89fddc92cf91260

https://gyazo.com/16f6e1898d97ecdc95199d154a457a41

https://gyazo.com/e58200448ead0c2972690de691bc6717


r/C_Homework • • Mar 10 '18

Compute a special quantity

0 Upvotes

The rightmost digit d1 in the 10-digit code d10d9d8 ... d1 is uniquely determined from the other 9 digits such that d1+ 2d2 + 3d3 + ... + 10d10 is a multiple of 11. d1 can be any value from 0 to 10. Example: d1 corresponding to 020131452 is 5 since 5 is the only value of d1 between 0 and 10 for which d1 + 22 + 35 + 44 + 51 + 63 + 71 + 80 + 92 + 10*0 is a multiple of 11. Write a program that takes a 9-digit integer as a command-line argument, computes d1, and prints the resulting 10-digit number. It's ok if you don't print any leading 0s.

Requirements

  1. 9-digit integer should be taken from the user as a command-line argument. 2) The aforementioned task should be implemented as a collection of at least two functions different from main(), 3) A function, which will take the 9-digit code as the parameter, and will compute and return d1, should be provided, 4) Another function, which will take d10d9d8 ... d2 and d1 as two different parameters, and will return the resulting 10-digit code, should be provided

How do you code this program in c language?