jephthah 1,888 Posting Maven

what is this mickey mouse bullshit, walt?

you go and pull my posts out of the middle of another thread, and use them to create a new thread in my name.... and then Double Post it, too?

you have too much time on your hands to be getting worked up into a state of such pettiness.

jephthah 1,888 Posting Maven

ato?() which is crap.

well, i'm not saying it's crap, per se, it is good for a quick prototyping that doesnt require validation.

but atol/atoi is terribly weak and unable to distinguish between non-numerics and a legitimate zero value.

now if you need to preface your calls to ato? with some routine that identifies whether or not it's a number in the first place, you've kind of defeated the purpose of having an ascii/string-to-numeric converter, yes?

You have brown eyes, don't you? ... get off your high horse and ... Become a real programmer

really? is this where we're headed?

.

jephthah 1,888 Posting Maven

nearly bulletproof

"nearly" is the key word. Murphy's Law always prevails.

but thanks for pointing this out. I realized that it would allow non-numerics after a valid number, but at some point i just got tired of "bulletproofing"

The rest is left as an exercise for the reader.

:P

jephthah 1,888 Posting Maven

i like how some people seem to assume that they can somehow guarantee the format and content of strings being input by an end user or some other uncontrolled process.

the fact is, nobody ever knows for certain what will wind up being passed in as a string argument. data can be corrupted even if everything else is "guaranteed"

that's why you need to use strtol() to convert numbers, rather than the non-error-checking atol/atoi

and strtok() is powerful enough to be able to handle multiple types of token delimeters. so, when combined with even a modest amount of error checking, strtok and strtol can make a nearly bulletproof string-to-numeric converter.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define MAX_DATESTR_LEN                16
#define DATESTR_DIVIDER_CHARACTERS     "/\\-_.,"  // allowable delimiters for month date year

int convertDateStringToVals (char*, const char*, int*, int*, int*);
int getUserInput(char*, int);

int main(void)
{
   char  dateStr[MAX_DATESTR_LEN];
   int   inputLen = 0,
         month,
         date,
         year,
         isInvalid;

   while (1)
   {
      do {
         printf("\nEnter Date String : ");
         fflush(stdout);
         inputLen = getUserInput(dateStr,MAX_DATESTR_LEN);
         if (inputLen > MAX_DATESTR_LEN)
            printf("string length %d, max length is %d, try again.\n\n",inputLen, MAX_DATESTR_LEN);
      }
      while (inputLen > MAX_DATESTR_LEN);

      if (inputLen == 0)
         break;

      isInvalid = convertDateStringToVals(dateStr, DATESTR_DIVIDER_CHARACTERS, &month, &date, &year);
      printf("   month : %02d\n   date  : %02d\n   year  : %d\n", month, date, year);

      if (isInvalid)
         printf("WARNING:  one or more fields are invalid.\n");
   }

   printf("exiting.\n");
   return 0;
}


//*****************************************************************************************//
// convertDateStringToVals()
//
// (c) 2010 by Jephthah and distributed for general use under the WTFPL licence
//
// purpose: …
jephthah 1,888 Posting Maven

i don't recommend atoi() or atol(). this does not handle invalid strings (non-integer strings) very well at all. for instance, if you try

value = atoi("CowAndChicken");

the result will be zero (value = 0)

and if you try

value = atoi("0");

the result will also be zero (value = 0)

strtol() avoids this confusion by allowing you to tell the difference between an actual zero, and an invalid string. it also will convert number bases other than base 10. look up the strtol() function here: http://www.cplusplus.com/reference/clibrary/cstdlib/strtol/

And I would use both "strtok" to parse the strings between the separator characters (which could be "/" or "-" or ".") in conjunction with "strtol", to properly convert each numeric string.

this is the best method, IMO, because it will allow you to handle conditions where you have extra spaces or invalid characters, or differently formatted month/date numbers.

for instance, consider all the differences between:

"01/01/10"

"1/1/10"

"1/01/2010"

"01 - 01 - 2010"

"1-1-10"

"01.01.2010"

etc.

jephthah 1,888 Posting Maven

Okay, Okay, Okay.

