0% found this document useful (0 votes)
29 views

IntroC DataTypesCtrlFlow

This document provides an overview of some basic concepts in ANSI C including data types, control flow statements, functions, operators, and I/O. It discusses primitive data types like int, float, char. It covers basic syntax for input/output, if/else statements, for/while loops, and switch statements. It also provides examples of printing output, getting input, and defining functions. The document describes proper use and common mistakes to avoid for control structures.

Uploaded by

Rhad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

IntroC DataTypesCtrlFlow

This document provides an overview of some basic concepts in ANSI C including data types, control flow statements, functions, operators, and I/O. It discusses primitive data types like int, float, char. It covers basic syntax for input/output, if/else statements, for/while loops, and switch statements. It also provides examples of printing output, getting input, and defining functions. The document describes proper use and common mistakes to avoid for control structures.

Uploaded by

Rhad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

ANSI C Data Types & Basic Control Flow

Adapted from Ray Klefstad

an general purpose programming language


major features include:
thin veneer over assembly language
allows machine access (pointers, addresses, register, assembly)
simple (relatively)
Language Reference: http://en.cppreference.com/w/c

Simple Input and Output


#include <stdio.h>
int main()
{
int i = 40;
printf("Enter a number:\n");
scanf_s("%d", &i);
printf("I is %d\n", i);
return 0;
}

#include brings in declarations


& in front of i gives its address so scanf_s can modify i

I/O

The main function


Every ANSI C program must have one function named main
when you run your program, main is called (on writing main)
#include <stdio.h>

int main() // int is the exit status for main


{
printf("Hello Everyone!\n");
return 0; // 0 means program terminated ok
}

Primitive Data Types


foundational types are built-in or pre-defined
every data type has a size (in bytes) and a range of values
includes integral, floating point, character and character string types

The Integral Types


correspond to whole integers
kinds of integral types:
char, 1 byte, -128 through 127
short, 2 bytes, -32768 through 32767
int, machine word size, now 32 bits

long, 4 bytes, -2147483648 through 2147483647


also unsigned versions of all
example literals
0
1
-1
-1234567
11 // decimal 11
011 // octal 9
0x11 // hex 17

The Floating Point Types

corresponds to floating point real numbers


three kinds of floating point types:
float (usually 4 bytes)
double (usually 8 bytes)
long double (usually 8 bytes)
example literals
1.0
-3.000001e-10
30.01E40

The Character Type

represents an ASCII character code


requires one byte
range of values
0 to 255

example literals
'\0' null character 0
'\n' newline (or linefeed) 10
'\r' return 13
'\t' tab 9
' ' space 32
'0' 48
'A' 65
'a' 97

variables must be declared before they are used


variable declaration with initialization
int numberOfStudents = 30;
int automobileVelocity = 0;

assignment operator changes the value in a variable


numberOfStudents = 0; // got rid of all the students
automobileVelocity += 20; // accelerated the auto

Variables

Symbolic Constants

constants have a fixed value


#define PI 3.1415926536
#define NEWLINE '\n'

it is good style to name literal constants


return 3.14159*r*r;
return PI*r*r;

Simple Operators

Numeric Operators
+, -, *, /, %, unary +, Assignment Operators (modifies state of object)
=, +=, -=, *=, /=, %=, ++, -velocity = ( acceleration * time * time ) / 2.0;

Using Operators Properly


precedence
associativity
parenthesis may over-ride
memorize these operators, precedence, and associativity
from highest to lowest
++ -- (unary) + */%
+ = += -= *= /= %=

Statements
Declaration Statements
introduces a new variable
variable is in scope to the end of enclosing block
int main()
{
double d = 2 * PI;
printf("%f\n", d);
return 0;
}

Expression Statements
any expression may be used as a statement
the value is discarded
int main()
{
double PI = 3.14159;
double d = 2.0 * PI;

printf("f\n", d);
d = d / 2.0;
square( 2.0 ); // be careful of this mistake
printf("%f\n", d);
return 0;
}

Output
output is done via printf function
EG
int main()
{
printf("Hello");
printf("%d", 10 * 10);
printf("%c", 'A');
printf("%f", 3.14159);
...
}

Input
input is done via scanf function
uses address of parameter to modify its value
it waits for a value to be entered (may require a return/enter)
EG
int main()
{
int i;
double d;
char c;
scanf(%d, &i); // reads string of digits as integer
scanf(%f, &d); // reads digits, decimal as a real number
scanf(%c, &c); // reads a single character
...
}

Other Statements
if, switch, while, for, return, break
you can declare local variables in loops
int main()
{
for ( int i=0; i<10; ++i )
printf(%d\n, i);
for ( int i=10; i>=0; --i )
printf("%d\n", i);
return 0;
}

The if Statement

conditional execution of a statement


int main()
{
int a = 1;
int b = 2;
if ( a < b )
printf("a < b\n");
else if ( a > b )
printf("a > b\n");
else
printf("a == b\n");
if ( a > 0 )
printf("a is positive\n");
}

else's match nearest unmatched if


