Homework 1

C Language Programming

 

bullet

Write and test the following 10 C programs .

                                              

  1. A program that uses a while loop to count from 1 to 10. Each number should be printed on a separate line.

  2. A program that reads a character from the keyboard and prints it on the screen.

  3. A program that uses a for loop to display the characters ‘A’ through ‘Z’.  

  4. A program that has two functions; the main function and a function called factorial. The main function should call the factorial function and print the return value. The factorial function should accept one integer parameter n, and returns the factorial n! of this integer, e.g., 5! = 1*2*3*4*5 = 120. Hint: the factorial function should be defined as follows:

  int factorial (int n) {

…

}

  1. A program that reads one line from the standard input stream and assigns it to a string variable. The program should find and print the number of spaces in this string, and should find and print the length of this string without using the strlen() function. Hint: the following C code gets one line from the standard input stream and stores it in s.

char s[100];

gets(s);

  1. A program that gets two integers from the standard input stream x and y. The program should print the results of applying all the C unary operators on x and the results of applying all the C binary operators on x and y. Include in your program all the C arithmetic, relational, logical, and bitwise operators. Hint: the following C code gets one integer from the standard input stream and assigns it to x.

int x;

scanf(“%d”, &x);

  1. A program that gets 10 integers from the standard input stream and finds their sum, average, and the minimum and maximum values.

  2. A program that accepts a filename from the standard input and uses this filename to create a new file and write the string “This is a new file” into the created file.

  3. Write and test the function int strrindex(char s[], char c), which returns the position of the rightmost occurrence of character c in the string s, or –1 if there is none.

  4. The following function removes all occurrences of the character c from the string s. Write and test an alternate version of squeeze(char s1[], char s2[]), which deletes each character in s1 that matches any character in the string s2.

/* squeeze: delete all c from s */

void squeeze(char s[], char c) {

   int i, j;

 

   for (i = j = 0; s[i] != ‘\0‘; i++)

        if (s[i] != c)

             s[j++] = s[i];

   s[j] = ‘\0‘;

}