Banfa, you are right. good job on calling me out on being sloppy. i should have followed through. the change is actually easy: all i needed to do was change 3 lines in the ConvertDateStringToVals from

if (ptr == mmStr)

to

if (ptr == mmStr || ptr != &mmStr[strlen(mmStr)])

here is the NOW BULLETPROOF(*) version that i should have posted in the first place

(* Nearly)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define MAX_DATESTR_LEN                16
#define DATESTR_DIVIDER_CHARACTERS     "/\\-_.,"  // allowable delimiters for month date year

int convertDateStringToVals (char*, const char*, int*, int*, int*);
int getUserInput(char*, int);

int main(void)
{
   char  dateStr[MAX_DATESTR_LEN];
   int   inputLen = 0,
         month,
         date,
         year,
         isInvalid;

   while (1)
   {
      do {
         printf("\nEnter Date String : ");
         fflush(stdout);
         inputLen = getUserInput(dateStr,MAX_DATESTR_LEN);
         if (inputLen > MAX_DATESTR_LEN)
            printf("string length %d, max length is %d, try again.\n\n",inputLen, MAX_DATESTR_LEN);
      }
      while (inputLen > MAX_DATESTR_LEN);

      if (inputLen == 0)
         break;

      isInvalid = convertDateStringToVals(dateStr, DATESTR_DIVIDER_CHARACTERS, &month, &date, &year);
      printf("   month : %02d\n   date  : %02d\n   year  : %d\n", month, date, year);

      if (isInvalid)
         printf("WARNING:  one or more fields are invalid.\n");
   }

   printf("exiting.\n");
   return 0;
}


//*****************************************************************************************//
// convertDateStringToVals()
//
// (c) 2010 by Jephthah and distributed for general use under the WTFPL licence
//
// purpose: converts each field of the datestring (month, day, year) into integer values.
//          fields may be separated by one or more possible token separator characters
//          invalid non-numeric fields will be converted to -1, and return an error flag
// …
jephthah 1,888 Posting Maven

ato?() which is crap.

well, i'm not saying it's crap, per se, it is good for a quick prototyping that doesnt require validation.

but atol/atoi is terribly weak and unable to distinguish between non-numerics and a legitimate zero value.

now if you need to preface your calls to ato? with some routine that identifies whether or not it's a number in the first place, you've kind of defeated the purpose of having an ascii/string-to-numeric converter, yes?

You have brown eyes, don't you? ... get off your high horse and ... Become a real programmer

really? is this where we're headed?

.

jephthah 1,888 Posting Maven

nearly bulletproof

"nearly" is the key word. Murphy's Law always prevails.

but thanks for pointing this out. I realized that it would allow non-numerics after a valid number, but at some point i just got tired of "bulletproofing"

The rest is left as an exercise for the reader.

:P

jephthah 1,888 Posting Maven

i dont normally work in the console/terminal window in my day job. so, i keep rewriting this every time i respond to someone needing help related to getting user input. im putting it here partly so i dont have to keep rewriting it.

this function will get a string input safely from the user and flush any extra characters if they enter too many.

if you (the programmer) need to get an integer or double floating point value from your program's user, then just follow up this code with a call to the strtol() or strtod() function from the standard C library, <stdlib.c>

this function forces the user who inputs the string to stay within boundaries, but just as importantly, it does not tempt the programmer (you) to use dangerous functions that could overflow buffers or get input "trapped", or to use undefined functions to try and flush the input buffer, etc.

And if your user does not input the correctly formatted value(s) that your program is looking for, strtol, strtod, etc. will point that out and allow you to handled invalid input gracefully.

Aia commented: I commend you for posting +8
jephthah 1,888 Posting Maven

i don't recommend atoi() or atol(). this does not handle invalid strings (non-integer strings) very well at all. for instance, if you try

value = atoi("CowAndChicken");

the result will be zero (value = 0)

and if you try

value = atoi("0");

the result will also be zero (value = 0)

strtol() avoids this confusion by allowing you to tell the difference between an actual zero, and an invalid string. it also will convert number bases other than base 10. look up the strtol() function here: http://www.cplusplus.com/reference/clibrary/cstdlib/strtol/

