e102f23Lecture02
e102f23Lecture02
Electromechanical Systems
Engineering Programming in C
Lecture 02
Fall 2023
1
Your first C program
#include <stdio.h> #include <stdio.h>
void main(void) int main() {
{ printf("Hello, world!\n");
printf(“Hello, world!\n”); return (0); }
}
#include <stdio.h>
#include <stdio.h> int main() {
void main(void) {
Which one is best? printf("Hello, world!\n");
printf(“Hello, “); }
printf(“world!”); #include <stdio.h>
printf(“\n”); } int main(void) {
I like this one
printf("Hello, world!\n");
getchar();
return 0; }
Reminder There are a lot of different ways to solve the same problem.
TO-DO: Experiment with leaving out parts of the program, to see what error
messages you get.
C compilation model… hello.c to hello
hello.c Type in program using an editor of
%gcc -o hello hello.c your choice (file.c); plain text
Java programmers may recognize the main() method but note that it is not embedded
within a class. C does not have classes. All methods (simply known as functions) are
written at file scope.
The main() method in Java has the prototype ‘main(String[] args)’ which provides the
program with an array of strings containing the command-line parameters. In C, an array
does not know its own length so an extra parameter (argc) is present to indicate the
number of entries in the argv array.
Your first C program (cont)
What is going on?
#include <stdio.h> - Tells the compiler to include this header
file for compilation. To access the standard functions that
comes with your compiler, you need to include a header with
the #include directive.
What is a header file? They contain prototypes and other
compiler/pre-processor directives. Prototypes are basic abstract
function definitions. More on these later...
Some common header files are stdio.h, stdlib.h, unistd.h, math.h.
Something is still a little fishy... I thought that 0 implied false (which it does)... so
isn't it returning that an int signifying a bad result? Thankfully there is a simple
solution to this. Let's add #include <stdlib.h> to our includes. Let's change our
return statement to return EXIT_SUCCESS;. Now it makes sense!
Let's take a look at printf. Hmm... I wonder what the prototype for printf is. (BTW,
what’s a prototype?) Utilizing the man pages we see that printf is: int printf(const
char *format, ...); printf returns an int. The man pages say that printf returns the
number of characters printed. Now you wonder, who cares? Why should you
care about this? It is good programming practice to ALWAYS check for return
values. It will not only make your program more readable, but in the end it will
make your programs less error prone. But in this particular case, we don't really
need it. So we cast the function's return to (void). fprintf, fflush, and exit are the
only functions where you should do this. More on this later when we get to I/O.
For now, let's just void the return value.
What about documentation? We should probably doc some of our code so that
other people can understand what we are doing. Comments in the C89 standard
are noted by: /* */. The comment begins with /* and ends with */.
Your first C program…
New and Improved?
#include <stdio.h>
#include <stdlib.h> // We don’t need this yet
/* Main Function
* Purpose: Controls program, prints Hello, World!
* Input: None
* Output: Returns Exit Status
*/
int main() {
printf("Hello, world!\n");
return EXIT_SUCCESS; // Don’t need this either
}
Much better! The KEY POINT of this whole introduction is to show you the fundamental
difference between correctness and understandability. All of the sample codes produce the exact
same output in "Hello, world!" However, only the latter example shows better readability in the
code leading to code that is understandable. All codes will have bugs. If you sacrifice code
readability with reduced (or no) comments and cryptic lines, the burden is shifted and magnified
when your code needs to be maintained.
Overview of C
Basic Data Types
Constants
Variables
Identifiers
Keywords
Basic I/O
NOTE: There are six classes of tokens: identifiers, keywords, constants, string
literals, operators, and other separators. Blanks, horizontal and vertical tabs,
newlines, form feeds and comments (collectively, ‘‘white space’’) are ignored except
as they separate tokens. Some white space is required to separate otherwise
adjacent identifiers, keywords, and constants
Basic Data Types
Integer Types
Char – smallest addressable unit; each byte has its own address
Short – not used so much
Int – default type for an integer constant value
Long – do you really need it?
Floating point Types – are “inexact”
Float – single precision (about 6 digits of precision)
Double – double precision (about 15 digits of precision)
constant default unless suffixed with ‘f’
Derived types
Beside the basic types, there is a conceptually infinite
class of derived types constructed from the
fundamental types in the following ways:
arrays of objects of a given type;
functions returning objects of a given type;
pointers to objects of a given type;
structures containing a sequence of objects of various
types;
unions capable of containing any of one of several objects
of various types.
In general these methods of constructing objects can
be applied recursively
An array of pointers
An array of characters (i.e. a string)
Structures that contain pointers
Constants
\a alert(bell)character \\ backslash
Special characters \b backspace \? questionmark
Not convenient to type on \f formfeed \’ singlequote
a keyboard
\n newline \" doublequote
Use single quotes i.e. ‘\n’ \r carriagereturn \ooo octalnumber
Looks like two characters \t horizontaltab \xhh hexadecimalnumber
but is really only one
\v verticaltab
Format Descriptors for
scanf and printf
• The symbol % is a format descriptor where
%d decimal integer
%6d decimal integer at least 6 characters wide
%f floating point
%f floating point at least 6 characters wide
%.2f floating point 2 characters after decimal
%6.2f floating point at least 6 wide and 2 after decimal point
%c character
%s string of characters (we will work with this later)
• Other useful escape sequences:
\n new line or carriage return
\t tab
Two Common Variable Types
#include <stdio.h>
#include <limits.h>
int main()
{
printf("Storage size for int : %d \n", sizeof(int));
}
When you compile and execute the above program, it produces the following result in
Linux
Storage size for int : 4
Floating Point Type Variables
Type Storage size Value range Precision
1.2E-38 to
float 4 byte 6 decimal places
3.4E+38
2.3E-308 to
double 8 byte 15 decimal places
1.7E+308
3.4E-4932 to
long double 10 byte 19 decimal places
1.1E+4932
The header file float.h defines macros that allow you to use these values and
other details about the binary representation of real numbers in your programs.
The following example prints the storage space taken by a float type and its
range values
#include <stdio.h>
#include <float.h>
int main() {
printf("Storage size for float : %d \n", sizeof(float));
printf("Minimum float positive value: %E\n", FLT_MIN );
printf("Maximum float positive value: %E\n", FLT_MAX );
printf("Precision value: %d\n", FLT_DIG );
}
When you compile and execute the above program,
it produces the following result on Linux −
A variable
Allows access and information about what is in
memory i.e. a storage location
A symbolic name (an identifier) that is associated
with a value and whose associated value may be
changed
The usual way to reference a stored value
Identifier Naming Style
Rules for identifiers
a-z, A-Z, 0-9, and _
Case sensitive
The first character must be a letter or _
Keywords are reserved words, and may not be used as
identifiers
Sample Identifiers
i0, j1, abc, stu_score, __st__, data_t, MAXOF, MINOF ...
Keywords