Question

Ensure the following compiles 5. Variable scope (1 mark) Some variables are only accessible while executing...

Ensure the following compiles

5. Variable scope (1 mark)

Some variables are only accessible while executing specific code. Global variables are often thought of as evil because the state of a system can be altered making functions execute differently when it isn't expected.

There is also the issue of block scope. For an example of block scope, see the file below. Notice that you don't get an error because the code uses the correct syntax. Although the syntax is correct, you cannot access the variable "val" outside of the if/else statement. So any time you intend to use a variable, it can only accessed in code blocks nested deeper than the block it was declared in. It's generally good practice to use variables in the deepest block you can so variables aren't confused or unintentionally altered.


%%file src/scope.c

/***
* Name:
* Date:
* Course:
*
* Description:
***/

#include <stdio.h>

/* Returns 1 if num is positive (> 0), 0 if num is negative or 0*/
int isPositive(int num) {
    int val;
    
    if(num > 0) {
        int val = 1;
    } else {
        int val = 0;
    }
    
    return val;
}



int main() {
    
    printf("%d\n", isPositive(6));
    printf("%d\n", isPositive(-6));
    
    return 0;
}


%%bash
gcc src/scope.c -o bin/testScope
./bin/testScope

Now that you have seen a runtime bug slip through the cracks, try adding the flags we normally use in this course to the code above to see what happens.

5.a. Fix the code below (1 mark)

Fix the code below to properly display the result. The program contains a single block of code around the if/else statement. You can change the code however you want to display the correct result as long you don't change the function signature. i.e. parameters and return value

Don't code like this, it's very difficult to read and predict behaviour because programmers easily confuse which variable is being accessed, thus varying the expected behaviour. This is just to demonstrate what you should avoid and why this is undesirable.


%%file src/scope.c

/***
* Name:
* Date:
* Course:
*
* Description:
***/

#include <stdio.h>


/* Global variable, avoid using these! */
int num = 6;


/* Returns 1 if num is positive (> 0), 0 if num is negative or 0*/
int isPositive(int num) {
    int val;
    
    {
        extern int num;
        
        if(num > 0) {
            int val = 1;
        } else {
            int val = 0;
        }
    }
    
    return val;
}


%%file include/lab2.h

/***
* Name:
* Date:
* Course:
*
* Description:
***/


#include<stdio.h>


/***
* Function prototype
***/


/* ifElse.c */
int newNumber(int oldNumber);


/* switch.c files */
int replaceZero(int numTwo);

int userDecision(int userInput, int numOne, int numTwo);


/* while.c */
int absoluteValue(int value);

int overflow(int dividend, int divisor);


/* forLoop.c */
float average(float numbers[], int length);


/* scope.c */
int isPositive(int num);



%%file src/main.c

/***
* Name:
* Date:
* Course:
*
* Description:
***/


#include "lab2.h"

int main(int argc, char *argv[]) {
    /* average is 6.0 */
    float aTestOne[] = {5.0, 6.0, 7.0};
    
    printf("Hello, World\n");
    
    printf("\n*** If/else ***\n");
    printf("This should be 1, %d\n", newNumber(0));
    printf("This should be 21, %d\n", newNumber(-21));
    printf("This should be 0, %d\n", newNumber(21));
    printf("This should be 13, %d\n", newNumber(13));
    
    printf("\n*** switch ***\n");
    
    printf("\n*** while loop ***\n");
    printf("overflow of 25/6 = %d, (should be %d)\n", overflow(25, 6), 5);
    printf("overflow of -14/9 = %d, (should be %d)\n", overflow(-14, 9), 4);
    
    printf("\n*** for loop ***\n");
    
    printf("\n*** Variable scope ***\n");
    
    return 0;
}

%%bash
gcc src/scope.c -o bin/testScope
./bin/testScope

6.b. Pass by Reference (2 marks)

Pass by reference refers to how variables are passed in functions when using pointers in c. Pointers behave differently (pass by reference) unlike pass by value shown above, finish the code below to swap the value of two char* variables passed. This can be a little difficult when first learning the basics of programming, but stick with it and pointer manipulation will eventually make sense.

