Chief Delphi

Chief Delphi (http://www.chiefdelphi.com/forums/index.php)
-   Programming (http://www.chiefdelphi.com/forums/forumdisplay.php?f=51)
-   -   C Programming Homework Help Needed (http://www.chiefdelphi.com/forums/showthread.php?t=57552)

Pat McCarthy 18-05-2007 23:51

C Programming Homework Help Needed
 
1 Attachment(s)
Hi all,
I'm taking an course, "Structured Programming in C" and am having some issues with my homework for the week.
My assignment is to write a program that calculates various aspects of projectile motion, but I am running into a problem with an output(?) in my program.

When I compile the program I receive no errors or warnings, but when I try to enter values into the first input, it turns the value into '+NAN'. I don't know what '+NAN' is or how to fix it.
I've attached a screen capture of what happens when the program is run and values are entered.

HELP!

Please excuse the messiness of the code, as it is not completed or functional.
Code:

/*
 * Author:        Patrick McCarthy
 * Filename:        P34.c
 * Description:        Homework 2, Chapter 3:4, CS261
 *        This program computes the duration of a projectile's flight
 *        and its height above the ground when it reaches the target.
*/

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

/* Function prototype */
float find_radians(float theta);

/* Function prototype */
float calculate_time(float distance, float velocity, float theta);

/* Function prototype */
float calculate_height(float velocity, float theta, float time);


int main(void)
{
        float degree;
        float theta;
        float distance;
        float velocity;
        float time;
        float height;

        /* Gets the angle of elevation from the user */
        printf("Enter angle (in degrees) of elevation =>");
        scanf("%f",&degree);

printf("%f degrees\n", &degree);

        theta = find_radians(degree);
       
        printf("%f radians\n", &theta);

        /* Gets the distance to the target from the user */
        printf("Enter distance (in feet) to target =>");
        scanf("%f" ,&distance);

        /* Gets the projectile's velocity from the user */
        printf("Enter projectile's velocity (ft/sec) =>");
        scanf("%f", &velocity);

        calculate_time(distance,velocity,theta);

        /* Displays time of projectile flight to user */
        printf("Time of flight is %f seconds.\n", &time);
       
        calculate_height(velocity,theta,time);

        /* Displays height of projectile at impact to user */
        printf("Height of projectile impact is %f feet from the ground.\n", &height);

        return 0;
}


/* Converts degrees to radians */
float find_radians(float degree)
{
        float theta;        /* local variable */
        float Pi = 3.14159;
       
        theta = degree * (180/Pi);

        return (theta);
}


float calculate_time(float distance,float velocity,float theta)
{
        float time;        // local variable
       
        time = distance / ( velocity * cos(theta) );

        return (time);
}


float calculate_height(float velocity, float theta, float time)
{
        float height;                // local variable
        float g = 32.17;        // Declares acceleration due to gravity as -32 ft/s/s

        height = velocity * sin(theta) * time - ( (g * time*time) / 2 );

        return (height);
}

Thanks!

Joel J 19-05-2007 00:05

Re: C Programming Homework Help Needed
 
As one step, you can remove the & sign from your printf statements.

For example,

printf("Time of flight is %f seconds.\n", &time);

becomes:

printf("Time of flight is %f seconds.\n", time);

Flash 19-05-2007 00:32

Re: C Programming Homework Help Needed
 
Joel is correct. Remove the & from your printf functions. The & means "address of". Printf doesn't want the address of the location where the number is kept, printf wants the number itself.

FYI, the & is correct in the scanf function. Scanf requires the address of the variable.

Btw NAN means "Not A Number".

Flash.

EricVanWyk 19-05-2007 01:09

Re: C Programming Homework Help Needed
 
I'm a bit confused as to exactly how this code compiled, and why it isn't happy. I know exactly enough C to confuse myself.

I understand why the code is wrong. I don't fully understand why this is the error that is given.

Since printf takes a variable number of untyped objects, I'll believe that it can't catch the type mismatch of address and float. This must be the case, since it did compile. Since C has no run-time environment to speak of, we must assume that the computer will do exactly what it is told: Take the address and interpret it as a float.

The code then loosely translates to:
Code:

float time;
int * backdoor = &time;
*backdoor = "integer value of the address of the variable time"
print time;

At this point we essentially have "take a random bit string and interpret it as a float". Why is this float NaN? I know that the float space does have NaN gaps, but I thought the space was relatively dense. In otherwords, I thought it was so dense that the probability of this error should be rather small. Does it happen repeatably? Is there something about the addressing space that places variables in the realm of NaN?

I may be reading too far into this, but I'd really appreciate the assistance of someone with a deeper understanding of C.

Thanks
Eric

Bongle 19-05-2007 08:54

Re: C Programming Homework Help Needed
 
I just ran it in Code::Blocks (open-source IDE, it is quite good), and no matter what number I entered, I got 0.0000 degrees, 0.00000 radians.

Check the scanf documentation, there is probably something small you're doing wrong.
Edit: I read the scanf documentation, and there doesn't appear to be anything wrong. Good luck.

Pat McCarthy 19-05-2007 11:30

Re: C Programming Homework Help Needed
 
1 Attachment(s)
Quote:

Originally Posted by Joel J. (Post 627907)
As one step, you can remove the & sign from your printf statements.

For example,

printf("Time of flight is %f seconds.\n", &time);

becomes:

printf("Time of flight is %f seconds.\n", time);

Thanks Joel, that did it.

To answer another question, I'm using the Borland C 5.5 compiler.

Pat McCarthy 09-06-2007 18:22

Re: C Programming Homework Help Needed
 
2 Attachment(s)
Back again...

I'm only concerned with a small portion of my program at the moment.
This part collects an integer value for use to set the color of an object later in the program, then checks to make sure it is within a certain range of numbers. If the number isn't within that set of numbers, it is supposed to ask the user to enter again, then collects a value again.

Currently, whether the value entered is within the parameters that I want, this chunk of program gets stuck in the error checking loop. Oddly, when you enter a two digit integer, it breaks the loop.

Code:

        /* Collects shape selection from user and checks for invalid inputs */
        do
        {
                color_error = 0;
               
                /* Collects desired color from user */
                printf("\nSelect color:\n");
                printf("BLACK (0), BLUE (1), GREEN (2)\n");
                printf("CYAN (3), RED (4), MAGENTA (5)\n=>");
                fflush(stdin);
                scanf("%d", &color);
                printf("Selected color: %d\n", color);
                fflush(stdin);

                /* Valitdate entry */
                switch (color)
                {
                        case '0':
                        case '1':
                        case '2':
                        case '3':
                        case '4':
                        case '5':
                                break;
                               
                        default:
                                color_error = 1;
                                printf("Please select one of the available colors\n");
                                break;
                }
        }
        while(color_error);

I've attached an image of what happens when the code is executed and the entire program's code. It needs to be compiled with a special .lib file that my prof wrote. (something in the forums is keeping me from attaching it)

Mike Bortfeldt 09-06-2007 18:56

Re: C Programming Homework Help Needed
 
Pat,

It looks like you are not being consistant with the data type for "color". You are inputting it as an integer (%d) so I'll assume you've defined it as such, however you are comparing it in the switch statement as a character. The value '0' will be converted to it's ASCII value (48) for the compare. If 'color' is an integer, then I'd try removing the single quotes from around the numbers in the case statements and see if that works.

Mike

Pat McCarthy 09-06-2007 19:22

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by Mike Bortfeldt (Post 631202)
Pat,

It looks like you are not being consistant with the data type for "color". You are inputting it as an integer (%d) so I'll assume you've defined it as such, however you are comparing it in the switch statement as a character. The value '0' will be converted to it's ASCII value (48) for the compare. If 'color' is an integer, then I'd try removing the single quotes from around the numbers in the case statements and see if that works.

Mike

Thanks, that did it. I didn't realize that single quotes changed things.

Pat McCarthy 10-06-2007 14:42

Re: C Programming Homework Help Needed
 
I think I need to make this the "Help Pat pass EGR 261" thread. :p

My problem this time is that a switch statement again.
After the menu displays, the user can enter a selection, but when they hit enter, it just displays a blank line and doesn't leave the switch statement.

Thanks for the continuing help guys.:)

Code:

        int menu_error;
        int menu_selection;

        do
        {
                do
                {
                        menu_error = 0;
               
                        /* Displays main menu */
                        printf("Please select from the following options:\n");
                        printf("(1) Draw a colored shape\n");
                        printf("(2) Clear graphics window\n");
                        printf("(3) Exit\n=>");
                        fflush(stdin);
                        scanf("%d\n", &menu_selection);

                        switch(menu_selection)
                        {
                                case 1:
                                        draw_shape();
                                        break;
                                       
                                case 2:
                                        clear_graphics();
                                        break;

                                case 3:
                                        break;

                                default:
                                        menu_error = 1;
                                        printf("Please enter a selection 1, 2, or 3");
                        }
                }
                while(menu_error);
        }
        while(menu_selection != 3);


Mike Bortfeldt 10-06-2007 15:55

Re: C Programming Homework Help Needed
 
Pat,

I'm not sure the problem is in the switch statement. Try removing the \n from the menu_selection scanf line ("%d" rather than "%d\n")

Mike

Pat McCarthy 10-06-2007 17:42

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by Mike Bortfeldt (Post 631297)
Pat,

I'm not sure the problem is in the switch statement. Try removing the \n from the menu_selection scanf line ("%d" rather than "%d\n")

Mike

That was it! Thanks again!

Pat McCarthy 01-07-2007 14:39

Re: C Programming Homework Help Needed
 
Back again!
I can't figure out how to convert a float value to a char string.
Suggestions? Thanks!

bear24rw 01-07-2007 15:19

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by Pat McCarthy (Post 633492)
Back again!
I can't figure out how to convert a float value to a char string.
Suggestions? Thanks!

Like take value 9.023 and turn it into '9' '.' '0' '2' '3' in a char string?

Idk how you would get each number individually but to change the number into its ASCII code you would do
# + '0' to get the ascii code of the number

Pat McCarthy 01-07-2007 15:21

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by bear24rw (Post 633500)
Like take value 9.023 and turn it into '9' '.' '0' '2' '3' in a char string?

Well, I have a float variable that I need to be able to display using WinBGI using the text function that only accepts char strings. So, I really don't know exactly.

EricVanWyk 01-07-2007 15:39

Re: C Programming Homework Help Needed
 
The function you are looking for is called "sprintf".

Use it just like you would use printf to print a float. The trick is that it throws it into a string, rather than at the console.

Code:

char * buffer = new char[10];
float f = 12.4;
sprintf(buffer,"%f",f);

I think... I don't have a C compiler in front of me.

Pat McCarthy 01-07-2007 20:48

Re: C Programming Homework Help Needed
 
Is there a header file you need to include?
I'm getting a 'no prototype for function' error for the sprintf function.

chris31 01-07-2007 21:05

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by Pat McCarthy (Post 633535)
Is there a header file you need to include?
I'm getting a 'no prototype for function' error for the sprintf function.

I believe you need to include stdio.h.

Pat McCarthy 01-07-2007 21:25

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by chris31 (Post 633538)
I believe you need to include stdio.h.

That made that error go away but I still don't really understand how to use the function.
The first line:

char * buffer = new char[10];

is confusing me.

eugenebrooks 01-07-2007 22:28

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by Pat McCarthy (Post 633546)
That made that error go away but I still don't really understand how to use the function.
The first line:

char * buffer = new char[10];

is confusing me.

The use of the "new" operator is C++ speak, not C speak.

char buffer[10]; /* bigger than 10 is a good idea */

If a static or automatic array (depending on the location
of the declaration) is good enough, or

char *buffer;

buffer = malloc(10); /* again, bigger than 10 is a good idea */

to allocate the storage using the heap allocator in C.

Eugene

Pat McCarthy 01-07-2007 22:40

Re: C Programming Homework Help Needed
 
1 Attachment(s)
I am using this code:
Code:

#include <stdio.h>

int main(void)
{
        char *buffer;

        buffer = malloc(10);
        float f = 12.4;
        sprintf(buffer,"%f",f);

        return 0;
}

Attached is the compile errors I am getting.

eugenebrooks 01-07-2007 22:46

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by Pat McCarthy (Post 633565)
I am using this code:
Code:

#include <stdio.h>

int main(void)
{
        char *buffer;

        buffer = malloc(10);
        float f = 12.4;
        sprintf(buffer,"%f",f);

        return 0;
}

Attached is the compile errors I am getting.

malloc() is likely declared in stdlib.h

Pat McCarthy 01-07-2007 23:01

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by eugenebrooks (Post 633568)
malloc() is likely declared in stdlib.h

It was. Thanks.

Now how can I use the char value?

I tried:
printf("%c", buffer);

But that printed out an an arrow pointing up.:p

eugenebrooks 01-07-2007 23:11

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by Pat McCarthy (Post 633570)
It was. Thanks.

Now how can I use the char value?

I tried:
printf("%c", buffer);

But that printed out an an arrow pointing up.:p

The result of sprintf is a null, '\0', terminated string.

printf("%s", buffer);


printf("%c", buffer[0]);
would print the first char

Eugene

Pat McCarthy 01-07-2007 23:14

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by eugenebrooks (Post 633573)
The result of sprintf is a null, '\0', terminated string.

printf("%s", buffer);


printf("%c", buffer[0]);
would print the first char

Eugene

Thanks! I think that should do it for this week!;)

Astronouth7303 03-07-2007 13:02

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by Pat McCarthy (Post 633570)
It was. Thanks.

Now how can I use the char value?

I tried:
printf("%c", buffer);

But that printed out an an arrow pointing up.:p

If you just want to print the value of the float, skip the sprintf() call and go straight to printf():
Code:

float f = 12.4;
printf("%f",f);

The *printf() family of functions (sprintf(), fprintf(), printf(), etc.) all work similarly. Becoming familiar with them will help.

If you ever have a simple question about a function, Google is your friend. (Just put in the function name or "C functionName".) Even Wikipedia has an article about most standard functions.

Pat McCarthy 02-09-2007 19:41

Re: C Programming Homework Help Needed
 
1 Attachment(s)
This code is supposed to convert a base 10 number, 123, into binary and display the value. Somewhere in the conversion, the division loop stops before it should, for a reason that I cannot identify.
Output with some diagnostic print statements attached.
Code:

/* Patrick McCarthy */

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

void base_convert(int base);
void convert_to_binary(int base, int number);
void divide(int D, int N, int *pq, int *pr);

int main(void)
{
        int base;
        int base_error;

        /* Gets the base from user and validates the value */
        do{
                base_error = 0;

                /* Collects base value from user */
                printf("Please enter an integer between 2 and 10 =>");
                fflush(stdin);
                scanf("%d",&base);

                /* Validate entry */
                switch (base)
                {
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                                break;
                        default:
                                base_error = 1;
                                printf("Invalid entry\n");
                }
        }
        while(base_error);

        /* Finds base N value of NUMBER */
//        base_convert(base);

        /* Converts number to Binary */
        convert_to_binary(base, 123);

        return 0;
}

void base_convert(int base)
{
        int i;
        int new[3];
        int NUMBER[3];
        int answer;

        //The base 10 number to be converted
        NUMBER[0] = 3;
        NUMBER[1] = 2;
        NUMBER[2] = 1;

        for(i = 0; i < 3; i++)
        {
                new[i] = ( NUMBER[i] * pow(base,i) );

                // Diagnostic
//                printf("i = %d; NUMBER[i] = %d; new[i] = %d\n", i, NUMBER[i], new[i]);
        };

        answer = new[0] + new[1] + new[2];

        printf("%d%d%d(Base 10) = %d(Base %d)", NUMBER[2],NUMBER[1],NUMBER[0],answer, base);

        return;
}

void convert_to_binary(int base, int number)
{
        int j,h;
        int q[16];
        int r[16];

        q[0] = number;

        for(j = 1; q[j] >= 0; j++)
        {
                printf("j=%d\n",j);
                divide(base, q[j-1], &q[j], &r[j]);
        }

        for(h = j; h <= 0; h--)
        {
                printf("%d", r[h]);
        }
}

void divide(int D, int N, int *pq, int *pr)
{
        int q,r;

        q = N / D;
        r = N % D;
       
        printf("Quotient: %d\nRemainder: %d\n\n", q,r);

        *pq = q;
        *pr = r;
}


EricVanWyk 02-09-2007 20:04

Re: C Programming Homework Help Needed
 
A few notes to make your life easier:

The switch(base) structure is confusing. I suggest replacing it with something that more clearly states what you want. I'd recommend something like

Code:

if(base <2 || base > 10) { Error !!}
I do like your use of the do while. However, I'd rather it set base_error=0.

Your printf statement doesn't really tell the user what you are going to do with the number. Put a more informative request in there.

"Please enter the base of the number (between 2 and 10)"

Please comment what q and r are. They are probably quotient and remainder, but explicit = maintainable.

Okay, enough with the picky details. Pain in the patookus, but trust me, you'll thank me later.


To clarify divide, I've used pass by reference, rather than by pointer. Also, I've added some more debuggging!
Code:

void divide(int D, int N, int &q, int &r)
{
        q = N / D;
        r = N % D;
       
        printf("%d/%d :: Quotient: %d\nRemainder: %d\n\n", N,D,q,r);
}



_____________________________________

Thought of a few more helper functions.
Code:

int convertFromBaseToBinary(int base, char * number_string)
{
        int num=0;        //number converted from string
        for(;number_string;number_string++)        //Scroll through the letters, starting with the most significant digit
                num = num*base+charToNumber(*number_string)       
        //num now holds the correct number
        return num;
}
int charToNumber(char a){
        return int(a-'0');
}
char numberToChar(int i){
        return char(i+'0');
}

EDIT 2
__________________________
Just noticed another bug.
for(j = 1; q[j] >= 0; j++)
will never terminate. I think you want q[j]>0 or maybe even q[j-1]>0

Edit 3
_________________________
And for more giggles, here is some Python
Code:

def convertToBase(num, base):
        s=[]
        while num is not 0:
                s=[num%base]+s
                num/=base
        return s


Pat McCarthy 02-09-2007 20:43

Re: C Programming Homework Help Needed
 
1 Attachment(s)
I'm having a little bit of trouble now. See output.
Code:

/* Patrick McCarthy */

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

void base_convert(int base);
void convert_to_binary(int base, int number);
void divide(int D, int N, int &q, int &r);

int main(void)
{
        int base;
        int base_error;

        /* Gets the base from user and validates the value */
        do{
                base_error = 0;

                /* Collects base value from user */
                printf("Please enter the base of the number (between 2 and 10) =>");
                fflush(stdin);
                scanf("%d",&base);

                /* Validate entry */
                if(base <2 || base > 10)
                {
                        base_error = 1;
                        printf("Invalid entry\n");
                }
               
        }
        while(base_error);

        /* Finds base N value of NUMBER */
//        base_convert(base);

        /* Converts number to Binary */
        convert_to_binary(base, 123);

        return 0;
}

void base_convert(int base)
{
        int i;
        int new[3];
        int NUMBER[3];
        int answer;

        //The base 10 number to be converted
        NUMBER[0] = 3;
        NUMBER[1] = 2;
        NUMBER[2] = 1;

        for(i = 0; i < 3; i++)
        {
                new[i] = ( NUMBER[i] * pow(base,i) );

                // Diagnostic
//                printf("i = %d; NUMBER[i] = %d; new[i] = %d\n", i, NUMBER[i], new[i]);
        };

        answer = new[0] + new[1] + new[2];

        printf("%d%d%d(Base 10) = %d(Base %d)", NUMBER[2],NUMBER[1],NUMBER[0],answer, base);

        return;
}

void convert_to_binary(int base, int number)
{
        int j,h;
        int q[16];
        int r[16];

        q[0] = number;

        for(j = 1; q[j]>0; j++)
        {
                printf("j=%d\n",j);
                divide(base, q[j-1], &q[j], &r[j]);
        }

        for(h = j; h <= 0; h--)
        {
                printf("%d", r[h]);
        }
}

void divide(int D, int N, int &q, int &r)
{
        int q,r;

        /* q is the quotient and r is the remainder */

        q = N / D;
        r = N % D;
       
        printf("%d/%d :: Quotient: %d\nRemainder: %d\n\n", N,D,q,r);
}


EricVanWyk 02-09-2007 20:54

Re: C Programming Homework Help Needed
 
You only half integrated my changes to divide.

q and r are coming in as references. You do not need to declare them again.

Also,
divide(base, q[j-1], &q[j], &r[j]);
should read as
divide(base, q[j-1], q[j], r[j]);

I'm going to be offline for a while. Good luck!

Pat McCarthy 02-09-2007 21:12

Re: C Programming Homework Help Needed
 
Got it working, thanks!

Pat McCarthy 08-09-2007 13:51

Re: C Programming Homework Help Needed
 
1 Attachment(s)
Don't you just hate those programs that have such a simple concept behind them, but are incredibly difficult to come up with a logarithm for?

I've got the embedded loops working properly, they start with the first character of the string, then check against all the following characters, then advances to the second character and checked against all the following characters and so forth.

I just can't seem to figure out the proper way to record if a character has been used, then make the loop exclude that character.

I could do it with some brute force tactics, but I'm sure there is a more elegant and less time consuming way.

Code:

/* Author:        Patrick McCarthy
 * Filename:        partiv.c
 * Description:        Takes in a string and prints it out with no character used more than once.
*/

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

int main(void);

int main(void)
{
        char temp[19];
        char final[19];
        int primary, secondary, j=0;
        int length;
        int used = 0, used_num;

        printf("Please enter a word or phrase => ");
        gets(temp);

        length = strlen(temp);

        /* Primary loop:
        * Starts with first string element, checks against all following
        * string elements for repeats
        */
        for(primary = 0; primary < length; primary++)
        {
                //printf("Primary = %d\n",primary);
               
                /* Secondary loop */
                for(secondary = primary + 1; secondary < length; secondary++)
                {
                        //printf("Secondary = %d\n",secondary);
                       
                        switch(used)
                        {
                                case 0:
                                {
                                        if(temp[primary] != temp[secondary])
                                        {
                                                final[j] = temp[primary];
                                                j++;
                                                used = 1;
                                        }
                                        break;
                                }
                                case 1:
                                {
                                        break;
                                }
                        }
                        /* Resets variable used to an unused condition */
                        used = 0;
                }

        }

        printf("\n");
        puts(final);
       
        return 0;
}


Alan Anderson 08-09-2007 15:00

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by Pat McCarthy (Post 641355)
I just can't seem to figure out the proper way to record if a character has been used, then make the loop exclude that character.

The way I'd do it is to have an array of flags, indexed by the ASCII value of the character. Before starting to print the string, set all flags to FALSE. For each character in the string, if the flag for that character's value is already TRUE, skip the character. Otherwise, print the character and set the flag to TRUE.

Pat McCarthy 08-09-2007 15:17

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by Alan Anderson (Post 641357)
The way I'd do it is to have an array of flags, indexed by the ASCII value of the character. Before starting to print the string, set all flags to FALSE.

When you declare an array like this:
Code:

int ascii_flag[128];
Does that automatically assign 0 or FALSE to each variable in the array?

DanDon 08-09-2007 15:51

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by Pat McCarthy (Post 641359)
When you declare an array like this:
Code:

int ascii_flag[128];
Does that automatically assign 0 or FALSE to each variable in the array?

I would personally run through a loop to make sure that each member of the array is initialized to FALSE.

Code:

for(i=0;i<128;i++){
    ascii_flag[i]=0;
}


Pat McCarthy 08-09-2007 16:38

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by dhoizner (Post 641364)
I would personally run through a loop to make sure that each member of the array is initialized to FALSE.

Code:

for(i=0;i<128;i++){
    ascii_flag[i]=0;
}


Thanks, that helped!

Pat McCarthy 09-09-2007 13:43

Re: C Programming Homework Help Needed
 
1 Attachment(s)
Ok, I think I'm really close, but there are a few problems still.

The program is supposed to not let letters of the alphabet be used more than once, whether that letter is upper or lower case. However, if the character is anything other than a letter, it is supposed to go right through the system, regardless of repeats.

Problems:
Currently, if a capital letter is the first character of the string, it won't print, but the same letter will print again after.
The last letter seems to be truncated.

After I get those problems worked out, I think that I can uncomment the last else if to take care of the remaining characters properly.

Thanks

Code:

/* Author:        Patrick McCarthy
 * Filename:        partiv.c
 * Description:        Takes in a string and prints it out with no letter of the alphabet used more than once.
*/

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

int main(void);

int main(void)
{
        char temp[19];
        int i;
        char final[19];
        int primary, secondary, j=0;
        int length;
        int ascii_flag[128];

        printf("Please enter a word or phrase => ");
        fflush(stdin);
        gets(temp);

        length = strlen(temp);

        for(i=0;i<128;i++)
        {
                ascii_flag[i]=0;
        }
       
       
        /* Primary loop:
        * Starts with first string element, checks against all following
        * string elements for repeats
        */
        for(primary = 0; primary < length; primary++)
        {
        //        printf("Primary = %d\n",primary);
               
                /* Secondary loop */
                for(secondary = primary + 1; secondary < length; secondary++)
                {
                //        printf("Secondary = %d\n",secondary);
                       
                        if(ascii_flag[temp[primary]] == 0)
                        {
                                // Checks for characters that are lowercase or uppercase letters
                                if( ((97 <= (temp[primary])) && ((temp[primary]) >= 122)) == 1)
                                {
                                        if(ascii_flag[temp[primary]-32] != 0)
                                        {
                                                final[j] = temp[primary];
                                                j++;
                                                ascii_flag[temp[primary]] = 1;
                                                ascii_flag[temp[primary]-32] = 1;
                                        }
                                }
                                else if( (((65 <= (temp[primary])) && ((temp[primary]) >= 90))) == 1)
                                {
                                        if(ascii_flag[temp[primary]+32] != 0)
                                        {
                                                final[j] = temp[primary];
                                                j++;
                                                ascii_flag[temp[primary]] = 1;
                                                ascii_flag[temp[primary]+32] = 1;
                                        }
                                }
                                // Processes the characters other than letters
                        /*        else if(ascii_flag[temp[primary]] == 0)
                                {
                                        final[j] = temp[primary];
                                        j++;
                                }*/
                        }
                }

        }

        printf("\n");
        puts(final);
       
        return 0;
}


Pat McCarthy 10-09-2007 20:20

Re: C Programming Homework Help Needed
 
Bump, because I'm still stuck.

Alan Anderson 10-09-2007 20:52

Re: C Programming Homework Help Needed
 
I don't understand the primary/secondary looping you're doing. You shouldn't have to look at each character more than once as you step through the string. If it's a non-letter, print it. If it's a letter and the character's flag isn't set to say you have seen it before, print it, and set that character's flag. It should be that simple.

Pat McCarthy 10-09-2007 21:06

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by Alan Anderson (Post 641595)
I don't understand the primary/secondary looping you're doing. You shouldn't have to look at each character more than once as you step through the string. If it's a non-letter, print it. If it's a letter and the character's flag isn't set to say you have seen it before, print it, and set that character's flag. It should be that simple.

Oh yeah, that is completely useless since I implemented the ascii_flag array. Just one for-while type statement is needed.
Still working on it.

Pat McCarthy 10-09-2007 21:53

Re: C Programming Homework Help Needed
 
I've cleaned it up a bit, but it quits reading the string after a space.
Also, I've identified a few problem characters: d, w, z, Z
Those characters give as a screen output.

Any clue as to why it would print the 'alt + 1' character instead of those letters?

Code:

/* Author:        Patrick McCarthy
 * Filename:        partiv.c
 * Description:        Takes in a string and prints it out with no letter of the alphabet used more than once.
*/

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

int main(void);

int main(void)
{
        char temp[19];
        int i, j=0;
        char final[19];
        int primary;
        int length;
        int ascii_flag[128];

        for(i=0;i<128;i++)
        {
                ascii_flag[i]=0;
        }       

        printf("Please enter a word or phrase => ");
        fflush(stdin);
        gets(temp);

        length = strlen(temp);

        /*
        */
        for(primary = 0; primary < length; primary++)
        {
                printf("\nPrimary = %d\n",primary);
                       
                if(ascii_flag[temp[primary]] == 0)
                {                               
                        // Checks for characters (ASCII) that are lowercase or uppercase letters
                        if( ((97 <= (temp[primary])) && ((temp[primary]) >= 122)) == 1)
                        {
                                if(ascii_flag[temp[primary]-32] != 0)
                                {
                                        final[j] = temp[primary];
                                        printf("%c\n",temp[primary]);
                                        j++;
                                        ascii_flag[temp[primary]] = 1;
                                        ascii_flag[temp[primary]-32] = 1;
                                }
                        }
                        else if( (((65 <= (temp[primary])) && ((temp[primary]) >= 90))) == 1)
                        {
                                if(ascii_flag[temp[primary]+32] != 0)
                                {
                                        final[j] = temp[primary];
                                        printf("%c\n",temp[primary]);
                                        j++;
                                        ascii_flag[temp[primary]] = 1;
                                        ascii_flag[temp[primary]+32] = 1;
                                }
                        }
                        // Processes the characters other than letters
                        else// if(ascii_flag[temp[primary]] == 0)
                        {
                                final[j] = temp[primary];
                                j++;
                        }
                }

        }

        printf("\n");
        puts(final);
       
        return 0;
}


Alan Anderson 10-09-2007 22:55

Re: C Programming Homework Help Needed
 
I'm having difficulty reading through the wordiness. Changing it to be a little more compact might help reveal any possible logic or syntax errors. For example, your code refers to temp[primary] a LOT. It might be clearer to say thischar = temp[primary]; once at the beginning of the loop, then refer to thischar thereafter.

Also, now that you've removed the "inner" loop, the term "primary" no longer applies. As part of the cleanup, consider changing it to "cursor" or something similar. I'm not sure what the name "ascii_flag" is supposed to mean; I'd have called it "letter_seen" or "already_printed" or "filter" or something descriptive.

I do see a couple of things that probably aren't right. The outer if statement looks either redundant or outright wrong. What is it supposed to be doing? The lowercase section looks at the flag for uppercase letters, and vice versa; you probably shouldn't be adding or subtracting the 32 when checking the flag.

There are also a few spots where I'd have combined operations, such as turning the two lines of printing at the end into a single printf() or combining the separate final[j] = ...; and j++; into a single final[j++] = ...;, but that's arguably a matter of personal style.

One last thing: I don't see anywhere that puts the trailing /0 on the string you're building in final. Without that string terminator, you'll have problems printing it.

dcbrown 10-09-2007 23:03

Re: C Programming Homework Help Needed
 
If you only care about a..z and A..Z but only need 1 flag per lower/upper pair that means just 26 flags. I'd have used a simple mask in a unsigned long instead of an array.

Initializing the single bit mask variable is straight forward. Then leverage the use of standard string/character functions [often implemented as macros]. If the character isalpha() [true if a..z or A..Z], then use tolower() to force the character to lower case. Subtract 'a' from this to get a 0..25 offset. Use the offset to create the bit check mask to see if the letter has been used before. If yes, then just continue on in the for loop. If no, set the bit to show the letter has been used and drop into common code that accumulates the character into the output string (and prints out the character). Repeat.


Something like:

Code:

#include <string.h>
#include <ctype.h>

char input[128], *src;
char output[128], *dst;
unsigned long mask;        /* Assumes long is at least 32 bits */
unsigned long flags;

    printf("Please enter a word or phrase => ");
    fflush(stdin);
    gets(input);

    flags = 0;
    dst = &output[0];
    for (src=&input[0]; *src != 0; src++)
    {
        if (isalpha(*src))
        {
              mask = 1<<(tolower(*src)-'a');
              if (flags & mask) continue;
              flags |= mask;
        }
        printf( "%c", *src );
        *dst++ = *src;
    }
    printf( "\n" );
    *dst = 0;
    puts( output );

The original code seems to have its comparisons incorrect?

Code:

if( ((97 <= (temp[primary])) && ((temp[primary]) >= 122)) == 1)
This clause is awkward as written.

if 'a' <= current input char and current input char >= 'z'

So }, |, {, ~ will meet this test because the character has to be greater than 'z' and all such characters will also meet the criteria that 'a' be less than that character. I think you meant to have

if current input char >= 'a' and current input char <= 'z' then process a..z ?


Bud

Pat McCarthy 10-09-2007 23:40

Re: C Programming Homework Help Needed
 
Thanks for the input guys, I've got it working finally.

Code:

/* Author:        Patrick McCarthy
 * Filename:        partiv.c
 * Description:        Takes in a string and prints it out with no letter of the alphabet used more than once.
*/

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

int main(void);

int main(void)
{
        char temp[19];
        int i, j=0;
        char final[19];
        int primary;
        int length;
        int ascii_flag[26];

        // Initializes the ascii_flag string.
        for(i=0;i<26;i++)
        {
                ascii_flag[i]=0;
        }
       
        // Initializes the final string.
        for(i=0;i<19;i++)
        {
                final[i]='\0';
        }       

        printf("Please enter a word or phrase => ");
        fflush(stdin);
        gets(temp);

        length = strlen(temp);

        for(primary = 0; primary < length; primary++)
        {
//                printf("\nPrimary = %d\n",primary);
                                                       
                        // Checks for characters (ASCII) that are lowercase or uppercase letters
                        if( ('A' <= temp[primary]) && (temp[primary] <= 'Z') )
                        {
                                if(!ascii_flag[temp[primary]-'A'])
                                {
                                        final[j] = temp[primary];
                                        printf("%c\n",temp[primary]);
                                        j++;
                                        ascii_flag[temp[primary]-'A'] = 1;
                                }
                        }
                        else if( ('a' <= temp[primary]) && (temp[primary] <= 'z') )
                        {
                                if(!ascii_flag[temp[primary]-'a'])
                                {
                                        final[j] = temp[primary];
                                        printf("%c\n",temp[primary]);
                                        j++;
                                        ascii_flag[temp[primary]-'a'] = 1;
                                }
                        }
                        // Processes the characters other than letters
                        else
                        {
                                final[j] = temp[primary];
                                j++;
                        }

        }

        printf("\n");
        puts(final);
       
        return 0;
}


Pat McCarthy 14-09-2008 21:35

Re: C Programming Homework Help Needed
 
Hi, looking for some help again!
This portion of my code prompts the user to input a 4-bit base-3 number then is supposed to check to make sure that all of the digits are within [0,2].
Currently, the error checking portion doesn't work properly. Many 4-bit numbers will work, many won't. I have a feeling it has to do with the array.

Code:

void ThreeToNine(void)
{
        int num[3];
        int n;
        int flag=0;
        // Range for Base-3 numbers
        int minVal=0, maxVal=2;

        while(flag==0)
        {
                flag=0;
               
                printf("Please enter the Base-3 number one digit at a time,\n");
                printf("starting with the most significant bit.\n");
                printf("MSB ====> "); fflush(stdin); scanf("%d",&num[3]);
                printf("Bit 2 ==> "); fflush(stdin); scanf("%d",&num[2]);
                printf("Bit 3 ==> "); fflush(stdin); scanf("%d",&num[1]);
                printf("LSB ====> "); fflush(stdin); scanf("%d",&num[0]);

                // Diagnostic
                printf("%d%d%d%d",num[3],num[2],num[1],num[0]);

                // Error checking loop
                for(n=3;n>=0;n--)
                {
                        if((num[n] >= minVal) && (num[n] <= maxVal))
                        {
                                if (n==0)
                                        flag=1;
                        }
                        else
                        {
                                printf("\nBit %d = %d",n,num[n]);
//                                printf("\nBit %d is not within the specified base. Try again.\n",n);
                        }
                }
               
                printf("\n");
        }
}


David Doerr 14-09-2008 21:48

Re: C Programming Homework Help Needed
 
Hi Pat,

Shouldn't your "for" loop start with its index set to 2 rather than 3? Your array size is 3 -- with an index of 0, 1 or 2.

Dave D

Pat McCarthy 14-09-2008 21:53

Re: C Programming Homework Help Needed
 
I just fixed that, but I'm still having the same problem.
As an example, I'll enter 1111 and the error checking appears to work, but then I'll enter 1211 and it will say there is an error with the second digit. This happens for any digit that has a value of 2.

David Doerr 14-09-2008 21:56

Re: C Programming Homework Help Needed
 
Sorry, no, your index is OK, but your array declaration should read

int num[4];

not

int num[3];

Pat McCarthy 14-09-2008 21:59

Re: C Programming Homework Help Needed
 
Thanks Dave! That seems to have taken care of it!
It's been a year since I've written code, so I'm a bit rusty. :p

David Doerr 14-09-2008 22:04

Re: C Programming Homework Help Needed
 
That C structured programming class seems to be dragging out for quite some time. It might be about time to start in on C++.

:)

