The char data type, review of the modulus operator

A variable declaration also functions as a definition for the variable, because it causes memory to be allocated to store the variable’s data type, and assigns this memory address a name. When a variable is declared it is assigned what is known as a junk value, which is whatever happened to be there from when the memory address was used last.

#include <stdio.h>

int main(void){
 
  int a;
  int b;
  
  /*
   * output the junk values
   * stored in variables 
   * a and b
   */
  printf("a = %d and b = %d\n", a, b);
  
  
  return 0;
  
}

An assignment statement, as we have seen earlier, takes the value to the right of the equal sign and stores in the variable on the left of the equal sign. The equals sign is thus called the assignment operator because it assign the value on the right to the variable on the left.

Whenever we print the value of a variable using the printf() function, we must provide the printf() function with at least two arguments inside the parenthesis, separated by a comma. The first argument is the control string, because it controls how the other arguments will be presented as output. The control string is a character string enclosed in double quotes. The control string is sometimes also referred to as the format string, since again it formats the output. The second argument is the variable whose value we wish to display.

The control string must have the proper conversion specifier in order to display the variable’s data properly. Note that because conversation specifiers always starting with a % character, if we want to output a % character we must use the sequence %%.

#include <stdio.h>

int main(void){
  
  /*
   * declare a char variable
   * called a
   */
  char a;
  /*
   * declare an int variable
   * called x
   */
  int x;
  
  /*
   * store 'b' in variable
   * a
   */
  a = 't';
  
 /*
  * store 451 in 
  * variable x
  */
  x = 451;
  
  /*
   * display output
   */
  printf("%%c is for chars, %%d is for ints\n");
  printf("a = %c, x = %d\n", a, x);
  
  return 0;
  
}

The char data type is used to store a single character of information. A character, also referred to as a character constant, is a symbol enclosed between two single quotation marks. Care should be taken to ensure that single and not double quotation marks are used. Along with letters, mathematical symbols and numbers can be stored in a char variable as well.

 #include <stdio.h>

