Variables (C)

C Programming Getting Started certificate

Following on from https://geektechstuff.com/2019/02/25/hello-world-c/, I have continued to work on learning C by enrolling on the EdX course “C Programming: Getting Started” in conjunction with Dartmouth and IMT.

The syllabus for C Programming: Getting Started includes:

  • Define, distinguish and give examples of hardware/software, computer programs/algorithms
  • Explain the concept of a variable and declare, initialise and modify variables of data types int, double and character
  • Create and comment simple C-programs that may print text, special characters and variables to the screen with controlled formatting
  • Create simple C-programs that utilise for-loops to repeat blocks of instructions

 

I’m proud to announce I’ve earned a passing grade (I like courses that include exams and programming challenges) in the course.

I’m using this post to help remind myself of using variables within C.

Variables in C must be declared before use, and unlike in Python, C must be told what type of data the variable holds (e.g. character, integer or decimal). When storing data in a variable an ampersand (&) is placed in front of the variable name.

printf(“”)

printf prints characters, numbers or variables.

scanf(“”)

scanf reads characters or numbers from user input.

Integers

keyword int and %d is for integers

Example:

int my_number = 42;

printf(“The number %d is import in HitchHikers Guide To The Galaxy”, my_number)

Would print “The number 42vis import in HitchHikers Guide To The Galaxy”.

in my_number =””;

scanf(“%d”,&my_number);

Would take an integer from input and then store it in the variable my_number.

Characters

keyword char and %c is for characters

Example:

char my_word=”programming”;

printf(“I enjoy learning %c”,my_word);

Would print “I enjoy learning programming“.

char fav_letter = “”;

scanf(“%c”;&fav_letter);

Would take a character from input and store it in the variable fav_letter.

Decimals (Floating Point Numbers)

keyword double and %lf is for decimals

%.2lf is for 2 decimal places.

Example:

double pi = 3.14;

printf(“Pi can be rounded to %lf”,pi);

Would print “Pi can be rounded to 3.14“.

double floating_number = “”;

scanf(“%lf”,&floating_number);

Would take a character from input and store it in the variable floating_number.

 

One thought on “Variables (C)

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.