C Programming/Beginning exercises
From Wikibooks, the open-content textbooks collection
Contents |
[edit] Variables
[edit] Naming
- Can a variable name start with a number?
- Can a variable name start with a typographical symbol (e.g. #, *, _)?
- Give an example of a C variable name that would not work. Why doesn't it work?
- No, the name of a variable must begin with a letter (minuscule or majuscule), or an underscore.
- Only the underscore can be used.
- for example, p$t is not allowed because $ is not a valid character for the name of a variable.
[edit] Data Types
- List at least three data types in C
- On your computer, how much memory does each require?
- Which ones can be used in place of another? Why?
- Are there any limitations on these uses?
- If so, what are they?
- Is it necessary to do anything special to use the alternative?
- Can the name we use for a data type (e.g. 'int', 'float') be used as a variable?
- 3 data types : char, int,double.
- On my computer :
- char : 1 byte
- int : 4 bytes
- double : 8 bytes
- we can not use 'int' or 'float' as a variable 's name.
[edit] Assignment
- How would you assign the value 3.14 to a variable called pi?
- Is it possible to assign an int to a double?
- Is the reverse possible?
double pi; pi=3.14;
- 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
- 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":
- What is the correct statement?
- What is the reverse? Is this a valid C statement (even if it gives incorrect results)?
- 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?
pi2 = pi;- The reverse,
pi = pi2;is a valid C statement ifpiis not a constant. - 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
- scanf() is a very powerful function. Describe some features that make it so versatile.
- Write the scanf() function call that will read into the variable "var":
- a float
- an int
- a double
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.
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.
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
* ** *** **** ***** ******
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:
* ** *** **** *** ** *
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:
*
***
*****
*******
*********
***********
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= 0; x < 2*y-1; x++) putchar('*'); putchar('\n'); } }
[edit] Program Flow
1. Build a program where control passes from main to three different functions with 3 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.
One possible solution using a naïve primality test:
#include <math.h> // for the square root function sqrt() 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.
#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,n;