Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
24 views

Learning C Programming (Basic)

The document provides an introduction to the C programming language. It discusses C program structure and covers topics like variables, expressions, operators, input/output, and data types. Example code and explanations of concepts like comments and header files are also provided.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Learning C Programming (Basic)

The document provides an introduction to the C programming language. It discusses C program structure and covers topics like variables, expressions, operators, input/output, and data types. Example code and explanations of concepts like comments and header files are also provided.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Introduction to the C Programming

Language
Table of Contents

• Introduction
• C Program Structure
• Variables, Expressions, &
Operators
• Input and Output

2
C Programming
Introduction

• Why Learn C?

3
C Programming
Why Learn C?

• Compact, fast, and powerful


• “Mid-level” Language
• Standard for program development (wide acceptance)
• It is everywhere! (portable)
• Supports modular programming style
• Useful for all applications
• C is the native language of UNIX
• Easy to interface with system devices/assembly routines
• C is terse

4
C Programming
C Program Structure

• Canonical First Program


• Header Files
• Names in C
• Comments
• Symbolic Constants

5
C Programming
Canonical First Program

• The following program is written in the C programming language:

#include <stdio.h>
main()
{
/* My first program */
printf("Hello World! \n");
}

• C is case sensitive. All commands in C must be lowercase.


• C has a free-form line structure. End of each statement must be marked
with a semicolon. Multiple statements can be on the same line. White space
is ignored. Statements can continue over many lines.

6
C Programming
Canonical First Program Continued

#include <stdio.h>
main()
{
/* My first program */
printf("Hello World! \n");
}

• The C program starting point is identified by the word main().


• This informs the computer as to where the program actually starts. The
parentheses that follow the keyword main indicate that there are no
arguments supplied to this program (this will be examined later on).
• The two braces, { and }, signify the begin and end segments of the
program. In general, braces are used throughout C to enclose a block of
statements to be treated as a unit. COMMON ERROR: unbalanced
number of open and close curly brackets!

7
C Programming
More on the Canonical First Program

#include <stdio.h>
main()
{
/* My first program */
printf("Hello World! \n");
}

• The purpose of the statement #include <stdio.h> is to allow the


use of the printf statement to provide program output. For each function
built into the language, an associated header file must be included. Text to be
displayed by printf() must be enclosed in double quotes. The program
only has the one printf() statement.
• printf() is actually a function (procedure) in C that is used for printing
variables and text. Where text appears in double quotes "", it is printed
without modification. There are some exceptions however. This has to do with
the \ and % characters. These characters are modifiers, and for the present
the
\ followed by the n character represents a newline character. 8
C Programming
Canonical First Program Output & Comments

• Thus the program prints


Hello World!
• And the cursor is set to the beginning of the next line. As we shall see later on,
what follows the \ character will determine what is printed (i.e., a tab, clear
screen, clear line, etc.)

/* My first program */
• Comments can be inserted into C programs by bracketing text with the /*
and
*/ delimiters. As will be discussed later, comments are useful for a variety of
reasons. Primarily they serve as internal documentation for program
structure and functionality.

9
C Programming
Header Files
• Header files contain definitions of functions and variables which can be
incorporated into any C program by using the pre-processor #include statement.
Standard header files are provided with each compiler, and cover a range of areas:
string handling, mathematics, data conversion, printing and reading of variables,
etc.
• To use any of the standard functions, the appropriate header file should be included.
This is done at the beginning of the C source file. For example, to use the function
printf() in a program, the line
#include <stdio.h>
• should be at the beginning of the source file, because the declaration for printf()
is found in the file stdio.h. All header files have the extension .h and generally
reside in the /usr/include subdirectory.
#include <string.h>
#include <math.h>
#include "mylib.h"
• The use of angle brackets <> informs the compiler to search the compiler’s include
directories for the specified file. The use of the double quotes "" around the
filename informs the compiler to start the search in the current directory for the
specified file. 10
C Programming
Comments

• The addition of comments inside programs is desirable. These may be added


to C programs by enclosing them as follows,
/*
Computational Kernel: In this section of code we implement the
Runge-Kutta algorithm for the numerical solution of the
differential Einstein Equations.
*/

