1.c program print string
C programming code
#include<stdio.h>
int main()
{
char array[20] = "Hello World";
printf("%s\n",array);
return 0;
}
To input a string we use scanf function.
C programming code
#include<stdio.h>
int main()
{
char array[100];
printf("Enter a string\n");
scanf("%s",&array);
printf("You entered the string %s\n",array);
return 0;
}
Note that scanf can only input single word strings, to receive strings containing spaces use gets function.
2.c program to add two numbers
C programming code
#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter two numbers to add\n");
scanf("%d%d",&a,&b);
c = a + b;
printf("Sum of entered numbers = %d\n",c);
return 0;
}
Add numbers program executable.
Output of program
Addition without using third variable
#include<stdio.h>
int main()
{
int a = 1, b = 2;
/* Storing result of addition in variable a */
a = a + b;
/* Not recommended because original value of a is lost
* and you may be using it some where in code considering it
* as it was entered by the user.
*/
printf("Sum of a and b = %d\n", a);
return 0;
}
C program to add two numbers repeatedly
#include<stdio.h>
int main()
{
int a, b, c;
char ch;
while(1)
{
printf("Enter values of a and b\n");
scanf("%d%d",&a,&b);
c = a + b;
printf("a + b = %d\n", c);
printf("Do you wish to add more numbers(y/n)\n");
scanf(" %c",&ch);
if ( ch == 'y' || ch == 'Y' )
continue;
else
break;
}
return 0;
}
Adding numbers in c using function
We have used long data type as it can handle large numbers.
#include<stdio.h>
long addition(long, long);
int main()
{
long first, second, sum;
scanf("%ld%ld", &first, &second);
sum = addition(first, second);
printf("%ld\n", sum);
return 0;
}
long addition(long a, long b)
{
long result;
result = a + b;
return result;
}
No comments:
Post a Comment