%%file src/swap.c

/***
* Name:
* Date:
* Course:
*
* Description:
***/

void swapString(char **varOne, char **varTwo) {
    
}

%%file include/lab2.h

/***
* Name:
* Date:
* Course:
*
* Description:
***/


#include<stdio.h>


/***
* Function prototypes
***/


/* from ifElse.c */
int newNumber(int oldNumber);


/* switch.c files */
int replaceZero(int numTwo);

int userDecision(int userInput, int numOne, int numTwo);


/* while.c */
int absoluteValue(int value);

int overflow(int dividend, int divisor);


/* forLoop.c */
float average(float numbers[], int length);


/* scope.c */
int isPositive(int num);


/* swap.c */
void swapString(char **varOne, char **varTwo);

%%file src/main.c
/***
* Name:
* Date:
* Course:
*
* Description:
***/


#include "lab2.h"


int main(int argc, char *argv[]) {
    char *stringOne = "String one!";
    char *stringTwo = "String, the second!";
    
    printf("Hello, World\n");
    
    printf("\n*** If/else ***\n");
    printf("This should be 1, %d\n", newNumber(0));
    printf("This should be 21, %d\n", newNumber(-21));
    printf("This should be 0, %d\n", newNumber(21));
    printf("This should be 13, %d\n", newNumber(13));
    
    printf("\n*** switch ***\n");
    
    printf("\n*** while loop ***\n");
    printf("overflow of 25/6 = %d, (should be %d)\n", overflow(25, 6), 5);
    printf("overflow of -14/9 = %d, (should be %d)\n", overflow(-14, 9), 4);
    
    printf("\n*** for loop ***\n");
    
    printf("\n*** Variable scope ***\n");
    
    printf("\n*** swap ***\n");
    printf("swap \"%s\" with \"%s\"\n", stringOne, stringTwo);
    swapString(&stringOne, &stringTwo);
    printf(" stringOne = \"%s\" \n", stringOne);
    printf(" stringTwo =\"%s\" \n", stringTwo);
    
    return 0;
}


I'm being lazy after compiling this many times. I am going to shorten everything by compiling all the c files in the src directory into a single exexutable using the "src/*.c" command to select all of the files. Before doing this you need to be sure that there is only one main function defined or the compiler will not be able to choose which main function to run.

%%bash
gcc -Wall -pedantic -ansi -Iinclude src/*.c -o bin/runMe
./bin/runMe

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find my implementation for two function.

Please repost others in sepatate post.

/*For loops are used when the developer knows the number of iterations.
Write a for loop to find the average of a list of floats, use the skeleton below
and make sure to return a float.*/

/***
* Name:
* Date:
* Course:
*
* Description:
***/


float average(float numbers[], int length) {
float sum = 0;
int i;
for(i=0; i<length; i++)
sum = sum + numbers[i]

return sum/length;
}

// 6.b
void swapString(char **varOne, char **varTwo) {

char *t = *varOne;
*varOne = *varTwo;
*varTwo = t;
}

