C Programming/Beginning exercises

From Wikibooks, open books for an open world
Jump to: navigation, search
Previous: File IO Index Next: Arrays



Contents

[edit] Variables

[edit] Naming

  1. Can a variable name start with a number?
  2. Can a variable name start with a typographical symbol (e.g. #, *, _)?
  3. Give an example of a C variable name that would not work. Why doesn't it work?
Solution
  1. No, the name of a variable must begin with a letter (lowercase or uppercase), or an underscore.
  2. Only the underscore can be used.
  3. for example, #nm*rt is not allowed because # and * are not the valid characters for the name of a variable.
#include<stdio.h>
main()
{
    int a,b,c,max;
    clrscr();
    printf("\nenter three numbers");
    scanf("%d%d%d",&a,&b,&c);
    max=a;
    if(max<b)
        max=b;
    if(max<c);
        max=c;
    printf("\nlargest=%d",max);
    getch();
}


[edit] Data Types

  1. List at least three data types in C
    1. On your computer, how much memory does each require?
    2. Which ones can be used in place of another? Why?
      1. Are there any limitations on these uses?
      2. If so, what are they?
      3. Is it necessary to do anything special to use the alternative?
  2. Can the name we use for a data type (e.g. 'int', 'float') be used as a variable?
Solution
  • 3 data types : long int, short int,float.
  • On my computer :
    • long int : 4 byte
    • short int : 2 bytes
    • float : 4 bytes
  • we can not use 'int' or 'float' as a variable's name.


[edit] Assignment

  1. How would you assign the value 3.14 to a variable called pi?
  2. Is it possible to assign an int to a double?
    1. Is the reverse possible?
Solution
double pi;
pi=3.14;
  • Extra credit for the following answer
const float pi = 3.14;

Since pi is a constant, good programming convention dictates to make it unchangeable during runtime.

  • Yes, for example :
int a=67;
double b;
b=a;
  • Yes, but a cast is necessary and the double is truncated:
double a=89;
int b;
b=(int) a;


[edit] Referencing

  1. A common mistake for new students is reversing the assignment statement. Suppose you want to assign the value stored in the variable "pi" to another variable, say "pi2":
    1. What is the correct statement?
    2. What is the reverse? Is this a valid C statement (even if it gives incorrect results)?
    3. What if you wanted to assign a constant value (like 3.1415) to "pi2":
      a. What would the correct statement look like?
      b. Would the reverse be a valid or invalid C statement?
Solution
  1. pi2 = pi;
  2. The reverse, pi = pi2; is a valid C statement if pi is not a constant.
  3. a. pi2 = 3.1415;
    b. The reverse: 3.1415 = pi2; is not valid since it is impossible to assign a value to a literal.


[edit] Simple I/O

[edit] Input

  1. scanf() is a very powerful function. Describe some features that make it so versatile.
  2. Write the scanf() function call that will read into the variable "var":
    1. a float
    2. an int
    3. a double
Solution
scanf("%f",&var);    //read float into var
scanf("%d",&var);    //read int into var
scanf("%lf", &var);  //read double into var


[edit] String manipulation

1. Write a program that prompts the user for a string, and prints its reverse.

Solution

One possible solution could be:

#include <stdio.h>
#include <string.h>
 
int main(void)
{   
    char s[81]; // A string of upto 80 chars + '\0'
    int i;
 
    puts("Please write a string: ");
    fgets(s, 81, stdin);
 
    puts("Your sentence in reverse: ");
    for (i= strlen(s)-1; i >= 0; i--)
    {
        if (s[i] == '\n')
            continue; // don't write newline
        else
            putchar(s[i]);
    }
    putchar('\n');
    return 0;
}

2. Write a program that prompts the user for a sentence, and prints each word on its own line.

Solution

One possible solution could be:

#include <stdio.h>
 
int main(void)
{
    char s[81], word[81];
    int n= 0, idx= 0;
 
    puts("Please write a sentence:");
    fgets(s, 81, stdin);
 
    /* %s matches a sequence of non-whitespace character, which is a
     *    fair definition of "word" in this context.
     * %n matches nothing, but stores the number of characters that have
     *    been processed. i.e. if s is "Hello, World!", then word and n
     *    will be "Hello," and 6 respectively in the first iteration. In
     *    the second iteration they will be "World!" and 7 (6 chars +
     *    the space in front of the word).
     */
    while ( sscanf(&s[idx], "%s%n", word, &n) > 0 )
    {
        idx += n;
        puts(word);
    }
    return 0;
}


[edit] Loops

1. Write a function that outputs a right isosceles triangle of height and width n, so n = 6 would look like

*
**
***
****
*****
******
Solution

One possible solution:

void isosceles(int n)
{
    int x,y;
    for (y= 0; y < n; y++)
    {
        for (x= 0; x <= y; x++)
            putchar('*');
        putchar('\n');
    }
}

2. Write a function that outputs a sideways triangle of height 2n-1 and width n, so the output for n = 4 would be:

*
**
***
****
***
**
*
Solution

One possible solution:

void sideways(int n)
{
    int x,y;
    for (y= 0; y < n; y++)
    {
        for (x= 0; x <= y; x++)
            putchar('*');
        putchar('\n');
    }
    for (y= n-1; y > 0; y--)
    {
        for (x= 0; x < y; x++)
            putchar('*');
        putchar('\n');
    }
}


3. Write a function that outputs a right-side-up triangle of height n and width 2n-1; the output for n = 6 would be:

     *
    ***
   *****
  *******
 *********
***********
Solution

One possible solution:

void right_side_up(int n)
{
    int x,y;
    for (y= 1; y <= n; y++)
    {
        for (x= 0; x < n-y; x++)
            putchar(' ');
        for (x= (n-y); x < (n-y)+(2*y-1); x++)
            putchar('*');
        putchar('\n');
    }
}


[edit] Program Flow

1. Build a program where control passes from main to four different functions with 4 calls.

2. Now make a while loop in main with the function calls inside it. Ask for input at the beginning of the loop. End the while loop if the user hits Q

3. Next add conditionals to call the functions when the user enters numbers, so 1 goes to function1, 2 goes to function 2, etc.

4. Have function 1 call function a, which calls function b, which calls function c

5. Draw out a diagram of program flow, with arrows to indicate where control goes

[edit] Functions

1. Write a function to check if an integer is negative; the declaration should look like bool is_positive(int i);

2. Write a function to raise a floating point number to an integer power, so for example to when you use it

float a = raise_to_power(2, 3); //a gets 8

float b = raise_to_power(9, 2); //b gets 81

float raise_to_power(float f, int power); //make this your declaration

[edit] Math

1. Write a function to calculate if a number is prime. Return 1 if it is prime and 0 if it is not a prime.

Solution

One possible solution using a naïve primality test:

// to compile: gcc -Wall prime.c -lm -o prime
 
#include <math.h>    // for the square root function sqrt()     
#include <stdio.h>
 
int is_prime(int n);
 
int main() 
{
  printf("Write an integer: ");
  int var;
  scanf("%d", &var);
  if (is_prime(var)==1) {
    printf("A prime\n");
  } else {
    printf("Not a prime\n");
  }
  return 1;
}
 
int is_prime(int n)
{
  int x;
  int sq= sqrt(n)+1;
 
  // Checking the trivial cases first
  if ( n < 2 )
    return 0;
  if ( n == 2 || n == 3 )
    return 1;
 
  // Checking if n is divisible by 2 or odd numbers between 3 and the
  // square root of n.
  if ( n % 2 == 0 )
    return 0;
  for (x= 3; x <= sq; x += 2)
    {
      if ( n % x == 0 )
        return 0;
    }
 
  return 1; 
}

2. Write a function to determine the number of prime numbers below n.

3. Write a function to find the square root by using Newton's method.

4. Write functions to evaluate the trigonometric functions:

5. Try to write a random number generator.

6. Write a function to determine the prime number between 2 and 100:

Previous: File IO Index Next: Arrays
Personal tools
Namespaces
Variants
Actions
Navigation
Community
Toolbox
In other languages
Sister projects
Print/export