Pat McCarthy 14-09-2008 22:09

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by David Doerr (Post 765504)
That C structured programming class seems to be dragging out for quite some time. It might be about time to start in on C++.

:)

Nah, it's been over multiple classes, just all using some C as a component of them.

StormRoBoT 17-09-2008 13:18

C Programming Homework Help Needed
 
help on palindrome

i have make a program that can trace palindrome number but i need it to loop over and over again till i keyin -1 then only the program terminate


this is the code that i have used:

Code:

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

void main()
{
char strsrc[5];
char strtmp[5];

printf("\n Enter a five-digit number ( -1 to end ): "); gets(strsrc);

strcpy(strtmp,strsrc);
strrev(strtmp);

if(strcmp(strsrc,strtmp)==0)
printf("\n %s is a palindrome\n",strsrc);
else
printf("\n %s is not a palindrome\n",strsrc);
}

any one can help?

Alan Anderson 17-09-2008 15:56

Re: C Programming Homework Help Needed
 
Quote:

Originally Posted by StormRoBoT (Post 765949)
i have make a program that can trace palindrome number but i need it to loop over and over again till i keyin -1 then only the program terminate

any one can help?

You want it to loop? Hint: use a while statement that never ends, putting all the things inside it that you want to keep executing over and over.

You want it to end? Hint: use an exit statement, but only execute it when the program is supposed to terminate.

ShotgunNinja 27-09-2008 22:15

Re: C Programming Homework Help Needed
 
What exactly do you mean by "loop"? Do you want it to repeatedly ask for a number, then check it for palindrome-ness (sorry, vocabulary suffered a non-Build season hit :D ) , or do you want to loop through calculations (a bit daft, but I don't know what the professor/employer expects...), or what?


All times are GMT -5. The time now is 13:22.

Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Copyright © Chief Delphi