indentation is not considered (be careful!)
int maxOfThree( int a, int b, int c )
{
if ( a < b )
if ( b < c )
return c;
else
return b;
else if ( a < c )
return c;
else
return a;
}

a syntax error that changes meaning of if statement


if ( e ); // extra semicoln means empty statements
printf("Hello\n"); // prints "Hello" even if e is false

an awkward use of if statement


if ( e )
; // nothing
else
printf("Hello\n");

natural, but very harmful, mistake


int a = 0;
if ( a = 0 )
printf("Hello\n"); // never happens! Why?

Nesting if Statements

if Statement Caveats

another awkward use of if statement


if ( a < b )
return true;
else
return false;
better to say

return a < b;

The Concept of Iteration


also called `looping'
allows repeating a similar action several times
the break statement will exit any loop
the return statement will also exit the loop

The for Statement

the most common loop statement


Natural for initializing, testing, then advancing
abstract examples
for ( each student, s, in this class )
assignGradeTo( s );
for ( each day, d, of the quarter )
studyHardOnDay( d );
for (each station, s, on the radio tuner )
{
tuneTo( radio, s );
if ( youLikeTheSong( listen( radio ) )
break; /// terminates this for loop
}
for ( each integer, i, in the range 0 to 9 )
printf("%d\n", i);

real examples
// print out numbers 0 through 9
for (int i = 0;i < 10; ++i)
printf("%d\n", i);
// read 10 integers from the input and print the sum
int main()
{
int valueRead = 0;
int sumTotal = 0;
for ( int i = 0; i < 10; i++ )
{
scanf("%d", &valueRead);
sumTotal += valueRead;
}
printf("The total is: %d\n", sumTotal);
}

The while Statement

Natural for testing BEFORE doing an action that involves repetition


EG
while ( isTooSour( coolade ) )
addATeaspoonOfSugar( coolade );
while ( waterIsTooCold( bathtub ) )
addAGallonOfHotWater( bathtub );
while ( ! understandTheHomeworkAssignment( student ) )
{
readTheHomeworkHandout( student );
askQuestions( student, TA );
}
while ( isStillAwake( student ) )
study( student );

Natural for doing an action then testing for completion before repetition
EG
do
turnIgnition( car );
while ( ! started( car ) );
do
pressANumber( phone );
while ( ! haveAConnection( phone ) );
do
{
readTheHomeworkHandout( student );
askSomeQuestions( student, TA );
} while ( ! understands( student, materialForWeek( w ) ) );
do
eat( person, pintOfIceCream );
while ( !sick( person ) );

The do-while Statement

Nested loops
EG // print out a calendar
#define JAN 1
#define DEC 12
int days_per_month[]={0,31,29,31,30,31,30,31,31,30,31,30,31};

int main()
{
for ( int y = 2015; y <= 2020; y++ )
for ( int m = JAN; m <= DEC; m++ )
{
for ( int d = 1; d <= days_per_month[m]; d++ )
printf( "%d / %d / %d ", m, d, y );
printf("\n");

}
}

Loop Caveats

loop control variable is only in scope over loop body


for (int i = 0; i < 10; i++ )
printf( "%d ", i );
printf( "%d\n", i ); /// i is no longer in scope

some errors may cause an infinite loop


for (int i = 0; i < 10; i+1 ) /// i+1 is not advancing
printf( "%d ", i );
...
int i; /// may forget to initialize
while ( i < 10 )
printf( "%d ", i ); /// not advancing!

some errors may cause wrong values for i or incorrect number of loops
for (int i = 0; i <= 10; i++ ) /// wrong < operator
printf("%d ", i);
...
for (int i = 1; i < 10; i++ ) /// wrong initial value
printf("%d ", i);

for selecting among a set of integral values


int main()
{
int i = getIntegerFromUser();
printf("Some stuff here\n");
switch ( i )
{
case 1:
case 3:
case 5:
case 7:
case 9:
printf("%d is odd\n", i);
break;
case 0:
case 2:
case 4:
case 6:
case 8:
printf("%d is even\n", i);
break;

The switch Statement

default:
printf("%d isn't in range 0 to 9\n", i);
break;
}
printf("Some more stuff here\n");
}

Another switch Statement Example

break isn't required with return


bool isDigit( char c )
{
switch ( c )
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return true;
default:
return false;
}
}

forgetting the break!


int main()
{
int score = getScoreFromUser();
char grade = computeStudentsGrade( score );
switch ( grade )
{
case 'A':
printf("Excellent!\n");
case 'B':
printf("Good.\n");
case 'C':
printf("Fair - just passed.\n");
case 'D':
printf("Poor - See you next quarter.\n");
case 'F':
printf("Failed - off to McDonalds.\n");

switch Statement Caveats

default:
printf("Invalid Grade %d\n", grade);
}
}

Another switch Statement Caveat

There are no ranges for integral values


bool isDigit(char c)
{
switch ( c )
{
case '0'-'9': // will subtract '9' from '0'
return true;
default:
return false;
}
}

Must be listed separately


bool isDigit(char c)
{
switch ( c )
{
case '0':
case '1':
case '2':
/// do something here
default:
return false;
}
}

You might also like