• Note that the /* opens the comment field and the */ closes the comment
field. Comments may span multiple lines. Comments may not be nested
one inside the another.
/* this is a comment. /* this comment is inside */ wrong */
• In the above example, the first occurrence of */ closes the comment
statement for the entire line, meaning that the text wrong is interpreted as a
C statement or variable, and in this example, generates an error.

11
C Programming
Why use comments?

• Documentation of variables and functions and their usage


• Explaining difficult sections of code
• Describes the program, author, date, modification changes, revisions…

Best programmers comment as they write the code, not after the fact.

12
C Programming
Variables, Expressions, and Operators

• Declaring Variables • Advanced Assignment Operators


• Basic Format • Precedence & Associativity of
• Basic Data Types: Integer Operators
• Basic Data Types: Float • Precedence & Associativity of
• Operators Examples
Basic Data Types: Double
• The int Data
• Basic Data Types: Character Type
The float and double
• Expressions and Statements • Data
Types
• Assignment Operator • The char Data
• Assignment Operator Evaluation Type
• ASCII Character Set
Initializing Variables •
• Automatic Type Conversion
Initializing Variables Example • Automatic Type Conversion with
• Arithmetic Operators • Assignment Operator
• Increment/Decrement Operators • Type Casting
• Prefix versus Postfix

13
C Programming
Declaring Variables

• A variable is a named memory location in which data of a certain type can be


stored. The contents of a variable can change, thus the name. User defined
variables must be declared before they can be used in a program. It is during
the declaration phase that the actual memory for the variable is reserved. All
variables in C must be declared before use.
• Get into the habit of declaring variables using lowercase characters.
Remember that C is case sensitive, so even though the two variables
listed below have the same name, they are considered different variables
in C.
sum Sum
• The declaration of variables is done after the opening brace of main().
main() {
int sum;
• It is possible to declare variables elsewhere in a program, but lets start
simply and then get into variations later on.

14
C Programming
Basic Format

• The basic format for declaring variables is

data_type var, var, …;

• where data_type is one of the four basic types, an integer, character,


float, or double type. Examples are

int i,j,k;
float
length,height; char
midinit;

15
C Programming
Basic Data Types: INTEGER

• INTEGER: These are whole numbers, both positive and negative.


Unsigned integers(positive values only) are also supported. In addition,
there are short and long integers. These specialized integer types will be
discussed later.

• The keyword used to define integers is

int

• An example of an integer value is 32. An example of declaring an integer


variable called age is

int age;

16
C Programming
Basic Data Types: FLOAT

• FLOATING POINT: These are numbers which contain fractional parts, both
positive and negative, and can be written in scientific notation.

• The keyword used to define float variables is

float

• Typical floating point values are 1.73 and 1.932e5 (1.932 x 105). An example
of declaring a float variable called x is

float x;

17
C Programming
Basic Data Types: DOUBLE

• DOUBLE: These are floating point numbers, both positive and


negative, which have a higher precision than float variables.

• The keyword used to define double variables is

double

• An example of declaring a double variable called voltage is

double voltage;

18
C Programming
Basic Data Types: CHAR

• CHARACTER: These are single characters.

• The keyword used to define character variables is

char

• Typical character values might be the letter A, the character 5, the symbol “,
etc. An example of declaring a character variable called letter is

char letter;

19
C Programming
Expressions and Statements

• Most expressions have a value based on their contents.

• A statement in C is just an expression terminated with a semicolon. For


example:

sum = x + y + z;
printf("Go
Buckeyes!");

20
C Programming
The Assignment Operator

• In C, the assignment operator is the equal sign = and is used to give a


variable the value of an expression. For example:

i=0;
x=34.8;
sum=a+b;
slope=tan(rise/run)
; midinit='J';
j=j+3;

• When used in this manner, the equal sign should be read as “gets”. Note
that when assigning a character value the character should be enclosed in
single quotes.

21
C Programming
The Assignment Operator Evaluation

• In the assignment statement

a=7;

• two things actually occur. The integer variable a gets the value of 7, and the
expression a=7 evaluates to 7.

22
C Programming
Initializing Variables

• C Variables may be initialized with a value when they are declared. Consider
the following declaration, which declares an integer variable count which
is initialized to 10.

int count = 10;

• In general, the user should not assume that variables are initialized to some
default value “automatically” by the compiler. Programmers must ensure
that variables have proper values before they are used in expressions.

23
C Programming
Initializing Variables Example

• The following example illustrates the two methods for variable


initialization:
#include <stdio.h>
main () {
int sum=33;
float money=44.12;
char letter;
double pressure;
letter='E'; /* assign character value */
printf("value of sum is %d\n",sum);
printf("value of money is %f\n",money);
printf("value of letter is %c\n",letter);
}

• which produces the following output:


value of sum is 33
value of money is 44.119999
value of letter is E

24
C Programming
Arithmetic Operators

• The primary arithmetic operators and their corresponding symbols in C


are:
Negation - Modulus %
Multiplication * Addition +
Division / Subtraction -

• When the / operator is used to perform integer division the resulting


integer is obtained by discarding (or truncating) the fractional part of the
actual floating point value. For example:
1/2 0
3/2 1
• The modulus operator % only works with integer operands. The
expression a%b is read as “a modulus b” and evaluates to the remainder
obtained after dividing a by b. For example
7 % 21
12 % 3 0
25
C Programming
Increment/Decrement Operators

• In C, specialized operators have been set aside for the incrementing and
decrementing of integer variables. The increment and decrement operators
are
++ and -- respectively. These operators allow a form of shorthand in C:
++i; is equivalent to i=i+1;
--i; is equivalent to i=i-1;

• The above example shows the prefix form of the


increment/decrement operators. They can also be used in postfix
form, as follows
i++; is equivalent to i=i+1;
i--; is equivalent to i=i-1;

26
C Programming
Advanced Assignment Operators

• A further example of C shorthand are operators which combine an arithmetic


operation and a assignment together in one form. For example, the following
statement
k=k+5; can be written as k += 5;
• The general syntax is
variable = variable op expression;
• can alternatively be written as
variable op= expression;
• common forms are:
+= -= *= /= %=
• Examples:
j=j*(3+x); j 3+x;
*=
a=a/(s-5); a s-5;
/=
27
C Programming
Precedence & Associativity of Operators

• The precedence of operators determines the order in which operations are


performed in an expression. Operators with higher precedence are employed
first. If two operators in an expression have the same precedence,
associativity determines the direction in which the expression will be
evaluated.

• C has a built-in operator hierarchy to determine the precedence of


operators. Operators higher up in the following diagram have higher
precedence. The associativity is also shown.
- ++ -- R L
* / % L R
+ - L R
= R L

28
C Programming
Precedence & Associativity of Operators Examples

• This is how the following expression is evaluated


1 + 2 * 3 - 4
1 + 6 - 4
7 - 4
3

• The programmer can use parentheses to override the hierarchy and force
a desired order of evaluation. Expressions enclosed in parentheses are
evaluated first. For example:

(1 + 2) * (3 - 4)
3 * -1
-3

29
C Programming
The float and double Data Types

• As with integers the different floating point types available in C correspond


to different ranges of values that can be represented. More importantly,
though, the number of bytes used to represent a real value determines the
precision to which the real value is represented. The more bytes used the
higher the number of decimal places of accuracy in the stored value. The
actual ranges and accuracy are machine-dependent.

• The three C floating point types are:

float
double
long double

• In general, the accuracy of the stored real values increases as you move
down the list.

30
C Programming
The char Data Type

• Variables of type char take up exactly one byte in memory and are used to
store printable and non-printable characters. The ASCII code is used to
associate each character with an integer (see next page). For example the
ASCII code associates the character ‘m’ with the integer 109. Internally, C
treats character variables as integers.

31
C Programming
Automatic Type Conversion with Assignment Operator

• Automatic conversion even takes place if the operator is the assignment


operator. This creates a method of type conversion. For example, if x is
double and i an integer, then

x=i;

• i is promoted to a double and resulting value given to x

• On the other hand say we have the following expression:

i=x;

• A conversion occurs, but result is machine-dependent

32
C Programming
Input and Output

• Basic Output
• printf Function
• Format Specifiers Table
• Common Special Characters for Cursor Control
• Basic Output Examples
• Basic Input
• Basic Input Example

33
C Programming
Basic Output

• Now, let us look more closely at the printf() statement. In a


previous program, we saw this example
print("value of sum is %d\n",sum);
• which produced this output:
value of sum is 33
• The first argument of the printf function is called the control string.
When the printf is executed, it starts printing the text in the control string
until it encounters a % character. The % sign is a special character in C and
marks the beginning of a format specifier. A format specifier controls how
the value of a variable will be displayed on the screen. When a format
specifier is found, printf looks up the next argument (in this case sum),
displays its value and continues on. The d character that follows the %
indicates that a (d)ecimal integer will be displayed. At the end of the control
statement, printf reads the special character \n which indicates print the
new line character.
34
C Programming
printf Function

• General form of printf function

printf(control string,argument list);

• where the control string consists of 1) literal text to be displayed, 2)


format specifiers, and 3)special characters. The arguments can be variables,
constants, expressions, or function calls -- anything that produces a value
which can be displayed. Number of arguments must match the number of
format identifiers. Unpredictable results if argument type does not “match”
the identifier.

35
C Programming
Format Specifiers Table

• The following table show what format specifiers should be used with
what data types:

Specifier Type
%c character
%d decimal integer
%o octal integer (leading 0)
%x hexadecimal integer (leading
%u 0x) unsigned decimal integer
%ld
long int
%f
%lf floating point
%e double or long double
%s exponential floating point
character string 36
C Programming
Common Special Characters for Cursor Control

• Some common special characters for cursor control are:

\n newline
\t tab
\r
carriage return
\f
\v form feed
\b vertical tab
\” backspace
\nnn Double quote (\ acts as an “escape”
mark)
octal character value

37
C Programming
Basic Output Examples

printf(“ABC”); ABC (cursor after the


printf(“%d\n”,5); C)
5 (cursor at start of next
printf(“%c %c %c”,’A’,’B’,’C’); line)
A B C
printf(“From sea ”); From sea to shining C
printf(“to shining “);
printf (“C”);
printf(“From sea \n”); From sea
printf(“to shining \n“); to shining
printf (“C”); C
leg1=200.3; leg2=357.4;
printf(“It was %f It was 557.700012 miles
miles”,leg1+leg2);
num1=10; num2=33;
printf(“%d\t%d\n”,num1,num2); 10 33
big=11e+23;
printf(“%e \n”,big); 1.100000e+24
printf(“%c \n”,’?’); ?
printf(“%d \n”,’?’); 63
printf(“\007 That was a beep\n”); try it yourself 38
C Programming
Basic Input

• There is a function in C which allows the programmer to accept input from


a keyboard. The following program illustrates the use of this function.
#include <stdio.h>
main() {
int pin;
printf("Please type in your PIN\n");
scanf("%d",&pin);
printf("Your access code is %d\n",pin);}
• What happens in this program? An integer called pin is defined. A prompt to
enter in a number is then printed with the first printf statement. The
scanf routine, which accepts the response, has a control string and an
address list. In the control string, the format specifier %d shows what data
type is expected. The &pin argument specifies the memory location of the
variable the input will be placed in. After the scanf routine completes, the
variable pin will be initialized with the input integer. This is confirmed with
the second printf statement. The & character has a very special meaning
in C. It is the address operator. (Much more with & when we get to
pointers…) 39
C Programming
Basic Input Example

#include <stdio.h>
main() {
int pin;
printf("Please type in your PIN\n");
scanf("%d",&pin);
printf("Your access code is %d\n",pin);}

• A session using the above code would look like this


Please type your PIN
4589
Your access code is 4589

• The format identifier used for a specific C data type is the same as for
the printf statement, with one exception. If you are inputting values
for a double variable, use the %lf format identifier.
• White space is skipped over in the input stream (including carriage
return) except for character input. A blank is valid character input.

40
C Programming

You might also like