Like Tree4Likes
  • 2 Post By whiteflags
  • 2 Post By Matticus

3 Small C Programs

This is a discussion on 3 Small C Programs within the C Programming forums, part of the General Programming Boards category; I have a HW assignment that I am getting stuck on, hopefully someone can help me fix my code. There ...

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    6

    3 Small C Programs

    I have a HW assignment that I am getting stuck on, hopefully someone can help me fix my code. There are 3 separate programs, I feel confident in the second one, and it compiled with no errors, but number 1 and 3 have proven to be a little trickier for me. Thanks in advance for your help.

    1) Create a 2-by-3 two-dimensional array of integers and fill it with data. Loop through the array and locate the smallest value stored. Print out the smallest value as well as its row and column position in the array.

    Code:
    #include <stdio.h>
    
    main ()
    
    {
    void selectionSort (int a[], int size)
    {
    int arr[2][3]={
    {1,2},
    {4,5},
    {7,8}
    };
    int pass, min, minIndex;
    for (pass = 0; pass < size - 1; pass++)
    {
    min = a[pass];
    minIndex = pass;
    printf("\nSmallest Value is: %d\n", minIndex);
    }
    return;
    }
    }

    2) Prompt the user for 3 sentences of text. Pass these pieces of text into a function connect() which will connect all three sentences into one long sentence. Pass the combination sentence back to the main program, where it is printed.

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    char *combineString(char *string1, char *string2, char *string3)
    {
    char *CombinedString;
    
    CombinedString = malloc(80);
    
    CombinedString[0] = 0;
    
    strcat(CombinedString, string1);
    strcat(CombinedString, " ");
    strcat(CombinedString, string2);
    strcat(CombinedString, " ");
    strcat(CombinedString, string3);
    return (CombinedString);
    }
    
    int main ()
    {
    char string1[20];
    char string2[20];
    char string3[20];
    
    printf("Please enter first sentence: ");
    scanf(" %19[^\n]", string1);
    
    printf("Please enter second sentence: ");
    scanf(" %19[^\n]", string2);
    
    printf("Please enter third sentence: ");
    scanf(" %19[^\n]", string3);
    
    printf("Combined sentence is: %s\n\n", combineString(string1,string2,string3));
    
    getchar();
    getchar();
    return(0);
    }

    3) Write a program that will prompt the user for a file name and open that file for reading. Print out all the information in the file, numbering each new line of text.

    Code:
    #include <stdio.h>
    
    int main(void)
    	{
    	int c;
    	FILE *file;
    	file = fopen("test.txt", "r");
    	if (file) {
    	while ((c = getc(file)) != EOF)
    		putchar(c);
    	fclose(file);
    	return 0;
    	}

  2. #2
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,762
    For your first program:

    You cannot declare functions inside of other functions.

    Code:
    #include <stdio.h>
    
    main()
    {
        void selectionSort( int a[], int size ) {
            int arr[2][3] = {
                {1, 2},
                {4, 5},
                {7, 8}
            };
            int pass, min, minIndex;
            for( pass = 0; pass < size - 1; pass++ ) {
                min = a[pass];
                minIndex = pass;
                printf( "\nSmallest Value is: %d\n", minIndex );
            }
            return;
        }
    }
    There are other things wrong with the main() function as well.

    For the second program:

    Your strings are quite small. I would plan for longer sentences than that but I suppose it is up to you, given the directions.

    You should not have allowed the memory to leak though.
    Code:
    printf("Combined sentence is: %s\n\n", combineString(string1,string2,string3));
    Once printf finishes, you don't have access to the memory anymore. The proper way to write this is:
    Code:
    char *combined = combineString(string1, string2, string3);
    printf("Combined sentence is: %s\n\n", combined);
    free(combined);
    The malloc() function must be paired with free(). You must call free() if C documentation says you are responsible for memory cleanup, as well.

    For the third program, shouldn't you work out how to check c if it's a newline? And then printing a line number after it.

    I have to say, I'm quite surprised at the errors. To the point that I am suspicious actually. I mean, in one program, you have a near perfect solution and you understand that functions are listed one after the other, as opposed to being nested inside one another. In one place you do things right, and another it's like you have no idea. It's surprisingly inconsistent. For these reasons, I won't help anymore than I already have. I am ok with being wrong - but three people wrote three programs here. And all of them don't know what indentation is!
    Matticus and Tanu like this.

  3. #3
    Registered User
    Join Date
    Sep 2011
    Location
    Dongargarh, India
    Posts
    16

    Problem 1

    As you have said you are kinda sure about 2'nd problem i'd try to help you with other two...
    Quote Originally Posted by Pl2lNCE View Post
    1) Create a 2-by-3 two-dimensional array of integers and fill it with data. Loop through the array and locate the smallest value stored. Print out the smallest value as well as its row and column position in the array.

    Code:
    #include <stdio.h>
    
    main ()
    
    {
    void selectionSort (int a[], int size)
    {
    int arr[2][3]={
    {1,2},
    {4,5},
    {7,8}
    };
    int pass, min, minIndex;
    for (pass = 0; pass < size - 1; pass++)
    {
    min = a[pass];
    minIndex = pass;
    printf("\nSmallest Value is: %d\n", minIndex);
    }
    return;
    }
    }
    first of all you can't define the function "selection sort" inside main function & you have not even called it once...
    I suggest reading about functions more before using them, just put your code inline for now.

    what is "size"???
    in the for loop???

    and as you have a 2D array, you'd need nested loops to traverse the whole array...
    or you could use a pointer, which i guess you would not be used to yet...
    & you will need two values to find the index of the smallest value.

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    2,706
    Salem and nvoigt like this.

  5. #5
    Registered User
    Join Date
    Sep 2011
    Location
    Dongargarh, India
    Posts
    16

    Third Problem

    Quote Originally Posted by Pl2lNCE View Post

    3) Write a program that will prompt the user for a file name and open that file for reading. Print out all the information in the file, numbering each new line of text.

    Code:
    #include <stdio.h>
    
    int main(void)
        {
        int c;
        FILE *file;
        file = fopen("test.txt", "r");
        if (file) {
        while ((c = getc(file)) != EOF)
            putchar(c);
        fclose(file);
        return 0;
        }
    Here are a few suggestions...

    1. try using fgets instead of getc.
    2. use a counter to count and print the number of lines in the text.
    3. Learn how to indent your code.
    4. try to read more before posting your problems on online forums.
    5. other users might not be too inclined to address your problems directly if you don't properly indent your code or make sillier than n00b mistakes. But don't get discouraged by that, mistakes are GOOD!

  6. #6
    Registered User
    Join Date
    Jan 2013
    Posts
    6

    Update

    Thanks for helping me out, I think I am pretty close to what I need can somebody just review these new programs and tell me if it looks good.

    I know the indentations still aren't fixed and some stuff is sloppy, but it's a work in progress so please bear with me.



    1) Create a 2-by-3 two-dimensional array of integers and fill it with data. Loop through the array and locate the smallest value stored. Print out the smallest value as well as its row and column position in the array.
    Code:
    #include <stdio.h>
     
    main()
    {
        int array[2][3] = {{10, 12, 33},{11, 28, 32},}; 
        int size = 6;
        int minimum, c, location = 1;
          
        for ( c = 0 ; c < size ; c++ )
            scanf("%d", &array[c]);
       
        minimum = array[0];
       
        for ( c = 1 ; c < size ; c++ )
        {
            if ( array[c] < minimum )
            {
               minimum = array[c];
               location = c+1;
            }
        }
       
        printf("Minimum element is present at location number %d and it's value is %d.\n", location, minimum);
        return 0;
    }
    2) Prompt the user for 3 sentences of text. Pass these pieces of text into a function connect() which will connect all three sentences into one long sentence. Pass the combination sentence back to the main program, where it is printed.
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
     
    char *combineString(char *string1, char *string2, char *string3)
    {
    char *CombinedString;
     
    CombinedString = malloc(200);
     
    CombinedString[0] = 0;
     
    strcat(CombinedString, string1);
    strcat(CombinedString, " ");
    strcat(CombinedString, string2);
    strcat(CombinedString, " ");
    strcat(CombinedString, string3);
    return (CombinedString);
    }
     
    int main ()
    {
    char string1[50];
    char string2[50];
    char string3[50];
     
    printf("Please enter first sentence: ");
    scanf(" %19[^\n]", string1);
     
    printf("Please enter second sentence: ");
    scanf(" %19[^\n]", string2);
     
    printf("Please enter third sentence: ");
    scanf(" %19[^\n]", string3);
     
    char *combined = combineString(string1, string2, string3);
    printf("Combined sentence is: %s\n\n", combined);
    free(combined);
     
    getchar();
    getchar();
    return(0);
    }
    3) Write a program that will prompt the user for a file name and open that file for reading. Print out all the information in the file, numbering each new line of text.
    Code:
    #include <stdio.h>
    int main ( void )
    {
    static const char filename[] = "Final-3.txt";
    FILE *file = fopen ( filename, "r" );
    if ( file != NULL )
    {
    char line [ 999 ]; 
    while ( fgets ( line, sizeof line, file ) != NULL ) 
    {
    printf(__LINE__, fputs (line, stdout ));
    }
    fclose ( file );
    }
    else
    {
    perror ( filename );
    }
    return 0;
    }
    Last edited by Pl2lNCE; 01-30-2013 at 03:21 PM.

  7. #7
    Registered User
    Join Date
    Nov 2012
    Posts
    1,220
    In your first program you have this line:

    Code:
    scanf("%d", &array[c]);
    This is not correct since you have defined array as a 2d array. In other words, you must say &array[y][x], where y is the row index and x is the column index - in other words, you need two index variables.

    2. In your second program I didn't test it but I noticed the spec called for a function named "connect" but you named your function something else. Maybe it seems like a small detail, but this means to me that it doesn't meet the requirement. For example, the standard library is supposed to provide a function called `strcpy'. If I get a compiler that calls it `stringcopy' instead then I would throw that compiler away immediately.

  8. #8
    Registered User
    Join Date
    Jan 2013
    Posts
    6
    okay so if i change program 1 to use 2 index variables on the array, like this:

    Code:
    #include <stdio.h>
      
    main()
    {
        int array[2][3] = {{10, 12, 33},{11, 28, 32},};
        int size = 6;
        int minimum, b, c, location = 1;
           
        for ( c = 0 ; c < size ; c++ )
            scanf("%d", &array[b][c]);
        
        minimum = array[0][0];
        
        for ( c = 1 ; c < size ; c++ )
        {
            if ( array[b][c] < minimum )
            {
               minimum = array[b][c];
               location = c+1;
            }
        }
        
        printf("Smallest Value: %d  at  Location Number: %d.\n", minimum, location);
        return 0;
    }
    then how should i alter my for statements and the location so they are relative to variable b and c without causing any conflicts

  9. #9
    Casual Visitor
    Join Date
    Oct 2001
    Posts
    350
    Code:
        int size=6;
        int minimum, b, c, location = 1;
           
        for ( c = 0 ; c < size ; c++ )
            scanf("%d", &array[b][c]);
    Making a habit of using code like above is going to burn you if you're not careful. You're using b without it being initialized - its value could be anything. c becomes out of bounds once it moves past 2. array[2][3] has valid index positions of [0-1][0-2].

    Why do you wait for input when you're asked to initialize an array, find the smallest value, and the position it's found? You don't need scanf at all.

    Code:
    if ( array[b][c] < minimum )
    {
         minimum = array[b][c];
         location = c+1;
    }
    With each iteration of c, you're trying to test array[???][1-5]. This whole loop is probably not what you want.

    If you're wanting to flatten the array, try

    Code:
    smallest = *(*array);
    location = 0;
    
    for(c = 1; c < size; ++c)
    {
       if(smallest > *(*array + c))
       {
           // update stuff
       }
    }
    Location *would* be the position within the flattened array though. You'll have to putz around with its value, one of the dimensions, and an operator or two to find the row and col of the 2d array.

    You might also consider using symbolic constants for the array size and loop control. It's a good habit to get into, and as your programs grow, it will be a lot easier to change a few constants at the top of the source than it will be to track down a bunch of variables and loops embedded throughout the source.
    I haven't used a compiler in ages, so please be gentle as I try to reacclimate myself. :P

  10. #10
    Registered User
    Join Date
    Jan 2013
    Posts
    6

    Last Call - For any guidance

    These are the final programs and I was wondering if I could get some help on me final review before submission. Can somebody please tell me what glaring omissions and errors, if any, are present in this code? Thanks again


    1) Create a 2-by-3 two-dimensional array of integers and fill it with data. Loop through the array and locate the smallest value stored. Print out the smallest value as well as its row and column position in the array.
    Code:
    #include <stdio.h>
       
    main()
    {
        int min, minrow, mincol, size, b, c;
        int array[2][3] = {{10, 12, 33},{11, 28, 32},};
    for ( c = 0 ; c < size ; c++ )
    {
            if ( array[b][c] < min )
            {
               min = array[b][c];
               minrow = b;
           mincol = c;
            }
    } 
        printf("Smallest Value: %d.\n", min);
        printf("Value located in Row: %d Column: %d.\n", minrow, mincol);
        return 0;
    }
    2) Prompt the user for 3 sentences of text. Pass these pieces of text into a function connect() which will connect all three sentences into one long sentence. Pass the combination sentence back to the main program, where it is printed.
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
      
    char *combineString(char *string1, char *string2, char *string3)
    {
    char *CombinedString;
      
    CombinedString = malloc(200);
      
    CombinedString[0] = 0;
      
    strcat(CombinedString, string1);
    strcat(CombinedString, " ");
    strcat(CombinedString, string2);
    strcat(CombinedString, " ");
    strcat(CombinedString, string3);
    return (CombinedString);
    }
      
    int connect ()
    {
    char string1[50];
    char string2[50];
    char string3[50];
      
    printf("Please enter first sentence: ");
    scanf(" %19[^\n]", string1);
      
    printf("Please enter second sentence: ");
    scanf(" %19[^\n]", string2);
      
    printf("Please enter third sentence: ");
    scanf(" %19[^\n]", string3);
      
    char *combined = combineString(string1, string2, string3);
    printf("Combined sentence is: %s\n\n", combined);
    free(combined);
      
    getchar();
    getchar();
    return(0);
    }
    3) Write a program that will prompt the user for a file name and open that file for reading. Print out all the information in the file, numbering each new line of text.
    Code:
    #include <stdio.h>
    int main ( void )
    {
    char filename[256];
    printf("Filename: ");
    scanf("%s", &filename);
    FILE *file = fopen(filename, "r");
    if ( file != NULL )
    {
    char line [ 999 ];
    while ( fgets ( line, sizeof line, file ) != NULL )
    {
    printf(__LINE__, fputs (line, stdout ));
    }
    fclose ( file );
    }
    else
    {
    perror ( filename );
    }
    return 0;
    }

  11. #11
    Registered User
    Join Date
    Jun 2011
    Posts
    2,706
    In your first program, "size" "b" and "min" are used before they are initialized, so they will contain garbage.

  12. #12
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Have you actually tried to compile the programs? If so, what errors/warnings did you get?

    Quote Originally Posted by Pl2lNCE View Post
    3) Write a program that will prompt the user for a file name and open that file for reading. Print out all the information in the file, numbering each new line of text.
    Code:
    printf(__LINE__, fputs (line, stdout ));
    You are just copy'n'pasting code snippets found somewhere on the internet.

    Bye, Andreas

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 08-28-2012, 07:11 AM
  2. Replies: 1
    Last Post: 11-09-2009, 07:03 AM
  3. Replies: 1
    Last Post: 01-19-2006, 02:37 PM
  4. A small problem with a small program
    By Wetling in forum C Programming
    Replies: 7
    Last Post: 03-25-2002, 09:45 PM
  5. Active c programs.....a small prog. as starter
    By Animate in forum C Programming
    Replies: 4
    Last Post: 03-13-2002, 03:11 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21