C - Exercise 1

C Programming

Share

In this exercise section of the tutorial we will write some basic C program.

Don't worry if you don't understand the code in one go. We will talk in detail about the program in later part of the tutorial.

1. Write a program in C to print "We are learning C".

This is fairly simple. All we have to do is use the printf() function.

#include <stdio.h>

int main(void)
{
  printf("We are learning C.");
  return 0;
}

2. Write a program in C to print your name

Try this yourself.

3. Write a program in C to add 10 and 20 and print the result.

We will create three integer variables a, b and sum.

We use variable to store value in C.

And since the variables will store integer value so, we will set the date type as int.

Data type of a variable tells us about the type of value stored in the variable.

#include <stdio.h>

int main(void)
{
  int a = 10;
  int b = 20;
  int sum = a + b;
  printf("Sum: %d", sum);
  return 0;
}

Output:

Sum: 30

Explanation

int a = 10;

In the above line we have created variable named a and its type is int which means we can store integer values.

Then we have assigned value 10 using the = assignment operator.

And we have ended the statement using the ; semicolon.

Similarly, we have created another integer variable b and assigned an integer value 20.

int b = 20;

Next we have the third integer variable sum that holds the sum of the two integer value stored in variable a and b. We are adding the value using the + addition operator.

int sum = a + b;

Finally we are printing the result using the printf() function.

printf("Sum: %d", sum);

The %d in the first argument "Sum: %d" of printf() function tells the compiler that the second argument sum is printed as a decimal number.

Share