SEARCH YOUR SOLUTION HERE  

converting some simple pseudocode to c++

all,

I;m a beginner C++ and I;m trying to convert some pseudocode into C++. Its
pseudo code of the peterson algorithm for N-processes.

I almost converted the whole code. But the last lines are very hard.

This is the pseudo code:

for [ k=1 to n except k==i ]

This is pretty simple code although I don;t know how to convert in into c++
because of the except in the pseudocode. for [k=1 to n] to c++ is for
(k=1;k

Posted On: Sunday 4th of November 2012 06:40:02 AM Total Views:  326
View Complete with Replies




Related Messages:

Problem in converting.   (206 Views)
Hi . I'm a new member in this forum and I have basic in C, I think. I have a bit problem, to convert from decimal to binary. I only have a bit of idea how it going to work. I know, user will input a number, for example 255 .the operation will use % until the final answer is 0, and all the remainder, either 1 or 0 will be the form of the decimal number in binary. and to collect all the remainder in one variable, I will use array. right But I think I misunderstood the concept of array. . Can someone give me a bit hint what is the right thing to do Code: Code: #include int main() { int userinput; int binary ; int answer[8]; printf("Please input Base 10 Number : "); scanf("%d",&userinput); printf("Base 10 number is : %d \n", userinput); //Calculation for (binary = 0; binary < 8; binary++) { answer[8]= userinput % 2; } printf("%d is in binary form \n",answer); system("pause"); return 0; }
Help converting a java program to C   (164 Views)
I am trying to convert the following program to C and actually understand it. This is an introductory type program for the beginner that is me. In my intro to C class we have just barely got to if statements and it would be fantastic if I could get this program working in time for a little fantasy football. If someone could take the time and help me through this and give me guidance from square one (especially with inputting external files into my program) I would be forever in their debt (ok not forever but it would be greatly appreciated). Anyways, here is the code in java: Code: import java.io.*; import java.util.*; public class FootballPlayer implements Comparable { // Components of a football player. private String name; private String position; private int powerRanking; // Creates a Football player object with all the necessary statistics. public FootballPlayer(String n, String p, int pass, int rush, int rec, int TD) { name = n; position = p; powerRanking = pass/30 + (rush+rec)/10 + 6*TD; } // Here is how we want a player to print out. public String toString() { return name + " " + position + " " + powerRanking; } public int compareTo(FootballPlayer other) { // First sort by power ranking. if (this.powerRanking != other.powerRanking) return other.powerRanking - this.powerRanking; // Break ties by name. return this.name.compareTo(other.name); } public static void main(String[] args) throws Exception { // Open file. Scanner stdin = new Scanner(System.in): System.out.println("What is the name of your input file"); String fileName = stdin.next(); Scanner fin = new Scanner(new File(fileName)); ArrayList nfl = new ArrayList(); int numPlayers = fin.nextInt(); // Go through the file. for (int i=0; i
Need help converting letters in a string   (203 Views)
I have to write a program when a user enters 26 letters which is a code that corresponds the normal 26 letter (A-Z) in order and then enter their name which can be any where from 1 to 19 letters. Then I have to convert each letter from their name (which is a string) to the letter corresponding to the code they entered. Example: They enter for their code: ZYXWVUTSRQPONMLKJIHGFEDCBA Then enter their name: JAKE Then the program spits out their encoded name: QZPV I used an array to collect the 26 letters, then a string to collect the name, but how do I change each letter in the string to a new letter based on the array and then reprint it
converting text to a variable   (241 Views)
Hi. I've recently done the following script, which finds the zeros of a given function: Code: #include #include #include /* ,___, Autor: Daniel Jal [O.o] Criado: 08-07-2012 /)__) Ultima reviso: 08-07-2012 -"--"- Departamento de Fsica da Universidade de Aveiro e-mail: djalo@me.com Metodo de bissec o */ float f(float x){ float y; y=pow(x,sin(x+5))-pow(x,2)+7*x-18; //Function which zero I'll find return y; } int main(void){ float x_antes,x_depois,x_meio,erro,epson; int repeat; printf("Metodo de bisseccao para determinacao de zeros\n\n"); do{ repeat=0; printf("Limite inferior= "); scanf("%f",&x_antes); printf("Limite superior= "); scanf("%f",&x_depois); if(f(x_antes)*f(x_depois)>0 || f(x_antes)*f(x_depois)==0){ repeat=1; printf("Valores invalidos. Escolha novos limites!\n\n"); if(x_antes>x_depois){ printf("O limite inferior nao pode ser maior que o limite superior\n\n"); repeat=1; } } } while(repeat==1); printf("Processando...\n"); x_meio=(x_depois+x_antes)/2; erro=pow(10,-5); epson=x_depois-x_antes; do{ if(f(x_antes)*f(x_meio) user chooses it Variable: x -> user chooses it Function is registered and the code runs, finding the zero..
I need help converting a unidimensional vector of characters into a bidimensional one   (302 Views)
Ok, so I was woking on this program in which the user types in a string of N characters and i have to convert it into a bidimensional matrix [N/3][3]. How do i do this I need the program to read line by line, as if it had several sequences of 3 characters each. HELP ME PLEASE!, Originally Posted by laserlight What idea do you have to solve this Have you tried solving this on paper (or in a text editor) for concrete values of N and sample input Code: #include #include #include void main() { char sequence[100], seq[100][4]; int i,j, size,line,column. printf("type in your nucleotide sequence:\n"); gets(sequence); size=strlen(sequence); column=0; line=0; for(i=0;i
A bit of an issue, converting char into int...   (202 Views)
you wonderful people... I was wondering if I could get your help real quick please, and thank you... So I want to write a code for an assignment to validate an ISBN number. So once the user inputs the number, I need to take each digit and multiply it by a predetermined weight, but since I am using a string array for the input, I am having a bit of a problem. The program runs, but gives me the wrong results... Can you please help me to figure out how to convert a char into int. I have used atoi, but that converts the entire input rather than digit by digit.
Trouble with program converting decimal to binary   (237 Views)
Hi ! I've just started programming, and I've been trying to write a program that converts a decimal number input by the user to a binary number.
converting printf to fprintf and fixing code problems   (293 Views)
Heres the code please help Code: #include #include #include #define ALIVE 1#define DEAD 0#define GOL_DIM 10int MArray[GOL_DIM+2][GOL_DIM+2];int PArray[GOL_DIM+2][GOL_DIM+2];int generation = 0;char *commands[] = {"help", "quit", "init", "next", "status", "print", "last",};typedef enum { help, quit, init, next, status, print, last } command_t;intcountMatrix(int currArray[][GOL_DIM+2], int dim){ /* count how many cells on the game board are still alive */...}voidinitMatrix(int currArray[][GOL_DIM+2], int dim){ int i, j; bzero(currArray, sizeof(int) * (GOL_DIM+2) * (GOL_DIM+2)); for(i = 1; i < (dim+1); i++) { for (j = 1; j < (dim+1); j++) { currArray[i][j] = random() % 2; } }}voidprintMatrix(int currArray[][GOL_DIM+2], int dim){ int i, j; printf("Column: "); for(i = 0; i < (dim+2); i++) printf("%2d ",i); printf("\n"); printf(" "); for(i = 0; i < (dim+2); i++) printf("__ "); printf("\n"); for(i = 0; i < (dim+2); i++) { printf("row = %2d > ", i); for (j = 0; j < (dim+2); j++) { printf(" %c ", (currArray[i][j] == 1) 'X' : ' '); } printf("
String manipulation and converting to a number   (244 Views)
Been struggling with the below and dont seem to be getting anywhere. I've got a string that contains: 1.3kwh : count:36 I want to pull out the values from the string and put them into 2 different variables. (the first one into the variable power, and the second value into the variable count) I've tried fiddling around with sscanf and atof but dont seem to be getting anywhere in c. Its probably fairly simple but I don't know enough to get it working. I've tried: Code: sscanf(reading,"%fkwh",&power); to get the first reading into the variable power (float) but it doesnt work. Also tried: Code: power = atof(reading); But I dont think I"m doing it right - there's probably a simple one liner which will do it. Help!
converting from windows wchar_t to linux wchar_t   (251 Views)
experts, I am dealing now in porting our server from windows to linux. our client is running only on windows machine. to avoid the wchar_t size problem ( in windows its 2 bytes and linux is 4 bytes ) we defined #ifdef WIN32 #define t_wchar_t wchar_t #else // LINUX #define t_wchar_t short #endif on the server I get a buffer that contains windows t_wchar_t string. something like struct user_data { t_wchar_t name[32]; ..... ..... }; all the data transfer is working great as long as the server don't care what's in the string my problem start when I want to print out some logs on the server using the content of the buffer. my Q is : is there a simple way to convert a 2 bytes wchar_t (windows version ) to 4 bytes wchar_t ( linux version ).
Question on converting unsigned long to std::string   (276 Views)
I need to convert unsigned long data to a std::string, I googled a bit to see if the string class supports any methods to achieve this - but didnt find any, I think of using sprintf and converting to a char buf and then putting it back in std::string - is anyone aware of any other way
Re: compiler converting char* to char*&   (335 Views)
> Content-Type: text/plain; charset=ISO-8859-1 X-Original-Date: Wed, 10 Sep 2008 09:33:15 -0700 (PDT) X-Submission-Address: c++-submit@netlab.cs.rpi.edu On Sep 9, 6:00 pm, mojumbo wrote: > I am using gcc 3.2.2. > I have declared 'const char* bob = "Some String"; ' in a .h file > (Inherited code). > When I try to pass bob into a method requiring std::string, the > compilation pops because the compiler has made bob a 'const char*&' - > which std::string has no c-tor for. > > Any ideas There's nothing wrong with passing a reference to T to a function expecting a T. Your code "should" compile, and while I don't have gcc 3.2.x available, I have 3.3 and it compiles for me. Perhaps you could show a minimal code snippit that reproduces the problem. I'm suspecting either your code is not quite what you described, or you're (possibly) running into a compiler/library bug. You do have a fairly old compiler---have you tried with a newer one -- Chris -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
converting an ostream's output to a pure char*   (317 Views)
Folks, I have a heterogenous env. where I developed some C++ code. This code has the '
Problem converting application from VS2003 to VS2005   (422 Views)
Hi! I recently converted an application from VS2003 to VS2005. The application consists of a main 'unmanaged C++ executable' which calls a managed C++ .dll. The .dll basically launches a separate form. The application use to work fine in VS2003. Now that I have converted to VS2005 the main executable is working but an exception gets thrown when it trys to call the .dll (basically the new separate form never launches). The .dll was compiled with (/clrldSyntax). This is the exception that gets thrown: File: dbgheap.c Line: 1414 Expression: _CrtIsValidHeapPointer(pUserData) I click on Retry and it triggers a breakpoint at if ( (oldsize = _msize_crt(*pbegin))
converting floating point types round off error ....   (423 Views)
Consider the equation (flight dynamics stuff): Yaw (Degrees) = Azimuth Angle(Radians) * 180 (Degrees) / 3.1415926535897932384626433832795 (Radians) There's a valid reason to use single precision floating point types. The number of decimal digits guaranteed to be correct on my implementation is 6. (i.e numeric_limits < float >::digits10 = 6 ) If I'm reading the IEEE standard, I'd could paraphrase the issue surrounding conversion to a string and back _without_ loss of precision as follows: If a float is correct to a decimal string with a least 6 significant decimal digits, and then converted back to a float, then the final number must match the original. IOW: given float a = 1. F ; float aa = 0. ; std::stringstream s ; s. precision ( 6 ) ; s aa; assert ( a != aa ) ; No sweat I have to serialize the Yaw answer above. The question: Is it safe to state that my PI representation is useless beyond six significant digits I'd like for the C++ source to reflect my Matlab models but I'm starting to get concerned here with the conversion aspect. Is there a good source out there that will show me how far out I could represent a value ( say PI ) for both single and double precision before truncation/round off loss kicks in ( I tend to struggle with numeric_limits at times + coupled with all the idiosyncrasies of machines and floating point types ) , On 2008-10-05 05:45:56 -0400, Paavo Helde said: > > Moreover, floating-point numbers are by nature inexact, No, floating-point numbers are exact. The problem is that they don't represent real numbers, and if you assume that they do, you don't get the results you expect. > so there seems to > be not much point for requiring the *exact* equality after serialization > and deserialization. It's not simple, but it can be done. -- Pete Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The Standard C++ Library Extensions: a Tutorial and Reference (www.petebecker.com/tr1book)
type wildcards (or something similar) for function parameters   (336 Views)
is there any way to define a function where one or more parameters might be of any type, since they aren't used in the function In particular, I'd need an operator val 'a f = fn : int -> 'a -> int (here the type of the second argument, y, is not specialized and is represented by the type variable 'a). Is this possible to achieve in C++
Rounding error when converting from double to int   (330 Views)
Steve McConnel, in his book "Code Complete", suggests converting money amounts from double to integer in order to avoid rounding errors during calculations. So we made a money class where the money amount is stored as an integer instead of a double. The cents are stored in the 10's and 1's position of the integer. For example: $1.23 is stored as the integer 123. The cents portion is 23, and the rest is the dollar portion. However we are having trouble initializing this integer amount when the original double amount contains fractions of a cent (due to some interest calculations). We want to round any fractional cents up to the nearest cent. We use a rounding scheme where values greater than or equal to 5 are rounded up. Below is our initialization function. Note that we use the type __int64 so we can hold larger numbers but the same problems happen with type int also. myCurrencyx100 is of the type __int64. The code multiplies the double by 100 first, then it rounds to the nearest 1, then it converts to int. So if value = 9.495 we want myCurrencyx100 to be initialized to 950. But the code sets it to 949. void GCSMoney::init( const double& value ) { if( value < 0 ) myCurrencyx100 = static_cast(100.0 * value - 0.5); else myCurrencyx100 = static_cast(100.0 * value + 0.5); } I experimented with the order of the calculations. I changed it to round to the nearest hundredth (cent), then multiply by 100, then convert to int. This will correctly set myCurrencyx100 to 950 when the double value is 9.495. But when I tried a double value of 1.115, it rounded it to 1.11 when it should have rounded it to 1.12. However the first init method worked for 1.115. void GCSMoney::init( const double& value ) { if( value < 0 ) myCurrencyx100 = static_cast(100.0 * (value - 0.005)); else myCurrencyx100 = static_cast(100.0 * (value + 0.005)); } So I have two different methods, but neither works with all values. For each of these methods, I noticed if I recoded the steps as individual lines of code, the error happens during the step when converting the double to int. Is there any commonly accepted practice for handling these types of errors
What is assigning object inside the class using scope some varoutside the class is illegal?   (179 Views)
Say we have the following class (adapted from the standard): enum {i=1}; class X{ char v[i]; enum{i=2} // why this is illegal int f(){ return sizeof(c); } // and this is legal };
Are (char * const somename) and (const char* somename) the same?   (265 Views)
I'm not too familiar with how C++ handles strings or it's equivalent of strings, which I understand to be a pointer to sort of an array of characters. I've seen examples using: char * const somename and others with const char* somename Is there any difference, or do these have the exact same effect - Dan
can I get some help   (271 Views)
I'n new hear < and I'm really sory about my bad language > I wont some help in making tic tac toe code in c I have a code witch could be usefull >> but I want to make sure that I understand it >> it should use minimax and heurastic algorithm so if some one could help me >> and sea if the coul using heurestic ..................................................................................................... #include #include /* the functions */ void theboard(void); void playgame(int play, char who); int boardfull(void); int win(int who); void computermove(int who); void humanmove(int who); void output(void); int minimax(int who); int bestminimaxmove(int a[9],int who); int board[3][3]; /* Main function */ int main(void) { int play; char c, who; clrscr(); printf("Tic Tac Toe !\n"); do { /* the board */ theboard(); /* to play */ printf("typ 1 to play or 2 to exit game !"); while ((play=getchar()-48)2); if (play==1) { printf("Who goes first (Computer or Human)"); while((who=toupper(getchar()))!='C' && who!='H'); } clrscr(); playgame(play,who); clrscr(); /* final output */ output(); /* Determine who won or if it was a game over and output */ if (win(-1)) { if(who=='C')printf("\nThe Computer won\n"); else if(who=='H')printf("\nPlayer won\n"); } else if (win(1)) { if(who=='C')printf("\nPlayer won\n"); else if(who=='H')printf("\nThe Computer won\n"); } else printf("\nIt game over.\n"); /* asking for another game */ printf("\nWould you like to play again\n"); while ((c=toupper(getchar()))!='N' && c!='Y'); } while(toupper(c)=='Y'); } /* theboard sets all of the values in the board to 0 */ void theboard() { int i,j; for(i=0;i