And I would use both "strtok" to parse the strings between the separator characters (which could be "/" or "-" or ".") in conjunction with "strtol", to properly convert each numeric string.

this is the best method, IMO, because it will allow you to handle conditions where you have extra spaces or invalid characters, or differently formatted month/date numbers.

for instance, consider all the differences between:

"01/01/10"

"1/1/10"

"1/01/2010"

"01 - 01 - 2010"

"1-1-10"

"01.01.2010"

etc.

jephthah 1,888 Posting Maven

are you sure you really need to use POSIX threads on Windows? The Windows API has plenty of support for multithreading
http://msdn.microsoft.com/en-us/library/ms684841%28VS.85%29.aspx

but if you really do need to use the Win32 port of pthreads, you can get it from here:
http://sourceware.org/pthreads-win32/

and a good tutorial here:
https://computing.llnl.gov/tutorials/pthreads/#PthreadsAPI

EDIT: hmm, the sourceware.org site seems to be down at the moment. try again later.

.

jephthah 1,888 Posting Maven

^ you mean you're a junior, as in a third-year undergraduate?


.

jephthah 1,888 Posting Maven

@jephthah, thanks alot :)
but there is no such thing in my lesson how to give multiple values for IF

well, you were certainly trying to do so! but you were doing it wrong. IF takes one conditional statement. the statement may have one or more values. you need to be able to deal with ANDs and ORs in your conditional statement, as you can see by your need to find the condition when 'a' equals either 0 or 1. to try and do this with only one value at a time, would be ridiculous

@WaltP , Our teacher teaching us from the basic and they told us to use such functions, i don't know any other function to use then these void main(void) and clrscr () & getch () , can you tell me which functions should i use istead of the functions above ?

i wasn't going to bother correcting this, since you've got more fundamental problems... but since Walt brought it up:

(1) always use int main (void) ... you will need to add a return 0; at the end of your main block. "void main" is wrong. it's undefined and can cause all sorts of problems in larger projects. any instructor that tells his student to do so, is immediately suspect of incompetence.

(2) you should never use "clrscr()". it's entirely unnecessary and obnoxious.

(3) use getchar() instead of getch().

(4) stop using the conio.h library altogether. use stdio.h and stdlib.h …

jephthah 1,888 Posting Maven

thank you so much.
but I haven't learned about fgets or many of those other code you used, so I can't use it...
what exactly did you do to fix the problem?

well... i fixed it by completely rewriting it and using strtok to separate the string into tokens based on the semicolon delimiter. but no, i guess it doesnt help you much if i do your homework for you using functions you haven't even learned, yet.

the problem with your code is this: the SkipOverRestOfComand *assumes* that a semicolon has not yet been found. this assumption breaks down if SkipBlank actually finds an out-of-place semicolon and passes control to SkipOverRestOfCommand -- because SkipOverRestOfCommand is only looking for a '\n' or a ';' -- which will continue to drop all characters (ie, the next command) until it finally finds a semicolon or newline. And therefore that entire next command is ignored.

so in the case where you find an out-of-place semicolon (or a non-alpha character), you need to run "SkipBlanks" again, before you move onto SKipOverRestOfCommand.

you can accomplish this very easily with two lines of code. at the end of your "else" statement, add a line to recall SkipBlanks function, followed by a "continue" statement that works with your "while" loop. if you don't yet know about "continue" , you need to learn it, because it's flow control that's a fundamental part of conditional statements like "while", "do/while", and "for"


.

jephthah 1,888 Posting Maven

sure enough, i can't give into the urge:

#include <stdio.h>
#include <string.h>

#define MAX_COMMAND_LEN		32


int main(void)
{
	char input[MAX_COMMAND_LEN+2], *iptr;
	size_t len;
		
	do {
		printf("input commands (max %d chars) : ", MAX_COMMAND_LEN);
		fflush(stdout);
	
		fgets(input,MAX_COMMAND_LEN+2,stdin);   // +2 allows /newline and NULL
		len = strlen(input);
		if (input[len-1] == '\n')				// get rid of /newline
			input[len-1] = '\0';
		len = strlen(input);
	} 
	while (len < 1 || len > MAX_COMMAND_LEN);   // force user input to MAX_COMMAND_LEN

	iptr = strtok(input,";");					// parse tokens
	while (iptr != NULL)
	{
		
		while(*iptr<0x41 || *iptr>0x5E && *iptr<0x61 || *iptr>0x7E)	// skip leading non-alpha
			iptr++;
		
		printf("command : %c\n",*iptr);
		iptr = strtok(NULL,";");
	}
	
	return 0;
	
}
jephthah 1,888 Posting Maven

the reason is because your different functions individually parse each character without regard to what the other is doing. Specifically, your "SkipOverRestOfCommand" function disposes of the ';' character without properly accounting for it to the "SkipBlanks" function.

in the even someone enters a ';' before any commands, your "SkipBlanks" function finds the ';', sees that it is not a space character, and returns.

then you go into "SkipOverRestOfCommand" function, and the semicolon found in the last function is not accounted for, but instead you just blaze on through and look at the next character. this next character is either a blank or a command, but this function is only looking for a '\n' or a ';', and therefore the entire next command is ignored.

try entering "a;b;c", then enter ";b;c" and you'll see what i mean.

i would never have written a string parser this way, so it's difficult for me to "fix" it without giving into the urge to significantly rewrite it.

.

jephthah 1,888 Posting Maven

you're trying to use a 20-year-old compiler on a modern OS. that's the problem.

Turbo C sucks enough already, but is known to be especially more problematic when installed on Windows Vista.

there are some workarounds but I'm not going to advocate them. The real solution starts when you uninstall Turbo C and throw all your copies away.

Aia commented: I like the real solution +8
tux4life commented: Excellent. +8
jephthah 1,888 Posting Maven

okay, i feel bad now. despite being dependent on legacy libraries, this is some nice looking code ... and the particular problem is an interesting one. i guess that's why i was disappointed i couldn't compile it.

But I also see now that the OP is an experienced programmer who used Borland back when it was top of the line in the 80s and early 90's. .

it's just a shame that today Borland focuses more on cornering the burgeoning Second World market than updating their compilers to the 21st Century.

perhaps in the future banders7 will just check that his code is compilable on MSVC or gcc or MinGW compilers as well as Borland.

jephthah 1,888 Posting Maven

why would you ever do something that depends on Borland C++? that's got to be one of the worst compilers out there.

please consider using MSVC, GCC or MinGW compilers. there are plenty of free development environments with full featured editors and debuggers that use modern libraries instead of the obscure non-standard ones peculiar to Borland and Turbo C.

jephthah 1,888 Posting Maven

what i'm getting at, is the OP presented his "code snippet" as such:

I made this really strange and not working code just to count the total number of letters in a string(user inputs then stops with enter), as well as divide each individual character(a, b, c etc) by the total number and show that as well. The reasoning seems right but can someone give me an idea where i'm writing the wrong code? this is my first code in c.

of course he "made this really strange and not working code" as his "first code in c"

complete with all the comments.

so, like, we should all totally get together and solve this really strange problem for him :icon_rolleyes:

.

WaltP commented: C'mon, it's obviously not a code snippet and hasn't been since someone corrected his misteak. After first mention is should not be harped upon. Mistake... -2
jephthah 1,888 Posting Maven

i was being facetious. the comments are ridiculous, considering this is something that was originally presented as his own "Code Snippet"

by the way, i prefer "The Procrastinators Ten Commandments"

Procrastinators Ten Commandments

1.

:P

jephthah 1,888 Posting Maven

line 7 is the problem.

a=0 is an assignment. a==0 is a conditional statement. you need to understand the difference. also, you can't test multiple conditions by throwing a comma between values. you need to fully express each condition, separated by an AND (&&) or an OR (||) as the logic you're trying to acheive requires.

so, what you are trying to say in line 7 should be if (a == 0 || a == 1) this is fundamental stuff. you need to review your early lessons on IF statements, conditional and assignment operators.

jephthah 1,888 Posting Maven

non-standard libraries. fatal compile errors. Failure.