Add a comment
Know the answer?
Add Answer to:
Ensure the following compiles 5. Variable scope (1 mark) Some variables are only accessible while executing...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Combine two codes (code 1) to get names with(code 2) to get info: Code 1: #include<unistd.h>...

    Combine two codes (code 1) to get names with(code 2) to get info: Code 1: #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<dirent.h> #include<stdio.h> #include<stdlib.h> void do_ls(char []); int main(int argc,char *argv[]) { if(argc == 1) do_ls("."); else while(--argc){ printf("%s:\n",*++argv); do_ls(*argv); } } void do_ls(char dirname[]) { DIR *dir_ptr; struct dirent *direntp; if((dir_ptr = opendir(dirname)) == NULL) fprintf(stderr,"ls1:cannot open %s\n",dirname); else { while((direntp = readdir(dir_ptr)) != NULL) printf("%s\n",direntp->d_name); closedir(dir_ptr); } } ____________________________ code 2: #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> void show_stat_info(char *,...

  • C program. Using do-while loop for this question. Question: write a program to calculate the average...

    C program. Using do-while loop for this question. Question: write a program to calculate the average of first n numbers. output: Enter the value of n : 18 The sum of first 18 numbers =171 The average of first 18 numbers = 9.00 my code couldn't give me the right avg and sum. Please help. #include<stdio.h> int main() {     int num;     int count =0;     int sum=0;     float avg;      printf("Enter the value of n: ");    ...

  • URGENT. Need help editing some C code. I have done most of the code it just...

    URGENT. Need help editing some C code. I have done most of the code it just needs the following added: takes an input file name from the command line; opens that file if possible; declares a C struct with three variables; these will have data types that correspond to the data types read from the file (i.e. string, int, float); declares an array of C structs (i.e. the same struct type declared in point c); reads a record from the...

  • Part D. On executing the below program, what will be the output of the following program...

    Part D. On executing the below program, what will be the output of the following program if the source file contains a line "This is a sample."? [5 marks] #include <stdio.h> int main() { char ch; int k, n=0; FILE * fs = fopen("source.txt", "r"); while(1) { ch = fgetc(fs); if(ch == EOF) break; else { for(k=0;k<4;k++) fgetc(fs); printf("%c", ch); n += k; } } printf("%d\n", n); fclose(fs); return 0; } ---------------------------------- Any one can explain the question to me...

  • can u please solve it in c++ format,,,, general format which is #include<stdio.h> .......printf and scanf...

    can u please solve it in c++ format,,,, general format which is #include<stdio.h> .......printf and scanf format dont worry about the answers i have down Q3, What is the output of the program shown below and explain why. #include #include <stdio.h> <string.h> int main(void) ( char str[ 39764 int N strlen(str) int nunj for (int i-0; i t Nǐ.de+ printf(") num (str[] 'e); I/ digits range in the ASCII code is 48-57 if (nue > e) f 9 printf( Xdin,...

  • The following C code keeps returning a segmentation fault! Please debug so that it compiles. Also...

    The following C code keeps returning a segmentation fault! Please debug so that it compiles. Also please explain why the seg fault is happening. Thank you #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // @Name loadMusicFile // @Brief Load the music database // 'size' is the size of the database. char** loadMusicFile(const char* fileName, int size){ FILE *myFile = fopen(fileName,"r"); // Allocate memory for each character-string pointer char** database = malloc(sizeof(char*)*size); unsigned int song=0; for(song =0; song < size;...

  • Please write MIPS program that runs in QtSpim (ex: MipsFile.s) Write a MIPS program that will...

    Please write MIPS program that runs in QtSpim (ex: MipsFile.s) Write a MIPS program that will read in a base (as an integer) and a value (nonnegative integer but as an ASCII string) in that base and print out the decimal value; you must implement a function (which accepts a base and an address for a string as parameters, and returns the value) and call the function from the main program. The base will be given in decimal and will...

  • How would I change the following C code to implement the following functions: CODE: #include <stdio.h>...

    How would I change the following C code to implement the following functions: CODE: #include <stdio.h> #include <stdlib.h> int main(int argc, char * argv[]) { if (argc != 2) printf("Invalid input!\n"); else { FILE * f = fopen (argv[1], "r"); if (f != NULL) { printf("File opened successfully.\n"); char line[256]; while (fgets(line, sizeof(line), f)) { printf("%s", line); } fclose(f); } else { printf("File cannot be opened!"); } } return 0; } QUESTION: Add a function that uses fscanf like this:...

  • Writing a program in C please help!! My file worked fine before but when I put...

    Writing a program in C please help!! My file worked fine before but when I put the functions in their own files and made a header file the diplayadj() funtion no longer works properly. It will only print the vertices instead of both the vertices and the adjacent like below. example input form commnd line file: A B B C E X C D A C The directed edges in this example are: A can go to both B and...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT