Introduction to C Programming

42
Introduction to C Programming

description

Introduction to C Programming. Microprocessors. Electronic brain which can perform computations It’s a brain without a mind (intelligence), you have provide it its intelligence in the form of instructions Those instructions are called programs/code - PowerPoint PPT Presentation

Transcript of Introduction to C Programming

Page 1: Introduction  to  C Programming

Introduction to C Programming

Page 2: Introduction  to  C Programming

Microprocessors

¨ Electronic brain which can perform computations

¨ It’s a brain without a mind (intelligence), you have provide it its intelligence in the form of instructions

¨ Those instructions are called programs/code¨ Most basic form of coding utilizes Machine

language or assembly code

Page 3: Introduction  to  C Programming

High-level view of programming¨ The file with instructions that comprise a

program is called you source code¨ What this file looks like depends on the choice

of programming language.¨ As long as you follow syntax rules for chosen

language, your source code file is valid.¨ For this project, we will start with a powerful

and well known language called C.

Page 4: Introduction  to  C Programming

High-level view of programming

¨ Compile the source code.– Compilation is the process of converting the source

code into machine language – the very minimalist language that is spoken directly by the machine in use.

– Note: It is possible to program directly in machine language, but it is tedious, ugly, and error-prone.

¨ Run or execute the machine-language file.– The compiler converts source code into a machine

language file which is stored on the microprocessor and executed.

Page 5: Introduction  to  C Programming

First C Program

Page 6: Introduction  to  C Programming

A Simple C Program

¨ Comments– Text surrounded by /* and */ is ignored by computer– Used to describe program

¨ #include <LABX-2.h>– Preprocessor directive

• Tells computer to load contents of a certain file (header files)

– <LABX-2.h> allows standard input/output operations

1 /* Fig. 2.1: fig02_01.c2 A first program in C */3 #include <LABX-2.h>45 void main()6 {7 fprintf(RS232, "Welcome to C!\n" );89 }

Welcome to C!

Page 7: Introduction  to  C Programming

A Simple C Program, Cont.

¨ void main()– C programs contain one or more functions,

exactly one of which must be main– Parenthesis used to indicate a function– Braces ({ and }) indicate a block

• The bodies of all functions must be contained in braces

– All statements must end with a semicolon ( ; )

Page 8: Introduction  to  C Programming

C Data Types

Page 9: Introduction  to  C Programming

What do program instructions look like?

¨ A simple program has at least these three main parts– variable declaration– variable initialization– main body

Page 10: Introduction  to  C Programming

Constants

¨ Constants are declared once and do NOT change

¨ Syntax #define PI = 3.1416– Do NOT use a semicolon for #define)– Declare constants before the main() function

Page 11: Introduction  to  C Programming

Variables in Programming¨ Represent storage units in a program¨ Used to store/retrieve data over life of program¨ Type of variable determines what can be placed in

the storage unit¨ Assignment – process of placing a particular value

in a variable¨ Variables must be declared before they are

assigned¨ The value of a variable can change; A constant

always has the same value

Page 12: Introduction  to  C Programming

Naming variables¨ When a variable is declared it is given a name

¨ Good programming practices– Choose a name that reflects the role of the variable in a

program, e.g.• Good: name, ssn;• Bad : n, no;

¨ Restrictions– Name must begin with a letter; otherwise, can contain

digits or any other characters. C is CASE SENSITIVE!– Ab is not the same as ab

Page 13: Introduction  to  C Programming

Basic C variable types¨ There are three basic data types in C:

– char• A single byte capable of holding one character in the

local character set. [Ex: a A b B + & …]

– int• An integer of unspecified size [Ex: 17, -99]

– float• Single-precision floating point [Ex: 7.4, -35.63,

2.001]

– The range of these data types is limited but it can be extended by adding 8, 16 or 32 at the end like float32 or int16 etc.

Page 14: Introduction  to  C Programming

Variable Declaration¨ All variables must be declared in a C program

before the first executable statement involving the variables! Examples:

main()

{

int a, b;

float c;

/* Do something here */

a=5; b=19;

c=(a+b)/10;

}

Page 15: Introduction  to  C Programming

Declaring variables

¨ All variables must always be declared before the first executable instruction

¨ Variable declarations are always: – var_type var_name;

• int age;• float cost_of_soda;• char your_name, my_name; /* multiple variables are ok */

¨ In most cases, variables have no meaningful value at this stage. Memory is set aside for them, but they are not meaningful until assigned.

Page 16: Introduction  to  C Programming

Variable assignment

¨ After variables are declared, they should be given values. This is called assignment and it is done with the ‘=‘ operator. Examples:float a, b;

float c;

b = 212;

c = 200;

a=b+c; (a is now equal to 412)

Page 17: Introduction  to  C Programming

Assigning values to Variables

¨ Either when they are declared, or at any subsequent time, variables are assigned values using the “=“ operator.

¨ Examples

int age = 52; //joint declaration/assignment

double salary;

salary = 150000.23;

age = 53; //value may change at any time

Page 18: Introduction  to  C Programming

Assignment, cont.¨ Be careful to assign proper type – contract

between declaration and assignments must be honored– int x=2.13 (not allowed since 2.13 is NOT and int)– double x = 3; (ok because 3 = 3.0)– char c = 300; (NOT ok because 300 is not a char)

Page 19: Introduction  to  C Programming

Arrays¨ Arrays are multiple variables of the same type

grouped together– int x[10] (10 integers grouped together called “x”)– char name[20] (20 characters called “name”)

¨ Declare variables the same way as before, just add [ ] at the end with the number of variables you want in the array

¨ Example– char c, my_name[6] = “Daniel”;– c = my_name[3]; (c = ‘i’, count up from 0)

Example # 2; int i = 4;c = my_name[i]; (c = ‘e’ since i=4)

Page 20: Introduction  to  C Programming

Input/Output

Page 21: Introduction  to  C Programming

The printf Executable Statement

¨ The only executable statements we’ve seen to this point are

– Assignments– The printf and gets functions– Assignment expressions with simple operators (+, -)

¨ Very hard to write any program without being able to print output. Must look at printf in more detail to start writing useful code.

Page 22: Introduction  to  C Programming

printf(), cont.

¨ Sends output to standard out, which for now we can think of as the terminal screen.

¨ General formprintf(format descriptor, var1, var2, …);

¨ format descriptor is composed of– Ordinary characters

• copied directly to output

– Conversion specification• Causes conversion and printing of next argument to printf• Each conversion specification begins with %

Page 23: Introduction  to  C Programming

printf() examples¨ Easiest to start with some examples

– printf( “hello world”);• Output: hello world • as a string

– printf(“j=%d, k=%d”, j, k);• If j=10 and k=99• Output: j=10, k=99• the value of the variable j as an integer followed by

the value of the variable k.– printf(“The sum (j + k) =\n%d”, j+k);

• Output: The sum (j + k) =

109• \n for new line.

Page 24: Introduction  to  C Programming

More on format statements¨ The format specifier in its simplest form is one of:

– %s • sequence of characters known as a String• Not a fundamental datatype in C (really an array of char)

– %d• Decimal integer (i.e. base ten)

– %f• Floating point

¨ Note that there are many other options. These are the most common, though, and are more than enough to get started.

Page 25: Introduction  to  C Programming

Invisible characters

¨ Some special characters are not visible directly in the output stream. These all begin with an escape character (i.e. \);– \n newline– \r carriage return (back to the start of line)– \t horizontal tab– \a alert bell– \v vertical tab

Page 26: Introduction  to  C Programming

Getchar/putchar example/* uses getchar with while to echo user input */

#include<stdio.h>

int main(){

int c; /* holds the input character value */

c = getchar(); /* reads first character from input stream

with keyboard, this is signaled by Enter key*/

while (1){ /* loop forever */

putchar(c); /* write char to keyboard */

c = getchar(); /*get next char in stream */

}

}

Page 27: Introduction  to  C Programming

Gets/puts example¨ Works like getc/putc but for entire strings [arrays] of characters

¨ Gets will capture a sting of characters until it detects a “null” character, also known as the “enter” key

¨ Puts will output a string of text that is terminated with a “null” character

Page 28: Introduction  to  C Programming

Second C Program

User variables, reading user input

Page 29: Introduction  to  C Programming

1 /* Profram2.c

2 #include <stdio.h>

3 #include <labx2.h> /*Circuit board specific header file

4

5 int main()

6 {

7 char name[20]; /* declaration */

8

9 printf( “Hello\n" ); /* prompt */

10 printf( “What is your name?\n" ); /* prompt */scanf( "%d", &integer1 ); /* read an integer */11 gets(name);

12 printf( “\n %s, Welcome to the world of microprocessors“, name); /* prompt *//* read an integer */13 return 0; /* indicate that program ended successfully */

14 }

HelloWhat is your name?SamSam, Welcome to the world of microprocessors

Page 30: Introduction  to  C Programming

Math Operations

Page 31: Introduction  to  C Programming

Arithmetic Operations¨ Five simple binary arithmetic operators

1. + “plus” c = a + b2. - “minus” c = a - b3. * “times” c = a * b4. / “divided by” c = a/b5. % “modulus” c = a % b

1. What are the values of c in each case above if– int a = 10, b = 2;– float a = 10, b = 2;– int a = 10; float b = 2; ??

Page 32: Introduction  to  C Programming

Relational Operators¨ Four basic operators for comparison of values in

C. These are typically called relational operators:

1. > “greater than”2. < “less than”3. >= “greater than or equal to”4. <= “less than or equal to”

1. For the declaration int a=1,b=2,c; what is the value of the following expressions?

a > b; a<b; a>=b;a<=b

Page 33: Introduction  to  C Programming

Relational Operators, cont.¨ Typically used with conditional expressions, e.g.

– if (a < 1) then … ¨ However, also completely valid expressions which

evaluate to a result – either 1 (true) or 0 (false). int c, a=2, b=1; c = (a > b)What is the value of c?

¨ Note: We’ll talk about order of precedence for multipart expressions a little later. For now, we force an order using parentheses.

Page 34: Introduction  to  C Programming

Equality Operators

¨ C distinguished between relational and equality operators.

¨ This is mainly to clarify rules of order of precedence.

¨ Two equality operators1. == “is equal to”

2. != “is not equal to”¨ These follow all of the same rules for relational

operators described on the previous slide.

Page 35: Introduction  to  C Programming

Logical Operators

¨ Logical Operators are used to create compound expressions

¨ There are two logical operators in C1. || “logical or”

¨ A compound expression formed with || evaluates to 1 (true) if any one of its components is true

2. && “logical and”¨ A compound expression formed with &&

evaluates to true if all of its components are true

Page 36: Introduction  to  C Programming

Logical Operators, cont.

¨ Logical operators, like relational operators, are typically used in conditional expressions

1. if ( (a == 1) && (b < 3) || (c == 1) ) etc.¨ Also works with characters

char x=‘A’, y = ‘G’, C = ‘A’If(x == C)y=‘C’;Printf(%c,y); //what is printed ?

Page 37: Introduction  to  C Programming

Converting String to integer

¨ An important function when using argv/argc is atoi.

¨ atoi converts a String argument to an integer in the following way:int input, output;

input = atoi(argv[1]);

output = input + 1;

printf("%d\n", output);

> a.out 333

334

Page 38: Introduction  to  C Programming

Reading single characters

¨ Another important pair of functions for keyboard input/output is getchar/putchar

¨ getchar reads a single character from the input stream; putchar write a single character to the standard out for example: int c;

c = getchar(); /* blocks until data is entered

if more than one char is entered only first is read */

putchar(c); /* prints value of c to screen */

Page 39: Introduction  to  C Programming

While loops¨ A simple technique for repeating a statement or

group of statements until some specified condition is met

¨ General form:while (expr){ statement1; statement2; . . }

¨ If expr evaluates to true (ie not 0), then perform statement1, etc. Otherwise, skip to end of while block.

¨ Repeat until expr evaluates to false (ie 0).

Page 40: Introduction  to  C Programming

FOR Loops

¨ Syntax:

for (initialize; test; change)

{ stuff }¨ Example

– for(i=0; i<100; i=i+1) – { printf(“i is now = %u \r\n”, i); }– will print out 1 through 99, each number on a

new line

Page 41: Introduction  to  C Programming

While example

¨ Syntax:

while (test)

{ stuff }¨ Example Note: != means not equal

– While(getc() != ‘X’)– { printf(“Still running.. /r/n”,); }– will print Still running… on a new line until

the user enters X on the keyboard

Page 42: Introduction  to  C Programming

If example

¨ Syntax:

if (test)

{ stuff }¨ Example

– if(X < 100)– { printf(“X is less that 100 /r/n”); }– will print X is less than 100 unless X is

greater than or equal to 100