||=== mci, Debug ===|
C:\sandbox\mci\mci_main.c||In function `main':|
C:\sandbox\mci\mci_main.c|16|error: `MAXDIR' undeclared (first use in this function)|
C:\sandbox\mci\mci_main.c|16|error: (Each undeclared identifier is reported only once|
C:\sandbox\mci\mci_main.c|16|error: for each function it appears in.)|
C:\sandbox\mci\mci_main.c|28|error: `MAXEXT' undeclared (first use in this function)|
C:\sandbox\mci\mci_main.c|28|error: `MAXFILE' undeclared (first use in this function)|
C:\sandbox\mci\mci_main.c|32|error: storage size of 'file' isn't known|
C:\sandbox\mci\mci_main.c|34|error: `FA_NORMAL' undeclared (first use in this function)|
C:\sandbox\mci\mci_main.c|59|warning: implicit declaration of function `fnsplit'|
C:\sandbox\mci\mci_main.c|65|warning: implicit declaration of function `findfirst'|
C:\sandbox\mci\mci_main.c|65|warning: implicit declaration of function `findnext'|
C:\sandbox\mci\mci_main.c|87|warning: implicit declaration of function `clrscr'|
C:\sandbox\mci\mci_main.c|158|warning: implicit declaration of function `wherey'|
C:\sandbox\mci\mci_main.c|159|warning: implicit declaration of function `wherex'|
C:\sandbox\mci\mci_main.c|171|warning: implicit declaration of function `gotoxy'|
C:\sandbox\mci\mci_main.c|172|warning: implicit declaration of function `clreol'|
C:\sandbox\mci\mci_main.c|211|warning: suggest parentheses around assignment used as truth value|
C:\sandbox\mci\mci_main.c|15|warning: unused variable `j'|
C:\sandbox\mci\mci_main.c|16|warning: unused variable `filename'|
C:\sandbox\mci\mci_main.c|18|warning: unused variable `dsz'|
C:\sandbox\mci\mci_main.c|28|warning: unused variable `ext'|
C:\sandbox\mci\mci_main.c|28|warning: unused variable `fname'|
C:\sandbox\mci\mci_main.c|32|warning: unused variable `file'|
C:\sandbox\mci\mci_main.c|33|warning: unused variable `srch'|
||=== Build finished: 7 errors, 16 warnings ===|
jephthah 1,888 Posting Maven

i did bother to look at the original code. the first thing i noticed was:

/*Header file declarations. You may not include any additional header files*/

/* Global variable Declarations. You may not include any additional global variables */

/* You may not modify the table[] global variable */ 

/* You may not modify the PrintMsg function */

/* You may not modify the calcError function */

I don't know what to do here, because there's not much code left that we're allowed to modify.

jephthah 1,888 Posting Maven

i may be (re)stating the obvious, but just for clarity's sake:

what Banfa meant, i think, is that you will need to take the references to the prototypes out of the C file and leave them only in the header file. in the C file(s), you will have the single line #include "myheaderfile.h" or whatever you call it.

the other programs will link the library when they are built. Depending on how the library is built, those programs' C files that use the library's external functions will probably need to have that #include "myheaderfile.h" line, as well.

and you may already know all this.

.

jephthah 1,888 Posting Maven

this so totally does not belong as a code snippet.

code snippets are supposed to be working code, that solves a particular problem, and that isl also be likely to be useful to at least a few other people in the world, somewhere.

but this ... this is a cry for help.

jephthah 1,888 Posting Maven

this is the reason why globals are generally considered bad programming. unless you have a compelling reason to do so, do not use global variables.

pass your array as a pointer argument into the functions that will be making use of it and/or modifying it.

your problems will disappear.

jephthah 1,888 Posting Maven

yeah, pretty much ... the rest is just details :P

just to be clear, you write the code and the header file, then you compile and build it as a library file, rather than a binary executable. the resulting library file(s) along with the .h file are distributed.

Note for MS Windows .DLLs, you have to specify in the code which functions will be externally visible. And Linux has completely different methods to create and include shared libraries. See the link above.