int main(void){
  
  char letter1 = 'D';
  char letter2 = 'x';
  
  /*
   * don't confuse the character
   * constants for numbers
   * with their numeric values
   */
  char number1 = '7';
  char number2 = '4';
  
  
  printf("Four char values: %c %c %c %c\n", letter1, number1, letter2, number2);
  
  return 0; 
    

Remember, the division operator always produces an integer result with the operands are of type int. To calculate the remainder, we need to use the modulus operator.

#include <stdio.h>

int main(void){
    
  int apples = 73;
  int students = 31;
  
  
  /*
   * calculate how many apples 
   * are available per student
   */
  int applesPerStudent = apples / students;
  
  /*
   * calculate how many apples are 
   * left over
   */
  int applesLeftOver = apples % students;
  
  printf("We can give %d apples to each student.\n", applesPerStudent);
  Printf("with %d apples left over.\n", applesLeftOver);
  
  
  return 0;
  

So far we have mostly been working with binary operators, so called because they operate on two operands. There are some operators that are unary, meaning that they only use one operand. The unary minus operator is the most familiar of these, it’s simply a minus sign that toggles the value of the operand to its opposite.

 #include <stdio.h>

int main(void){
  
  
  double balance = 49.99;
  
  double book = 11.99;
  double meal = 29.99;
  double shirt = 39.99;
  
  
  printf("Your balance is %f\n", balance);
  
  balance = balance - book;
  
  printf("balance has changed by %f\n", -book);
  
  balance = balance - meal;
  
  printf("balance has changed by %f\n", -meal);
  
  balance = balance - shirt;
  
  printf("balance has changed by %f\n", -shirt);
  
  printf("Your balance is %f\n", balance);
  
  return 0; 
}

The unary minus operator when applied to a variable results in the inversion of the sign of the value stored in the variable; thus, positive becomes negative and negative becomes positive.

Advertisements

More About Variables in C

In C, when one int is divided by another int, the result is also an int. If we divide six by three all’s well, but what if we divide five by three? We find that any fractional part is discarded, this is called truncation.

One answer is to use data types that can handle decimal numbers, we will cover that a little later. In this example program, however, we will use the modulus operator to find the remainder. The modulus operator is specified by the percent sign, %, and using it gives us the remainder of a division operation.

 #include <stdio.h>

int main(void){
 int a = 73;
 int b = 451;

 int answer;

 answer = a + b;
 printf("a + b = %d\n", answer);
 
 answer = a - b;
 printf("a - b = %d\n", answer);
 
 answer = a * b;
 printf("a * b = %d\n", answer);
 
 answer = b / a;
 printf("b / a = %d\n", answer);
 
 /*
  * int data type doesn't handle
  * decimals
  * let's find the remainder
  */
 answer = b % a;
 printf("oh, with a remainder of %d.\n", answer);
 
 
 return 0;
 
 
}

Let’s use the modulus operator to convert a number of inches into yards, feet, and inches.

#include <stdio.h> 


int main(void){
 
 int totalInches, inches, yards, feet;

 totalInches = 150;
 
 inches = totalInches;
 
 yards = inches % 36;
 
 inches = inches % 36;
 
 feet = inches % 12;
 
 feet = inches % 12;
 
 printf("%d inches is %d yards, %d feet and %d inches\n", totalInches, yards, feet, inches);
 
 return 0;
 
 

Having used the int data type quite a bit, it’s time to learn about floating point numbers. Floating point numbers can be either whole or fractional, because they have a fractional portion called the mantissa. They are able to have a fractional portion because they are stored differently in the computer than integers.

We will use the keyword float to declare a variable that will be used to store a floating point value. When we declare a variable as a float, some storage is allocated to store a floating point value that can be referred to using the variable name. We can then use the assignment operator, =, to store a decimal value in that allocated memory space.

When using a float we must use a different conversion specifier in the control string. Instead of embedding an %d, we must instead use a %f.

 #include <stdio.h>

int main(void){
  /*
   * declare a variable called
   * price
   */
  float price = 1.05;
 
  printf("The price is %f\n", price);
 
 
  /*
   * bad things happen
   * when we use the wrong
   * conversion specifier
   */
  printf("not %d\n", price);
 
 return 0;
}

Floating point numbers come in two types, float and double. The double data type has roughly twice the precision as float, but takes up more memory. In terms of calculations, float and double are treated identically, because float variables are automatically converted to double values before they are used in any operation. Note that they both use the same format character, which is %f.

#include <stdio.h>

int main(void){
 
 double x = 2.718;
 double y = 1.618;
 
 double answer;
 
 answer = x + y;
 printf("%f + %f = %f\n", x, y, answer);
 
 answer = x - y;
 printf("%f - %f = %f\n", x, y, answer);
 
 answer = x * y;
 printf("%f - %f = %f\n", x, y, answer);
 
 answer = x / y;
 printf("%f / %f = %f\n", x, y, answer);
 
 
 return 0;
}

 

 

 

 

Introduction to Variables

Variable names are used in a program in much the same way as they are in algebra. The difference is that rather than represent that value itself, a variable in a program represents the memory location where the value is stored.

In C each variable must be declared before being used. The program must therefore contain a statement specifying exactly what kind of information the variable will contain. For example, if we wish to use the variable x to store an integer value, we must declare that x is of the type int. The word int is a keyword in C, keywords must always be typed in lowercase.

Variable names must begin with a letter of the alphabet. No variable name may be a keyword. Variable names are case-sensitive.

We give values to variables using assignment statements. An assignment statement uses the equals sign, which is called the assignment operator, to store a value in the memory of the computer under the symbolic variable name.

#include <stdio.h>

int main(void){

  /*
   * declare a variable
   */
  int x;

  /*
   * assign a value to the variable
   */
  x = 1729;

  /*
   * display the variable using
   * the %d conversion specification
   */
  printf("The Hardy–Ramanujan number is %d.", x);

  return 0; 
}

A conversion specification is a composite symbol that states that a literal or variable value of a specific type is to be inserted at that position. There is a one-to-one correspondence between conversion specifications and the variables associated with them. The conversion specification for an integer value type is %d.

In our next program, the printf() statement contains two conversion specifications within the control string. This is so that we can print out the values stored in the two variables using a single statement. Both variable identifiers must be listed at the end of the printf() statement in the order that they are to be inserted. The variable identifiers must be separated from each other and from the control string by commas.

#include <stdio.h>

int main(void){

  /*
   * declare and initialize variables
   * in one statement
   */
  int minutes = 60;
  int hours = 24;

  /*
   * display values using 
   * multiple conversion specifications
   */
  printf("%d in an hour, %d hours in a day", minutess, hours);

 return 0; 

}

C uses the same arithmetic operators as seen in algebra. These operators are sometimes called binary operators because they operate on two terms or values at a time.

As we have seen earlier, C provides a way to combine a declaration with an assignment. We can even assign the value of an expression to a variable.

#include <stdio.h>

int main(void){
  int speed, time, distance;

  speed = 88;
  time = 3;

  distance = speed * time;

  printf("Traveling at %d MPH for %d hours, ", speed, time);
  printf(" we cover %d miles.\n", distance);

  return 0; 
}

As we have seen above, an expression used in an assignment operation may even contain other variables that have been previously declared and initialized.

More on the main() Function

A function body is enclosed between two curly braces. Every function must have a body, although it can be empty. All code in a C program must be contained within a function. The code in the body of one function is separate from that of other functions.

 

Every C program must have at least one function, and at least one function must be named main(). The main() function may call other functions; in fact, the printf() command we have been using is itself a function. After a function finishes executing, control returns to the function that called it. After the main() function finishes executing, control is returned to the operating system.

#include <stdio.h>

int aFunction(void){/*this is the beginning ofthe function*/
  printf("Vote for Governor Santini!");
  /*
   * return control to the calling function
   */
  return 0;
}/*this is the end of the function*/



int main(void){/*this is the beginning ofthe function*/
    
  /*
   * call aFunction()
   */
  aFunction();
 
 
  /*
   * execution returns to the main() function
   */
  printf("Tuesday is Soylent Green Day.");

  /*
   * return control to the
   * OS
   */
  return 0;
 
}/*this is the end of the function*/

 

Note that all executable statements in C must end with a semicolon, this includes function calls.

First Programs

In this first post we will look at a few very basic programs.

#include <stdio.h>

int main(void){

  /*
   * A very basic program.
   */

  printf("Three pounds of flax.");

  return 0;
}

We should try to get into the habit of documenting our programs with comments. Comments are placed between /* and */, as the compiler will ignore any code following /* until a matching */ is found. Comments can span multiple lines, and can be placed wherever we want.

#include <stdio.h>

int main(void){

 /*
  *print output to stdout
  */ 
 printf("Why is a raven like a writing desk?");

 /*
  * return control to the operating system
  */ 
 return 0;

}

The return statement in the program above returns control to the operating system.

The # symbol in the first line of the program indicates that this line is a preprocessing directive. A preprocessing directive is a special instruction to the compiler to do something before compiling the source code. A very common preprocessing directive is to include a header file; in this example we are including the stdio.h header file. A header file contains a set of code for the program to use There is a standard library of header files that all compilers should have, stdio.h is one of these. All header files in C have the .h file extension.

#include <stdio.h>
/*
 *preprocessor directive
 * /

/*
 * begin the program
 * with the main() function
 */
int main(void){

 /*
  * display output using 
  * printf() function
  */
 printf("Photons be free!");

 /*
  * end execution of the main() function
  */
 return 0; 

}

A function is a named block of code. A function in C is delimited by curly braces. Every C program consists of one or more functions, one of which must be called main(), this is the function that controls the program, and from which other functions are called.

Most functions end with a return statement. A return statement sends a value back to the function that called it. In the case of main(), the function returns 0, this return value indicates that the program terminated normally; a nonzero value returned to the operating system would indicate that there was a problem.