C Language Elements
CSCI 112: Programming in C
C Language Elements CSCI 112: Programming in C A simple program to - - PowerPoint PPT Presentation
C Language Elements CSCI 112: Programming in C A simple program to convert miles to kilometers Ask the user for a number of miles Convert that number to kilometers Display the result to the user #include <stdio.h> #define
CSCI 112: Programming in C
A simple program to convert miles to kilometers
Ask the user for a number of miles Convert that number to kilometers Display the result to the user
#include <stdio.h> #define KMS_PER_MILE 1.609 int main(void) { double miles, kms; printf("Enter the distance in miles: "); scanf("%lf", &miles); kms = KMS_PER_MILE * miles; printf("That is %f kilometers. \n", kms); return 0; }
These are instructions that are given to the C preprocessor. The preprocessor's job is to modify the text of the C program before it is compiled Preprocessor directives start with the # sign. The two most common ones are:
#include <header file> #define NAME <value
#include <stdio.h> #define KMS_PER_MILE 1.609 int main(void) { double miles, kms; printf("Enter the distance in miles: "); scanf("%lf", &miles); kms = KMS_PER_MILE * miles; printf("That is %f kilometers. \n", kms); return 0; }
This allows the programmer to include definitions from a header file into the current source file. Header files typically end with .h, and contain additional definitions that the program can use When a program contains multiple source files, header files are how a programmer can share functions between files C does not have a lot of functionality directly. Instead, it comes with several 'standard libraries' which may be included in this manner.
For example, we included stdio.h in the miles to kiometers rpgoram
If the name is in quotes, it’s treated as a relative path to that file. If it’s in <>, the preprocessor looks for that file in the system’s C direcotry.
This is a 'constant macro' It instructs the preprocessor to replace every occurrence
NAME is a user-defined identifier
Comments are important, as they help the programmer understand what the code is supposed to be doing. Ignored by preprocessor and compiler. In C, there are two styles
comments and line comments.
A block comment starts with the characters /* and ends with the characters */. A line comment starts with the characters //, and ends at the end of the line.
#include <stdio.h> #define KMS_PER_MILE 1.609 /* * The main function (runs first) */ int main(void) { double miles, kms; printf("Enter the distance in miles: "); scanf("%lf", &miles); // Convert the distance to kilometers kms = KMS_PER_MILE * miles; printf("That is %f kilometers. \n", kms); return 0; }
The entry point into a C program— the first thing t be run. First line declares return type of function, in this case int. Next line indicates function name (main) and parameters (void, indicating no parameters) Between the {} brackets is the function body, containing declarations and executable statements. The final line is the return statement, the value the function gives back to the caller (the
0 indicates success. Any other number indicates some type of error.
#include <stdio.h> #define KMS_PER_MILE 1.609 int main(void) { double miles, kms; printf("Enter the distance in miles: "); scanf("%lf", &miles); kms = KMS_PER_MILE * miles; printf("That is %f kilometers. \n", kms); return 0; }
Some words have special meaning in C, and cannot be used for other purposes. These include
Variable types If/else For/while/do Return sizeof
#include <stdio.h> #define KMS_PER_MILE 1.609 int main(void) { double miles, kms; printf("Enter the distance in miles: "); scanf("%lf", &miles); kms = KMS_PER_MILE * miles; printf("That is %f kilometers. \n", kms); return 0; }
These are words with a special meaning, like reserved words. The difference is that they’re defined in a C standard library. Printf, scanf in our example
#include <stdio.h> #define KMS_PER_MILE 1.609 int main(void) { double miles, kms; printf("Enter the distance in miles: "); scanf("%lf", &miles); kms = KMS_PER_MILE * miles; printf("That is %f kilometers. \n", kms); return 0; }
Programmers choose names of functions, variable and constans An identifier must consist
underscores An identifier cannot begin with a digit A C reserved word cannot be used as an identifier An identifier defined in a C standard library should not be redefined Try to keep identifiers concise and meaningful! All identifiers are CASE SENSITIVE
#include <stdio.h> #define KMS_PER_MILE 1.609 int main(void) { double miles, kms; printf("Enter the distance in miles: "); scanf("%lf", &miles); kms = KMS_PER_MILE * miles; printf("That is %f kilometers. \n", kms); return 0; }
C defines a few different data types, for storing different types of content.
int - whole numbers double – A float with twice the precision char - individual characters (letter, digit, punctuation, etc...) Notice anything missing?
The char data type actually represents characters as integers. The value stored for a certain character depends upon the system your C compiler uses.
The most common version of this system is the ASCII code (American Standard Code for Information Interchange).
The int data type stores integers, but there are a few different qualifiers depending on what range of values need to be stored Why might we want to use long instead of int? Say we need to store positive integers up to 60,000. Which type would be best? Why? C does not guarantee sizes of data types, only inequalities between them: sizeof(short) <= sizeof(int) <= sizeof(long) On modern macOS systems, for example:
A char is 1 byte A short is 2 bytes An int is 4 bytes A long is 8 bytes
Like with the integers, there are various types that can store reals. These numbers are stored in memory in three parts: the exponent, sign and mantissa. The actual value is equal to mantisaa * 2exponent Why we care—for now, because the storage space affects both the range and accuracy of stored numbers
A function consists of variable declarations and executable statements A declaration tells the compiler that a variable exists, and that it needs to set aside memory cells to store it, but it does not initialize it to any value An executable statement performs some sort of computation or action with variables. It’s what gets translated into machine language and run by the CPU.
char myChar;
You use a function call n order to activate a function in C. This is done by simply typing it as an instruction in our program. A function performs some work for you, without you having to know the details of what it is doing. Function name, in this case, printf Function arguments. This includes everything in between the ( ) parenthesis characters. Example: printf
The arguments for printf consist of two main things:
The format string, which starts and ends with the " quote character. The print list, which is a comma-separated list of variable names that app
The format string contains the placeholder %f. When the string is printed to the screen, the value stored in kms will be substituted into that text as it is printed out.ear after the format string. The number of placeholders in the format string should match the number of variables passed to printf in the print list. Placeholders must also match the data type of the variable passed in. Below, %lf is placeholder and kms is the only member of the value list.
printf("That equals %lf kilometers.\n", kms);
printf(”%d, %lf, %f, %c", anInt, aDouble, aFloat, aChar);
Data type..............Placeholder int.......................... %d char....................... %c double................... %lf float....................... %f
The \n character is the 'newline' character. It causes the cursor to move down to the beginning of the next line, similar to how pressing 'enter' in a text editor adds a new line to a text document.
This function copies the data from the standard input device (the keyboard) into the variable(s) specified. The first argument is what input to look for—same as printf The & is the address-of operator: it provides the memory address in which the variable resides.
In this case, the compiler doesn’t care what value is in miles, it needs to know where miles is so that it can place the user input into it. printf("Enter the distance in miles > "); scanf("%lf", &miles);
This function copies the data from the standard input device (the keyboard) into the variable(s) specified. The first argument is what input to look for—same as printf The & is the address-of operator: it provides the memory address in which the variable resides.
In this case, the compiler doesn’t care what value is in miles, it needs to know where miles is so that it can place the user input into it. printf("Enter the distance in miles > "); scanf("%lf", &miles); scanf(”%d_%lf", &miles, &someDouble); Puts first number into miles, second into someDouble. User must enter like “6_4.5”
An assignment statement stores a value or computational result in a variable In C, the = character is the assignment operator.
variable = expression
First, expression is evaluated, then the result is stored in variable. Consider this:
sum = sum + item This says, “take the current value of sum, add the value of item to it, then make that the new value of sum”
Make sure you’re familiar with all of these! What is the final value of result in this code? What is 13 % 6?
int x = 5; int result = x / 4;
Make sure you’re familiar with all of these! What is the final value of result in this code? What is 13 % 6?
int x = 5; int result = x / 4;
Remember how integer division works!
Transform the following expressions into C code. What type will the result be if all input variables are int?
𝑐" − 4𝑏𝑑
' '()*
We can specify how many columns a printed number will take, as well as how many decimal places we want. (Widths include negative signs and decimal points) For numbers of type int:
%<width>d
For numbers of type float/double:
%<width>.<deciamlPlaces>lf
If x is a double containing the value 3.1415926, how do we achieve the following formatted output? (_ represents a blank column)
3.14 3.142 _ _ 3.1
Variables may be converted from one type to another via a cast. For example, this converts a char to an integer with a cast: Note that modern C compilers will do this implicitly, i.e., you can assign a char to an int without specifying the cast.
char myChar = 'A'; int myCharVal = (int)myChar;
Known as bugs Debugging is the process of finding and correcting them Types of errors:
Syntax errors - Error in the formatting of the source file Runtime errors Undetected errors Logic errors