it's some extra work, but the benefit of doing it this way, rather than just handing them the .C source code, is that libraries can be maintained/revised without affecting the programs that use them (unless the prototypes are changed) also the library build is controlled and can't be modified in a way not intended by the author, other than allowing them to tweak #define values in the header


.

jephthah 1,888 Posting Maven

header files are good programming practice especially for large projects with mulitple files.

but, no, you can't just plop a header file into some other program and have it work without code available. you do need to have the source code -- in one form or another -- included as well as the header.

in many cases, such as standard libraries like <stdio.h>, the source code is part of a library that is included in the build when the header file is included. these libraries are the source code, and are already compiled for your specific operating system, and are typically provided as .lib or .dll files

so for your code to be portable, you would have to distribute the source code, either as the .c source file or in an external library, if you want to allow that functionality to be ported to some other program. merely including the header prototypes will not do it.

but it is good practice to put all the prototypes and defines and global declarations and typedefs and etcetera in their own header files. as your projects get bigger, these header files can and will become fairly substantial, and it becomes necessary to maintain programmer sanity to keep everything organized.

also it's important to not redefine elements, so the header files are framed with their own define to keep them from being called more than once.

/**********************************
*  myproject.h
*
*  contains definitions and prototypes
*  for myproject.c …
jephthah 1,888 Posting Maven

while (number != 0)

allows you to keep entering new numbers until zero is entered at which point the program quits.

the inner loop, "while (number > 1)" counts down the factorial loops, and multiplies each one into the total product, as long as the number is 2 or larger. because to multiply it by 1 doesn't change anything

jephthah 1,888 Posting Maven

you have to specify a length for fgets()

you can test that the last character of the string received by fgets() has a newline, indicating that it is complete. if it doesn't have a newline, that means the input exceeded the length and the remaining characters are still in the input buffer. then you will have to figure out a way to get the rest of the characters and either use them or dispose of them.

you can do something like this

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

#define MAX_STR_LEN 10   // set to whatever size desired

int main(void)
{
    char inputStr[MAX_STR_LEN+1], extraStr[MAX_STR_LEN+1]; // account for NULL
    size_t len, count;

    while(1)
    {
        printf("\ninput up to %d chars: ", MAX_STR_LEN);
        fflush(stdout);   // because a newline was not printed
        fgets(inputStr,MAX_STR_LEN+1,stdin); // account for NULL
        len = strlen(inputStr);
        if (inputStr[len-1] == '\n') // found newline, string fit
        {                   // get rid of newline amd recalc len
            inputStr[len-1] = '\0';
            len = strlen(inputStr);
            printf("\nstring \"%s\" is %d characters\n",inputStr,len);
        }
        else   // string was too long, newline was not discovered in first fgets()
        {      // print the partial string 
            printf("\nstring \"%s\" used maximum %d characters\n",inputStr,len);
            printf("the remainder \"");
            count = len;
            while (len == MAX_STR_LEN)   // then continue to fgets() the remining
            {                            // string from the input buffer
                fgets(extraStr,MAX_STR_LEN+1,stdin);
                len = strlen(extraStr);
                if (extraStr[len-1] == '\n') // once newline is found,
                {                   // get rid of newline amd recalc len
                    extraStr[len-1] = '\0';
                    len = strlen(extraStr);
                }
                printf("%s",extraStr);  // print 'extra' chars 
                count …
jephthah 1,888 Posting Maven

Do you need to learn how to program in C? there are plenty of tutorials. Here's one: Basics of C Programming

Do you want to write better C? there are plenty of guides. Here's one: Six ways to write more comprehensible code


.

jephthah 1,888 Posting Maven

(1) use fopen() to read all items from the file into a structure in memory, then fclose() the file immediately

(2) do whatever manipulations you want on the memory structure.

(3) when the user is ready to commit a change (either singly or in a batch) reopen the file using fopen() to write all items from the data structure back into the file, then fclose().

(4) repeat 2 - 3 as often as desired until exiting the program.


another method you may see or be told, is to open the file for simultaneous read and write access, and perform reads and writes on the fly. this is more complicated, requires the use of other commands like "rewind" and/or "fseek" and opens up many opportunities for you to permanently corrupt your data file. I don't recommend this method at all.

.

jephthah 1,888 Posting Maven

We are forced to use turbo c at college

your college forces you to use a substandard compiler and IDE that is 20 years out-of-date, that uses deprecated and obsolete libraries, when modern industry-standard compilers and development environments are freely available in the form of GCC and MinGW.

think about that.

but i applaud you for trying to move to MSVC. you have the potential to break out of this cycle of despair. keep using MSVC whenever you can. if you dont have the full installation, consider checking out the full development CodeBlocks complete with modern graphics libraries and debugger.

Salem commented: oh yeah! +19
jephthah 1,888 Posting Maven

it's totally due to that terrible hack of a "wait" routine. that's it and that's all.

the while loop is using every single available CPU cycle to approximate a timer. Like AD said, you need to use the library function for sleep(), in order to free up the CPU for other processes.

the other tweaks are good coding practice, but any speed gains won't even be noticeable compared to that behemoth of a cycle-eater you've got in that while() loop.

jephthah 1,888 Posting Maven

conio.h, check. alloc.h, check. goto, che ... wait, what?

GOTO?

is this a joke?

where do you people come from?

jephthah 1,888 Posting Maven

Microsoft's Visual C and GCC are both pretty sweet for doing small assignments and programs. I use them a great deal, as does the rest of the First World, whereas nobody in technically competent companies or institutions here in this 21st century use Turbo C.

seriously throw that archaic Turbo C crap away. let it die like it should have already done back in the early 1990's.

jephthah 1,888 Posting Maven

scanf is often the source of input problems. as you can see, you have the most trivial example and it's already being problematic. since there are better alternatives readily available, you'll do well to learn to stop using it as soon as possible.

i too am partial to fgets(). it's intuitive to use and safe. the sooner you start using it, the sooner you will learn to love it.

word of caution: never, ever, use the similar-looking "gets()" function, however. "gets()" is an idiot test. anyone who ever suggests that you use it is an idiot. this especially includes programming instructors. here is why.

jephthah 1,888 Posting Maven

That's not pseudocode. That's BASIC. :icon_wink:

eh, i thought BASIC was pseudo code :P

WaltP commented: Well, OK then :D +11
jephthah 1,888 Posting Maven

jesus, man, you don't need to post all 156 identical errors. :confused: in fact you really don't need to post any. because the answer is simple:

rule #1 -- you can not take header files from one compiler's library and plop them into another. this will not work.

"graphics.h" (and "conio.h", too) is non-standard Borland/Turbo trash. and as such, Microsoft's Visual C compiler does not, can not, and will not use it. the sooner you cut your losses and forget all this non-standard crap you learn using Turbo C, the better.

however, if you are being forced to use Turbo C and its obsolete, archaic libraries by your incompetent university's administration, then you better get off MSVC now and go back to using your 1980's era toy computer, and spend your time there to figure out what you're doing wrong.

when you're ready to join the 21st century western world, you'll toss all that Turbo C code away.

.

jephthah 1,888 Posting Maven

you probably want to look into sparse matrix compression algorithms

jephthah 1,888 Posting Maven

basically the "inner loop" is variable, and will execute a number of times that varies depending on the value of the outer loops.

outer loop #1
inner loop executes 1 time

outer loop #2
inner loop executes 2 times

outer loop #3
inner loop executes 3 times

etc.

consider also, that your inner loop may "decrement" instead of incrementing. that is, it will be like for (loop = 10; loop >0; loop--) if you want it to loop from 10 to 1.

when you're printing variable-length lines that depend on the inner loop, you will only print a newline character when the inner loop has completed.

i dont know how to explain this any better, without resorting to code. here it is 'explained' in pseudocode

first problem:

for i = 1 to CHARS
{
    for j = 1 to i
    {
        print "$"
    }
    print \newline
}

second problem:

for i = 1 to CHARS 
{
    for j = (CHARS - 1) to (CHARS - i) 
    {
         print char('A' + j)
    }
    print \newline
}

in this second problem, your "inner loop" will need to be decremented.


third problem:

will be left as an exercise for the reader. in other words, fully understand 1 and 2, then work on 3.

.

jephthah 1,888 Posting Maven

glad to help.. sorry i got you diverted on the addition thing.

jephthah 1,888 Posting Maven

i know the range of int, it will not find the factorial of 8 or number above 8 because this would be outside the int range....

the size of "int" is determined by the compiler.

if you are using a relatively modern compiler, as in from the past 15 years or so, the size of "int" should be 32 bits.

this will allow factorials up to !12

and if you use a type "long long", this will be 64 bits, and i believe will allow factorials up to !20

jephthah 1,888 Posting Maven

okay, sorry, you're right i'm not understanding your question. let me try again.

you're trying to calculate a factorial. in this example you're trying to calculate the factorial of "5". the factorial of 5 is

5! = 1 x 2 x 3 x 4 x 5 = 120.

your program performs this by a using a loop, by multiplying each of these numbers and holding the value in the variable "c". in your specific case, your program does it in reverse

5! = 5 x 4 x 3 x 2 x 1 = 120.

but its the same thing. in any event, please forget that i said anything about addition. you should not be using the addition operator "+" or "+=" for anything here.

here is what you have:

a = the number you want to take factorial of
b = a loop counter
c = the total answer, kept as a running value.

c is initialized to 1
c = 1

a is set to 5
a = 5

b is set to value of a, at the beginning of the "for" loop.
b = a

start loop using b, and decrement by 1 as long as b > 0

first loop:
b = 5
c = c * b
c = 1 * 5
c = 5

second loop:
b = 4
c = …

jephthah 1,888 Posting Maven

okay, hang on a sec. lets get the definition of 'factorial' agreed upon.

factorial is a total products, as calculated using recursive multiplication from 1 up to the number that you are getting the factorial of.

factorial of 5, is written as "5!"

and 5! = 1 x 2 x 3 x 4 x 5 = 120.

so you should be multiplying it as originally shown, using the "c *= b" assignment

(there is another operation that does addition, like 1 + 2 + 3 + 4 + 5 = 15, but that's not a factorial, i forget what it is called.)

so the whole point of this program is to be able to vary the number you want to compute the factorial of. in your example 5 is used, but there you should be able to check any number within a reasonable range, such as 6! or 7!, etc....

that's why you use a loop, because the point is not to just hard-code "1x2x3x4x5" ... but to be able to count any number of factorials from 1! through at least 12! depending on how large of an integer you can handle.

jephthah 1,888 Posting Maven

and why we've used c in a program ?? can't we done this without using airthmaetic assignment operator ?

not sure i understand your question. factorial is recursive multiplication, so you have to do some amount of arithmetic, and you have to assign the value to something, right?

if you want to get rid of a variable, you could get rid of "c" i suppose, and keep the total factorial product in "a". you'd save a variable, and maybe a line of code or two, but the end result should be the same.


.

jephthah 1,888 Posting Maven

thanks alot :)
but here b is equal to 5 4 3 2 1 , then why ithis program is multiplying all the values of b ???
i mean why the ouput is 120 since we never said to the program to multiply all the values of loop

i don't know why you're multiplying it. you're the one who wrote the program, right? ;)

change the multiplication operator to an addition operator if you want to recursively add values c += b .

jephthah 1,888 Posting Maven

i've never heard of Relo as an IDE, so I don't know anything about it. If you're using it with the MinGW compiler, I suppose it should be fine.

open up a new project and either write or copy and paste your C code. if it's anything like any other IDE, it should be able to build console applications by default.

i guess i don't understand what your problem is or what your question is asking.

if Relo is still just completely confusing you or causing you other problems, give another IDE a shot. I recommend CodeBlocks ... it's free and open source, widely used, and in my opinion is well designed for beginners and experts alike.

jephthah 1,888 Posting Maven

because your assignment statement c *= b; is a shorthand way of saying c = c * b by setting c=1, this correctly causes the first execution to be read as "c = 1 * b", and uses the value of c recursively each time afterward.

if you don't initialize c=1 at the very beginning, the first execution will be "c = <some_unknown_value> * b"... and you don't want that.

.

Xufyan commented: thankx alot +1